3

在我的应用程序中,我通过 json 格式的 post 方法将数据发送到服务器。在这里你可以看到我的代码。

JSONObject object1 = new JSONObject();
        object1.put("homesafe_events_version", "1.0");

        JSONObject object = new JSONObject();
        object.put("PhoneNumber", phoneNumber);
        object.put("EventTypeID", Integer.parseInt(eventTypeId));
        object.put("FreeFromText", "");
        object.put("EventTime", eventTime );
        object.put("Latitude", latitude);
        object.put("Longitude", longitude);
        object.put("Altitude", Double.parseDouble(df.format(altitude)));
        object.put("HorizAccuracy",Double.parseDouble(df.format(horizAccuracy)));
        object.put("VertAccuracy", vertiAccuracy);
        object.put("Speed", speed);
        object.put("Heading", Double.parseDouble(df.format(heading)));
        object.put("BatteryStatus", batteryStatus);

        object1.put("Event", object);

        String str = object1.toString();
        HttpClient client = new DefaultHttpClient();

        String encodedURL = URLEncoder.encode(str, "UTF-8");
        HttpPost request = new HttpPost(url);
        List<NameValuePair> value = new ArrayList<NameValuePair>();

        value.add(new BasicNameValuePair("Name", encodedURL));

        // UrlEncodedFormEntity entity=new UrlEncodedFormEntity(value);
        StringEntity entity = new StringEntity(str, "UTF8");
        request.setHeader("Content-Type", "application/json");
        request.setEntity(entity);

        HttpResponse response = client.execute(request);

        HttpEntity resEntity = response.getEntity();
        response_str = EntityUtils.toString(resEntity);

一切正常。我的应用程序中有一个按钮。单击该按钮时,会计算一些值并传入参数以将它们发送到服务器。现在假设互联网不可用,然后我按下该按钮 5 次在这种情况下,计算 5 次的所有值都存储在其他地方,当连接到来时,Web 服务将命中,所有数据都将发送到服务器。这是我的实际问题。请建议我该怎么做。提前致谢 !!

4

3 回答 3

3

您可以创建一个数据库并将这些值存储在那里。现在,在发送这些值之后,您必须将它们从数据库中删除。

现在,创建一个始终检查网络状态的广播类。当网络到来时,它将检查该数据库并将它们发送到服务器上。您可以相应地对其进行编码。

public class NetworkStatusChangeReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    boolean status = Utility.isInternetAvailable(context);
    if (!status)
    {
        Toast.makeText(context, "Network Error !", Toast.LENGTH_SHORT).show();
    }
 }
}

把它放在清单中。

    <receiver    
        android:name="NetworkStatusChangeReceiver"
        android:label="NetworkStatusChangeReceiver" >
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
        </intent-filter>
    </receiver>

这可能会有所帮助!!!!

于 2013-06-19T07:25:04.283 回答
2

将数据临时存储在SQLite 数据库共享首选项文件中怎么样?

你可以做这样的事情来检查连接是否可用

private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager 
          = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

我将创建一个Android 服务,每隔几秒/分钟在后台进行一次检查,如果连接可用,则进行发布。

于 2013-06-19T07:02:33.830 回答
0

我解决了这个案例:

1º 创建一种方法来保存要发布的数据,将位置留给状态列(已发送/未发送)。我使用了 SqlLite 数据库;

2º创建一个将发布数据的通信器类;

3º 创建一个 IntentService,它将检查数据库中是否有任何未发布的数据。

以下代码仅供参考:

    @Override
    protected void onStart() {
        super.onStart();

        //Start the IntentService
        Intent intent = new Intent(this, IntentService.class);
        startService(intent);
    }

//...

    private void sendData() {
            synchronized (this) {
                //Save the Data in local dataBase.
                DataToSend dataTosend = new DataToSend(foo, bar);
                dataTosend.save(context);
                //Pass the data to communicator
                communicator.sendData(dataTosend);
            }

        }

//Communicator.class

    public void sendData(DataToSend dataTosend) {
    //Code to send the Data to the server

    //POST Request successfully:
    dataTosend.setAsSent();

    //POST Request failure:
    dataTosend.setAsNotSent();
}

//IntentService.class

    //...

    private synchronized void sincroniza(String token) {
    //Check for dataTosend not yet send
    List<DataTosend> dataTosends = DataTosend.getNotSent(context);
    thatIsNotSentDataToSend = dataTosends.size() > 0;

    while (thatIsNotSentDataToSend) {

        synchronized (this) {
            try {
                for (DataTosend dataTosend :
                        dataTosends) {
                    //Send the data and mark as sent
                    communicator.sendData(dataToSend);

                    //If the comunicador send this data successfully, it will mark as sent (setAsSent() method).

                    //Clear the local DataBase
                    DataTosend.clearSentData(context);
                }
                //Verifies that there is still unsent Data
                dataTosends = DataToSend.getNotSent(context);
                thatIsNotSentDataToSend = (dataTosends.size() > 0);

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
于 2016-06-10T23:05:09.977 回答