当互联网连接恢复时,通过邮件将数据发送到服务器

时间:2013-06-19 06:54:02

标签: android json parsing

在我的应用程序中,我通过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服务将会命中并且所有数据都将被发送到服务器。这是我的实际问题。请告诉我什么要做。谢谢!

3 个答案:

答案 0 :(得分: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>

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

答案 1 :(得分:2)

如何将数据暂时存储在SQLite databaseshared preferences file

您可以执行以下操作来检查连接是否可用

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

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

答案 2 :(得分:0)

我这样解决了这个案子:

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

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

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();
            }
        }

    }