我知道如何在应用程序打开时使用活动检查互联网连接状态。但是当我的应用程序没有运行时,如何在服务中检查连接性呢?
您可能需要使用广播接收器。这样您就可以持续地接收连接状态的更新。(已连接/未连接)
示例:
清单文件:
权限:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
注册广播接收器:
<receiver android:name=".ConnectivityChangeReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
创建接收器类:
public class ConnectivityChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// Explicitly specify that which service class will handle the intent.
ComponentName comp = new ComponentName(context.getPackageName(),
YourService.class.getName());
intent.putExtra("isNetworkConnected",isConnected(context));
startService(context, (intent.setComponent(comp)));
}
public boolean isConnected(Context context) {
ConnectivityManager connectivityManager = ((ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE));
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isAvailable() && networkInfo.isConnected();
}
}
您的服务类:
class YourService extends IntentService{
@Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
boolean isNetworkConnected = extras.getBoolean("isNetworkConnected");
// your code
}
}
当网络连接状态改变时,系统会提供一个Broadcast
,您可以使用BroadcastReceiver
来读取。无论您的应用程序是打开还是关闭,此操作都将被调用。
public boolean isConnectingToInternet(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)
{
return true;
}
}
return false;
}