如何使用AlarmManager在android中以指定的时间间隔运行某些任务?

Che*_*tty 0 android alarmmanager

您好stackoverflow我正在尝试开发一个可以在特定时间间隔运行某些任务的Android应用程序,我正在使用AlarmManager该任务,代码片段如下,

if (radioBtnChecked)
{   
     MyActivity.this.alarmMgr = (AlarmManager) MyActivity.this.getSystemService(Context.ALARM_SERVICE);
     Intent serviceIntent = new Intent(MyActivity.this, MyService.class);
     MyActivity.this.pi = PendingIntent.getService(MyActivity.this, 0, serviceIntent, 0);
     MyActivity.this.alarmMgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), 10000, pi);

 }//End of if condition
Run Code Online (Sandbox Code Playgroud)

MyService.java

public class MyService extends Service 
{
    @Override
    public IBinder onBind(Intent intent) 
    {
        return null;
    }//End of onBind method

    public void onStart(Intent intent, int startId) 
    {
        super.onStart(intent, startId);
        Toast.makeText(getApplicationContext(),"Service started", Toast.LENGTH_SHORT).show();
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是Service started当我单击单选按钮时第一次显示该消息,但是我想在Service started之后显示消息10 seconds.请有人帮我解决这个问题,请分享你的知识,以便我能纠正我的错误.

提前致谢.

ssw*_*zek 5

像这样设置AlarmManager:

private static final int REPEAT_TIME_IN_SECONDS = 60; //repeat every 60 seconds

AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

alarmManager.setRepeating(AlarmManager.RTC, System.currentTimeMillis(),
            REPEAT_TIME_IN_SECONDS * 1000, pendingIntent);
Run Code Online (Sandbox Code Playgroud)

如果您想要在电话关闭时唤醒电话,请更改AlarmManager.RTCAlarmManager.RTC_WAKEUP.更多关于AlarmManager的信息

这两个参数也意味着您的闹钟时间将是System.currentTimeMilis()UTC时间.

编辑:

您的解决方案AlarmManager.ELAPSED_REALTIME用于测量设备启动后的时间,包括睡眠.这意味着如果您希望在10秒后运行此代码,然后想要重复它并且您的设备运行的时间超过此值,PendingIntent将立即触发,因为过去启动后10秒.

编辑2:

如果你想在10秒后只运行一次代码,试试这个:

private static final int START_AFTER_SECONDS = 10;
...
if (radioBtnChecked)
{ 
    Runnable mRunnable;
    Handler mHandler = new Handler();
    mRunnable = new Runnable() {
        @Override
        public void run() {
            Intent serviceIntent = new Intent(MyActivity.this, MyService.class);
            MyActivity.this.startService(serviceIntent);
        }
    };
    mHandler.postDelayed(mRunnable, START_AFTER_SECONDS * 1000);
}
Run Code Online (Sandbox Code Playgroud)