我想创建一个应用程序,用户可以通过简单的表单提交他的信息。现在,如果用户没有连接到互联网,那么它应该缓存数据,每当用户连接到互联网时,就会开始上传该数据,而不会通知用户。
任何帮助?
答案 0 :(得分:0)
使用此Receiver,它将帮助您在设备在线时提交表单
public class NetworkChangeReceiver extends BroadcastReceiver{
private static final String LOG_TAG = "NetworkChangeReceiver";
private boolean isConnected = false;
@Override
public void onReceive(Context context, Intent intent) {
Log.v(LOG_TAG, "Receieved notification about network status");
isNetworkAvailable(context);
}
private boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
if (!isConnected) {
Log.v(LOG_TAG, "Now you are connected to Internet!");
Toast.makeText(context, "Internet available via Broadcast receiver", Toast.LENGTH_SHORT).show();
isConnected = true;
// do your processing here ---
// if you need to post or get any data to the server
}
return true;
}
}
}
}
Log.v(LOG_TAG, "You are not connected to Internet!");
isConnected = false;
return false;
}
}
让我知道它是否适用于您或此处的任何其他问题。
答案 1 :(得分:0)
您可以创建可以捕获网络更改并启动上传服务的BroadcastReceiver
:
public class NetworkReceiver extends BroadcastReceiver {
public static final String EXTRA_DATA_NAME_NETWORK_CONNECTED = "my.package.name.NetworkConnected";
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ConnectivityManager.CONNECTIVITY_ACTION.equals(action)) {
Intent serviceIntent = new Intent(UploadService.ACTION_NETWORK_STATUS, null, context, UploadService.class);
serviceIntent.putExtra(EXTRA_DATA_NAME_NETWORK_CONNECTED, isNetworkConnected(context));
context.startService(serviceIntent);
}
}
}
网络连接方法:
public static boolean isNetworkConnected(Context context) {
ConnectivityManager conn = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = conn.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected();
}