[英]Broadcast Receiver: Why it doesn't work?
我有这个广播接收器,它可以获取并保持有关电池的最新信息。 有关电池的信息运作良好,从某种意义上来说,无需重新创建活动即可更新电池,而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);
}
}
};
我认为您的接收器尚未注册以进行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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.