我有MainService,它调用BroadcastReceiver来监视电池的充电状态。
MainService:
public class MainService extends Service {
private static final String TAG = MainService.class.getName();
BroadcastReceiver broadcastReceiver = new BatteryChargingReceiver();
NotificationManagerCompat notificationManager;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG,"creating service");
registerReceiver(broadcastReceiver,new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
@Override
public void onDestroy() {
Log.d(TAG,"destroying service");
//notificationManager.cancelAll();
unregisterReceiver(broadcastReceiver);
super.onDestroy();
}
public static void startIfEnabled(Context context) {
SharedPreferences preferences = context.getSharedPreferences(Constants.PREFERENCES_FILE_NAME, 0);
boolean isEnabled = preferences.getBoolean(Constants.PREFERENCES_KEY_ENABLED, false);
Intent intent = new Intent(context, MainService.class);
if (isEnabled) {
context.startService(intent);
} else {
context.stopService(intent);
}
}
广播接收器:
public void onReceive(Context context, Intent intent) {
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
sharedPreferences = context.getSharedPreferences(Constants.PREFERENCES_FILE_NAME,0);
isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
status == BatteryManager.BATTERY_STATUS_FULL;
level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
boolean isEnabled = sharedPreferences.getBoolean(Constants.PREFERENCES_KEY_ENABLED,false);
Intent notifintent = new Intent(context,MainActivity.class);
notifintent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notifintent, 0);
if(intent != null){
final String action = intent.getAction();
if(Intent.ACTION_BATTERY_CHANGED.equals(action)){
if(isCharging && isEnabled){
alreadyNotified = true;
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.baseline_battery_full_black_24)
.setContentTitle("Battery Assistant")
.setContentText("Battery Percentage : "+level+"%")
.setOnlyAlertOnce(false)
.setContentIntent(pendingIntent)
.setCategory(NotificationCompat.CATEGORY_ALARM)
.setProgress(Constants.PROGRESS_MAX,level,false)
.setOngoing(true)
.setPriority(NotificationCompat.PRIORITY_HIGH);
notificationManager=NotificationManagerCompat.from(context);
notificationManager.notify(Constants.notificationId,builder.build());
if(level==100){
// Do some stuff
}
}
else{
if(alreadyNotified){
alreadyNotified = false;
notificationManager.cancel(Constants.notificationId);
}
Mainservice启动广播接收器,该接收器读取电池的充电状态和电池的充电水平。
因此,当手机处于充电状态时,会弹出通知。如果MainService在此状态下停止,则通知将保留在那里。我希望它在服务停止时被关闭。
我尝试在 MainService的 onDestroy 方法中调用 notificationmanager.cancel(id)或 notificationmanager.cancelAll()但它给出了致命的异常。 同样重要的是,调用BroadcastReceiver中的“通知”构建器以根据电池电量不断更新通知。
那么如何实现呢?