AlarmManager 在多个设备中无法工作

我的应用程序使用 AlarmManager,它已经工作了4年了。但我注意到有些设备开始出现故障。

我非常肯定代码是正确的(我使用的是 Wakeful BroadcastReceiver,并且在带有 Doze 的设备上使用 setExactAndAllowWhileIdle) ,因为它在 Nexus 设备上运行得很好,但是在一些制造商的设备上(华为,小米...)却失败了。

例如,华为的设备有一种电池管理器,可以关闭应用程序,当一个应用程序被关闭时,预定的警报就会被取消。因此,在华为设置应用程序为“受保护”的电池管理器就解决了这个问题。

但是最近我注意到它并不适用于更多的设备,比如小米,三星(也许它和新的“智能管理器”有关?)似乎这种行为正在成为一种标准: 扼杀后台应用程序。

有人知道这件事吗? 有什么办法能确保警报响起吗?

编辑: 这个问题是由不同厂家添加的“电池节省器”引起的。更多信息请点击这里: https://dontkillmyapp.com/

17712 次浏览

most new phones nowadays are bundled with some kind of battery/power saving manager which do same thing you described. not counting duboosters and clean masters.

I think you need to put a disclaimer or faq in your app / play store listing stating that this app needs to be put into exception of your battery manager app in order to work properly.

I don't think killing the app will prevent the alarm manager from waking your app.

Its only when you "force stop" or disable the app you don't receive call backs from alarm manager.

The root cause might be something else.

Also on M... setExactAndAllowWhileIdle does throttling...that is if u schedule an alarm every 2 mins it won't be triggered. ..There needs to be 15 mins window. .

i stopped using AlarmManager a while ago... a better and more stable alternative

  1. create a service
  2. register a BroadcastReceiver for BOOT_COMPLETED
  3. fire your service from the receiver
  4. start a new Handler inside your service that loop itself every X minutes (Android - running a method periodically using postDelayed() call)
  5. check if time to execute the task has come: now - execution time > 0 (How to find the duration of difference between two dates in java?)
  6. if so.. execute the task and stop the handler

yes.. it's a pain..but the job get done NO MATTER WHAT

Are you listening for BOOT_COMPLETED? You need to set alarms again when a device is rebooted.

The issue is Smart Manager. Samsung has a battery manager which at times disables certain apps from running in background. It tried to "resume" when going back to the app but completely disables the application or may resume every 5 mins or so (depending how Samsung has it).

This would work on stock versions of android as there is no Samsung Manager. You can also install custom version of android which has some features to enable SM (depending on the rom).

What version of Android are these devices running?

As of API 23, the OS itself will go into a low-power idle mode when it's been unused for a while, and in that mode alarms will not be delivered. There is a way for apps to explicitly say "I need this alarm to go off at this time regardless of battery usage," however; the new AlarmManager methods called setAndAllowWhileIdle() and setExactAndAllowWhileIdle().

From your description it sounds like this might not be the particular cause of your issues on certain OEMs' devices, but this is something that all developers using the Alarm Manager ought to be aware of.

Finally, many usages of the Alarm Manager are better addressed using the Job Scheduler's mechanisms. For backwards compatibility the Play Services "GCM Network Manager" is actually very close to the Job Scheduler in functionality -- it uses the Job Scheduler internally on newer versions of Android -- and is not necessarily about networking, despite the class's name.

I also have an app that sets alarms.The solution is to use AlarmManager.setAlarmClock() on api >= 21. This is unaffected by doze afaik and has the added bonus of putting an alarm clock icon in the system tray.

Use AlarmManager for <5.0 devices, and JobScheduler for 5.0+ devices. I can't say for sure that JobScheduler will be unaffected by manufacturer shenanigans, but it would seem much less likely to me, given that Android is trying to move people away from AlarmManager and onto JobScheduler.

EDIT: Google has come out with a first-party solution to this problem called WorkManager. It abstracts multiple scheduling frameworks and uses the most appropriate one for the device.

