我有一个应用程序,显示状态栏和通知栏中的电池电量和温度。打开应用程序后,我可以在状态栏和通知中看到数据更新。当我退出/关闭应用程序时,状态栏和通知不会更新其值。为什么关闭应用时状态栏和通知栏没有更新?
我使用BroadcastReceiver来显示通知。
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
notificationMessage(context, intent);
}
private void notificationMessage(Context context, Intent intent){
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
int icon = R.drawable.battery_level_images;
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
float cTemperature = (float) intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1)/10;
float fTemperature = celsiusToFahrenheit(cTemperature);
float voltage = (float) intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1)/1000;
int health = intent.getIntExtra(BatteryManager.EXTRA_HEALTH, -1);
String healthText = getHealthText(health);
Notification notification = new NotificationCompat.Builder(context)
.setContentTitle("" + level + "% | " + healthText)
.setContentText(cTemperature + "\u2103 | " + fTemperature + "\u2109 | " + voltage + "V")
.setSmallIcon(icon, level)
.setWhen(0)
.setProgress(100, level, false)
.setOngoing(true)
.setContentIntent(pendingIntent)
.build();
notificationManager.notify(0, notification);
}
在我的主要活动课程中,我使用复选框打开通知。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
............................
myReceiver = new MyReceiver();
ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
batteryStatus = this.registerReceiver(mBatteryInfoReceiver, ifilter);
....................
}
public void onToggleClicked(View view) {
// Is the toggle on?
boolean on = ((CheckBox) view).isChecked();
if (on) {
batteryStatus = this.registerReceiver(myReceiver, ifilter);
SavingData.setNotificationState(true);
} else {
try{
this.unregisterReceiver(myReceiver);
}catch (IllegalArgumentException iae){
iae.printStackTrace();
}
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancelAll();
SavingData.setNotificationState(false);
}
}
这是我的AndroidManifest中的BroadcastReceiver。
<receiver android:name=".MyReceiver" />
答案 0 :(得分:1)
在您的服务中注册BroadcastReceiver
并在后台运行。一直运行您的服务可能会耗尽用户的电量。当心:))
答案 1 :(得分:0)
一旦您的活动被销毁,通过BroadcastReceiver
注册的registerReceiver()
也会消失。您可能在LogCat中发出警告或错误,指出这一点。在BroadcastReceiver
消失后,您将停止更新Notification
。