0
我有這個廣播接收器獲取並保持有關電池的最新信息。有關電池的信息很好地工作,在無需重新創建活動的情況下進行更新,而WiFi沒有。例如,如果我禁用WiFi,則不會更改首選項摘要(並且應該)。爲什麼?我該如何解決?這是代碼。廣播接收器:爲什麼它不起作用?
@Override
protected void onStop()
{
unregisterReceiver(batteryInfoReceiver);
super.onStop();
}
@Override
protected void onRestart()
{
this.registerReceiver(this.batteryInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
super.onRestart();
}
private BroadcastReceiver batteryInfoReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
WifiManager wifiMgr = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
int level= intent.getIntExtra(BatteryManager.EXTRA_LEVEL,0);
String technology= intent.getExtras().getString(BatteryManager.EXTRA_TECHNOLOGY);
int temperature= intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE,0)/10;
int voltage= intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE,0);
int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
if (sdkVersion < Build.VERSION_CODES.JELLY_BEAN_MR1) {
boolean wCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_WIRELESS;
if(wCharge) {
ricarica.setSummary("Charging (WiFi)");
}
}
if(usbCharge) {
ricarica.setSummary("Charging (USB)");
}
else if (acCharge){
ricarica.setSummary("Charging (AC)");
}
else {
ricarica.setSummary("Not charging");
}
livelloBatteria.setSummary("Battery at "+level+"%");
livelloVoltaggio.setSummary(voltage+" mV");
livelloTemperatura.setSummary(Integer.toString(temperature)+"° Celsius");
tecnologia.setSummary(technology);
int ip = wifiInfo.getIpAddress();
int speed = wifiInfo.getLinkSpeed();
String speedString = Integer.toString(speed);
String mac = wifiInfo.getMacAddress();
String ssid = wifiInfo.getSSID();
String ipAddress = Formatter.formatIpAddress(ip);
if (wifiMgr.isWifiEnabled()){
if(mac!=null) {
indirizzoMac.setSummary(mac);
}
else {
indirizzoMac.setSummary("Unkown");
}
if(ipAddress!=null) {
indirizzoIp.setSummary(ipAddress);
}
else {
indirizzoIp.setSummary("Unkown");
}
if(ssid!=null) {
indirizzoSsid.setSummary(ssid);
}
else {
indirizzoSsid.setSummary("Unkown");
}
if(speedString!=null) {
velocità.setSummary(speedString+" Mbps");
}
else {
velocità.setSummary("Unkown");
}
}
else {
indirizzoIp.setSummary("WiFi disabled");
indirizzoSsid.setSummary("WiFi disabled");
velocità.setSummary("WIFi disabled");
indirizzoMac.setSummary(mac);
}
}
};
您可以發佈清單嗎?你有沒有正確設置意圖過濾器捕獲連接事件? – SuppressWarnings
你已經在Manifest中用正確的意圖過濾器註冊了您的BroadcastReceiver? –