我有这个广播接收器,可以获取并保持有关电池的最新信息。有关电池的信息很好,从某种意义上说,它们是更新而无需重新创建活动,而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);
}
}
};
答案 0 :(得分:1)
我认为你的接收器没有注册wifi连接更改尝试添加另一个过滤器:
IntentFilter filter= new IntentFilter();
filter.addAction(Intent.ACTION_BATTERY_CHANGED);
filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
this.registerReceiver(this.batteryInfoReceiver,filter);
您还可以添加连接更改操作进行过滤,以便在网络连接发生变化时调用onReceive:
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);