我正在用 Java 为 Android 创建一个应用程序。我可以将信息发送到网络服务,但是当我离线时我想存储信息并且当手机连接到互联网时我想将其发送到网络服务。
谁能帮我?
谢谢
最佳答案
public void onReceive(Context context, Intent intent) {
String s = intent.getAction();
if (s.equals("android.net.conn.CONNECTIVITY_CHANGE")) {
if (IsNetworkAvailable(context)) {
// update your online data-base and delete all rows from SQlite
}
return;
}
}
方法是网络可用:
public static boolean isNetworkAvailable(Context mContext) {
Context context = mContext.getApplicationContext();
ConnectivityManager connectivity = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
return false;
} else {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED){
return true;
}
}
}
}
return false;
}
您还需要权限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
关于java - 如何在我的 Android 应用程序中离线时保存数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34497864/