问题描述
我正在使用服务来管理wifi网络状态。只要应用程序正在运行,它就可以正常工作。但是,当应用关闭时,服务中的广播接收器将无法正常工作。
public class WifiService extends Service {
private class WifiReceiver extends broadcastReceiver{
String wifiNameN;
int wifiIdN;
@Override
public void onReceive(Context context,Intent intent) {
if(WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(intent.getAction())) {
NetworkInfo netInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
assert netInfo != null;
Log.i("SerSC","=State"+wifiName);
Log.i("SerSC","=State"+wifiId);
if(netInfo.getDetailedState().equals(NetworkInfo.DetailedState.CONNECTED)) {
Log.i("SerSC","=Connection");
} else if(netInfo.getDetailedState().equals(NetworkInfo.DetailedState.CONNECTING)) {
} else if(netInfo.getDetailedState().equals(NetworkInfo.DetailedState.disCONNECTING)) {
WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
assert wifiManager != null;
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
wifiInfo.getSSID();
wifiNameN = netInfo.getExtraInfo();
Log.i("SerSC","=D"+wifiNameN+"---"+wifiIdN);
wifiIdN = wifiInfo.getIpAddress();
} else if(netInfo.getDetailedState().equals(NetworkInfo.DetailedState.disCONNECTED)) {
if (wifiName.equals(wifiNameN) && wifiId == wifiIdN) {
Log.i("SerSC","=DC"+wifiNameN+"---"+wifiIdN);
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 5000 milliseconds
assert v != null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
v.vibrate(VibrationEffect.createOneshot(1000,VibrationEffect.DEFAULT_AMPLITUDE));
} else {
//deprecated in API 26
v.vibrate(1000);
}
// I want to show a notification on system window e.g like messenger chat head appears when message comes
}
}
}
}
}
private String wifiName;
private int wifiId;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
IntentFilter filter = new IntentFilter();
filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
registerReceiver(new WifiReceiver(),filter);
}
@Override
public int onStartCommand(Intent intent,int flags,int startId) {
Log.i("SerSC","Service Started");
if (intent != null) {
wifiName = intent.getStringExtra(MainActivity.WIFI_NAME_TAG);
wifiId = intent.getIntExtra(MainActivity.WIFI_NETWORK_TAG,-1);
}
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i("SerSC","Service Destroyed");
unregisterReceiver(new WifiReceiver());
}
}
这种情况还在起作用
if(netInfo.getDetailedState().equals(NetworkInfo.DetailedState.CONNECTED)) {
Log.i("SerSC","=Connection");
}
但是,当我关闭WIFI设备时,NetworkInfo.DetailedState.disCONNECTING和disCONNECTED无法正常工作。 我想在后台永久运行服务,即使应用未运行,也要监听网络状态。请不要提供链接。如果您决心帮助我,请写代码
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)