首页 > 解决方案 > 临时存储 JSON 对象并在 Internet 可用时 POST 到 Volley

问题描述

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

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 可用,我可以将数据发布到服务器。但是如果 Internet 不可用,我需要将这个 JSON 对象临时存储在某个地方,当 Internet 可用时,我需要将所有 JSON 对象发布到本地存储的服务器。如何做到这一点?

标签: androidjsonrestandroid-volley

解决方案


为了实现这一点,您必须遵循这些步骤。

  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>

推荐阅读