android – 需要在设备获得wifi /数据连接时运行服务
作者:互联网
上次,我使用以下编码来运行后台服务.
Intent intent = new Intent(InitActivity.this, GetService.class);
PendingIntent pintent = PendingIntent.getService(InitActivity.this, 0, intent, 0);
Calendar calendar = Calendar.getInstance();
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 50 * 1000, pintent);
return getZipInfo.toString();
为了获得更好的性能,我想在设备连接WIFI /数据连接后运行我的后台服务.要说清楚,如果设备没有连接wifi /数据连接,我的后台服务将无法运行.一旦连接wifi /数据连接,它将立即运行.
解决方法:
要检查WiFi连接,您可以使用此功能
ConnectivityManager connManager = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (mWifi.isConnected()) {
// Do whatever
}
要在连接Wifi时执行代码,您必须注册Brodcast Recevier
注册接收器
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
registerReceiver(broadcastReceiver, intentFilter);
在Receiver类中执行此操作
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION)) {
if (intent.getBooleanExtra(WifiManager.EXTRA_SUPPLICANT_CONNECTED, false)) {
//do stuff
} else {
// wifi connection was lost
}
}
如下所述,不要忘记在AndroidManifest.xml中添加权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
标签:android,service,android-wifi 来源: https://codeday.me/bug/20191008/1874416.html