使用 android 上的服务检查互联网连接 [英] Checking internet connection with service on android
本文介绍了使用 android 上的服务检查互联网连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我的应用程序使用活动打开时,我知道如何检查互联网连接.但是如何在我的应用未运行时检查服务中的连接?
I know how to check for internet connectivity when my app is open using activity. But how to check for connectivity in service when my app is not running?
推荐答案
您可能需要使用广播接收器.您将不断收到连接更新.(已连接/已断开连接)
You might need to use broadcast receiver. You will continuously receive updates in connectivity.(Connected/Disconnected)
示例:
清单:
权限:
<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
}
}
这篇关于使用 android 上的服务检查互联网连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文