我正在开发一款必须在后台执行2项定期任务的Android应用程序:
我该怎么做?
答案 0 :(得分:3)
首先,您需要使用 AlarmManager 。当注册的警报例如24小时的情况下,将触发,您可以从AlarmManager的广播接收器呼叫服务。如果你还不知道,你需要研究一下AlarmManager。如需进一步的帮助,您可以从下面的代码中获得一些想法:
Calendar cur_cal = new GregorianCalendar();
cur_cal.setTimeInMillis(System.currentTimeMillis());
Calendar cal = new GregorianCalendar();
cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR) + 1); //+1 For Next day (24 hours or so...)
cal.set(Calendar.HOUR_OF_DAY, hour);
cal.set(Calendar.MINUTE, minute);
cal.set(Calendar.SECOND, cur_cal.get(Calendar.SECOND));
cal.set(Calendar.MILLISECOND, cur_cal.get(Calendar.MILLISECOND));
cal.set(Calendar.DATE, cur_cal.get(Calendar.DATE));
cal.set(Calendar.MONTH, cur_cal.get(Calendar.MONTH));
AlarmManager am = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(getApplicationContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, PendingIntent.FLAG_ONE_SHOT);
am.cancel(pendingIntent);
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);
以下是设置闹钟的方法。现在,当触发警报时,您将按照以下方式致电您的服务:
public class AlarmReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context arg0, Intent arg1)
{
// Call you service or any task here
}
}
最后,请不要忘记在AndroidManifest.xml中提及您的广播接收器和服务
<receiver android:name=".AlarmReceiver">
</receiver>
<service android:name=".MyService"/>
答案 1 :(得分:0)
以下是关于AlarmManager
的官方Android文档Note: The Alarm Manager is intended for cases where you want to have
your application code run at a specific time, even if your application
is not currently running. For normal timing operations (ticks, timeouts, etc)
it is easier and much more efficient to use Handler.
Handler文档。