For Xiaomi you may need to enable AutoStart for your app. I am trying do to a list of Android modifications(usually from phone's manufacturer) that may effect a background process. If you have something new please add an answer here List of Android task killers

I'm trying to solve it several weeks already. I found nothing. Huawei just kill all the alarms after some time. If I put the app to the protected app in their battery saver it does't help. But If I change package name of my app to contain words like alarm, clock or calendar, it works absolutely normal like on any other devices. I don't understand how Google can give certification for this crap. I think that OEM should not modify core platform in such way. I understand that they have own batter saver which kill the app after some time, when user don't use it. But this killing alarms also of protected apps.

Also setAlarmClock() for exact timing alarms helps. But it is not possible to use this for thinks like widget update.

Update: Protection by package name keywords is already not working on current Huawei devices, it was true in 2017.

We need to enable our app in autostart manager in app manager, some handsets like vivo v5,

In vivo v5, We can find out this menu in iManager-->App Manager--> Auto Start Manager. Enable our app here.

Then your alarm/ alarmmanager will trigger alarm if the app is killed or closed.

I were looking for an answer and after several hours I found this:

https://stackoverflow.com/a/35220476/3174791

In resume is way to know if your app was killed by 'Protected apps' and this only works on Huawei devices. let me know if there is any solution for other devices (Samsung,Sony,Xiaomi, etc).

Most of modern Android devices come with an app or mechanism, which automagically tries to figure out how to save battery and as a result might kill certain 3rd party apps. This might result in removing scheduled tasks and jobs, (e.g. alarms not going off, push notification not working, etc.). In many cases this happens completely independent from battery saving mechanisms of Android, in my case i couldn't make more battery optimization when i detect some devices model, i redirect user to the start up manager to whitelist my application

You found in this link for every model the intent that you should invoke https://android-arsenal.com/details/1/6771

This might be late but I hope it helps someone.

I was stuck on the same problem for so long. But now I konw how to solve this problem. This is for anyone who might have the same problem. People keep saying that you have to enable AutoStart but I managed to it with out using auto start.

First of all, WakeFullBroadcastaReceiver is now deprecated and you should use BroadcastReceiver. Second of all, you have to use the ForegroudService instead of BackgroundService.

I will give you the example in the following:

IntentService.class

public class NotificationService extends IntentService {




//In order to send notification when the app is close
//we use a foreground service, background service doesn't do the work.






public NotificationService() {
super("NotificationService");
}


@Override
public void onCreate() {
super.onCreate();


}


@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);


//There is no difference in the result between start_sticky or start_not_sticky at the moment
return START_NOT_STICKY;
}


@Override
protected void onHandleIntent(@Nullable Intent intent) {


//TODO check if the app is in foreground or not, we can use activity lifecyclecallbacks for this


startForegroundServiceT();
sendNotification(intent);
stopSelf();
}




/***
* you have to show the notification to the user when running foreground service
* otherwise it will throw an exception
*/
private void startForegroundServiceT(){


if (Build.VERSION.SDK_INT >= 26) {
String CHANNEL_ID = "my_channel_01";
NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);


((NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);


Notification notification = new Notification.Builder(this, CHANNEL_ID)
.setContentTitle("")
.setContentText("").build();


startForeground(1, notification);
}
}


private void sendNotification(Intent intent){


//Send notification
//Use notification channle for android O+
}
}

start the foreground service in BroadcastReceiver.class

public class AlarmReceiver extends BroadcastReceiver {




@Override
public void onReceive(Context context, Intent intent) {




Intent service = new Intent(context, NotificationService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(service);
} else {
context.startService(service);
}


}
}

And the setAlarms like this:

 public static void setAlarm(Context context, int requestCode, int hour, int minute){




AlarmManager alarmManager =( AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context//same activity should be used when canceling the alarm
, AlarmReceiver.class);
intent.setAction("android.intent.action.NOTIFY");


//setting FLAG_CANCEL_CURRENT makes some problems. and doest allow the cancelAlarm to work properly
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 1001, intent, 0);


Calendar time = getTime(hour, minute);


//set Alarm for different API levels
if (Build.VERSION.SDK_INT >= 23){
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,time.getTimeInMillis(),pendingIntent);
}
else{
alarmManager.set(AlarmManager.RTC_WAKEUP,time.getTimeInMillis(),pendingIntent);
}

Then you have to declare the receiver and the foregroundservice in the manifest.

       <receiver android:name=".AlarmReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.NOTIFY">


</action>
</intent-filter>
</receiver>
<service
android:name=".NotificationService"
android:enabled="true"
android:exported="true"></service>

I hope this helps some one.