android - 临时存储 JSON 对象并在 Internet 可用时 POST 到 Volley
问题描述
我Volley
在应用程序中使用。我正在使用REST
Api 向服务器发送数据。这是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 对象发布到本地存储的服务器。如何做到这一点?
解决方案
为了实现这一点,您必须遵循这些步骤。
- 检查互联网是否已连接。
- 如果互联网已连接,请发送呼叫。
- 如果未连接互联网,您可以将 Json 转换为字符串并将其保存在共享首选项或数据库中。
- 然后你必须创建一个广播接收器来检查互联网连接和
- 当您收到活动互联网的消息时,您需要将待处理的数据发送到服务器。
更新 用于创建广播接收器
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>
推荐阅读
- azure - 使用 Azure CLI 获取 Kubernetes 负载均衡器的公网 IP
- elasticsearch - Elasticsearch - 为多个字段计算有多少记录具有特定字段值
- flutter - 使用flutter和firestore创建文档ID时如何存储文档ID
- javascript - Selenium Python - 将Javascript提取为字符串
- google-analytics - 气流连接构建凭据
- python - 使用 Python 库“请求”,我可以成功登录使用 JSEncrypt 函数作为 id 和 pw 的站点登录页面吗?
- java - 为什么(int i=0;我
关于二维数组的嵌套for循环,为什么应该是(int i=0;i<cars.length;i++),而不是(int i=0;i<=cars.length;i++)?
公共类主要{
public static void mai
- windows - 无法从其他文件夹加载 SQLite 扩展
- python - 自定义 template.yaml 时,部署的 Lambda 中缺少 aws-sam-cli Python requirements.txt
- image - Google Lighthouse:使用错误的 SRCSET 图像