Android: how to schedule an alarmmanager broadcast event that will be called even if my application is closed?

烈酒焚心 提交于 2019-12-18 07:07:03

问题


My app needs to execute a specific task every hour. It does not matter if app is runing, suspended, or even closed.

When app is running or suspended, I can do it by just scheduling an AlarmManager broadcastreceiver. But when the application is closed, I have to call "unregisterReceiver" to not leak an intent, and app will never be wake up (or something) to process the task.

Then, the question is: how to schedule an alarmmanager task that I don't need to unregister, so it will be called even if my application is closed?


回答1:


Use AlarmManager.setRepeating(int type, long triggerAtTime, long interval, PendingIntent operation) for this. Set the type to AlarmManager.RTC_WAKEUP to make sure that the device is woken up if it is sleeping (if that is your requirement).

Something like this:

    Intent intent = new Intent("com.foo.android.MY_TIMER");
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
    AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
    long now = System.currentTimeMillis();
    long interval = 60 * 60 * 1000; // 1 hour
    manager.setRepeating(AlarmManager.RTC_WAKEUP, now + interval, interval,
        pendingIntent); // Schedule timer for one hour from now and every hour after that

You pass a PendingIntent to this method. You don't need to worry about leaking Intents.

Remember to turn the alarm off by calling AlarmManager.cancel() when you don't need it anymore.

Don't register a Receiver in code for this. Just add an <intent-filter> tag to the manifest entry for your BroadcastReceiver, like this:

    <receiver android:name=".MyReceiver">
        <intent-filter>
            <action
                    android:name="com.foo.android.MY_TIMER"/>
        </intent-filter>
    </receiver>



回答2:


You need to user an Android Component Called Service for this. From the service code you can schedule your Task using the AlarmManager with PendingIntent Class for every hours. As your AlarmManger is declared in the Service Components it doesn't require any GUI and will get execute in background, till you have battery in your device.



来源:https://stackoverflow.com/questions/10818313/android-how-to-schedule-an-alarmmanager-broadcast-event-that-will-be-called-eve

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!