【发布时间】:2012-05-11 05:18:44
【问题描述】:
我知道如何在活动中检查互联网是否可用,我的要求是,实际上我在设备离线(没有互联网)时将一些值存储在 DB 中,当涉及到在线时必须传递 DB 值到没有用户交互的服务器。我怎么能做到这一点。 我得到了这个例子How to check the Internet Connection periodically in whole application?,但它只适用于一项活动,如何使它成为全球性的。
【问题讨论】:
我知道如何在活动中检查互联网是否可用,我的要求是,实际上我在设备离线(没有互联网)时将一些值存储在 DB 中,当涉及到在线时必须传递 DB 值到没有用户交互的服务器。我怎么能做到这一点。 我得到了这个例子How to check the Internet Connection periodically in whole application?,但它只适用于一项活动,如何使它成为全球性的。
【问题讨论】:
在你的接收器中使用它
<receiver android:name=".UpdateReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
您的更新接收者
public class UpdateReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connectivityManager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE );
NetworkInfo activeNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
boolean isConnected = activeNetInfo != null && activeNetInfo.isConnectedOrConnecting();
if (isConnected)
Log.i("NET", "connecte" +isConnected);
else Log.i("NET", "not connecte" +isConnected);
}
}
【讨论】:
试试这个功能
public static boolean isInternetAvailable(Context context) {
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
在清单中
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
享受..
【讨论】: