我想在电池电量低时制作我的应用程序,例如从 6% 到 4% 在应用程序关闭时每 1 分钟推送一次通知
我是使用后台服务并使用 BrodcastReceiver 和许多其他东西但都告诉我警报管理器将与我的应用程序一起工作,因为它在后台工作
我希望应用程序在用户下载应用程序时在后台运行以使应用程序监听电池电量并且当电池电量为 6% 到 4% 时每 1 分钟推送一次通知工作管理器通知
public class NotificationWork extends Worker {
private static final String WORK_RESULT = "work_result";
public NotificationWork(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams);
}
@NonNull
@Override
public Result doWork() {
showNotification();
return Result.success();
}
private void showNotification() {
NotificationManager manager = (NotificationManager) getApplicationContext().getSystemService(
Context.NOTIFICATION_SERVICE);
String channelId = "task_channel";
String channelName = "task_name";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new
NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_DEFAULT);
manager.createNotificationChannel(channel);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), channelId)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentText("text")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
// Set the intent that will fire when the user taps the notification
.setAutoCancel(true);
manager.notify(1, builder.build());
}
}
和开始工作的方法管理器
private void startWorkManager() {
Constraints constraints = new Constraints.Builder()
.setRequiresBatteryNotLow(true)
.build();
PeriodicWorkRequest periodicWorkRequest= new
PeriodicWorkRequest.Builder(NotificationWork.class , 15 , TimeUnit.MINUTES)
.build();
WorkManager.getInstance().enqueue(periodicWorkRequest);
}