临时存储 JSON 个对象,并在 Internet 可用时将 POST 存储到 Volley

Store JSON object temporarily and POST to Volley when Internet is available

我在应用程序中使用 Volley。我正在使用 REST Api 向服务器发送数据。这是对服务器的 JSON POST 请求。

private void add() {
        String NetworkStatus = biz.fyra.bookapp.utils.NetworkStatus.checkConnection(getContext());
        if (NetworkStatus.equals("false")) {
            alert.noInternetAlert(getActivity());
        } else {
            JSONObject info = new JSONObject();
            try {
                info.put("name", full_name);
                info.put("phone", foodie_contact);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, ApiUrls.ADD, info, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                }
            }) {
            };
            AppController.getInstance().addToRequestQueue(request);
        }
    }  

如果 Internet 可用,我可以 POST 将数据发送到服务器。但是如果 Internet 不可用,我需要将这个 JSON 对象临时存储在某个地方,当 Internet 可用时,我需要 POST 所有 JSON 对象到本地存储的服务器。如何实现?

要实现此目标,您必须执行以下步骤。

  1. 检查是否已连接互联网。
  2. 如果互联网已连接,请拨打电话。
  3. 如果未连接互联网,您可以将 Json 转换为字符串并保存 在共享首选项或数据库中。
  4. 然后你必须创建一个广播接收器来检查互联网连接和
  5. 当您收到活动互联网的消息时,您需要发送待处理数据 到服务器。

更新 用于创建广播​​接收器

public class NetworkChangeReceiver extends BroadcastReceiver {

@Override
public void onReceive(final Context context, final Intent intent) {
    final ConnectivityManager connMgr = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);

    final android.net.NetworkInfo wifi = connMgr
            .getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    final android.net.NetworkInfo mobile = connMgr
            .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

    if (wifi.isAvailable() || mobile.isAvailable()) {
        Log.d("Network Available ", "Flag No 1");
    }
}

}

然后在 Menifest 文件中的 Application 标签中添加 Intent Filter

<receiver android:name=".NetworkChangeReceiver" >
    <intent-filter>
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
    </intent-filter>
</receiver>