Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
494 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...