在android中的服务中,每天在特定时间安排一次TimerTask

时间:2016-02-29 15:56:30

标签: android service timer android-service timertask

我有TimerTask个对象 timerTask 。我的代码正在运行,但是当服务最初启动时,我的计时器任务会在指定的时间(即下午3:30)之前立即运行,但我希望它仅在每天下午3:30运行一次。

Calendar cal = Calendar.getInstance();
cal.set(Calendar.AM_PM, Calendar.PM);
cal.set(Calendar.HOUR, 3);    
cal.set(Calendar.MINUTE, 30);
cal.set(Calendar.SECOND, 0);
Date date = cal.getTime();
timer.schedule(timerTask, date, 1000*60*60*24); // once per day

1 个答案:

答案 0 :(得分:2)

正如其他社区用户建议的那样,不要使用Timertask,android有一个 AlarmManager

你可以使用。

HOW?

  1. 使用广播接收器注册警报管理器,在那里覆盖onReceive方法(当alamr被触发时该怎么办)
  2. 使用每日间隔和要执行的时间设置警报。
  3. 这里是一个Snippet示例:

    public class MainActivity extends Activity {
    private static final String TAG ="MainActivity";
    PendingIntent myPendingIntent;
    AlarmManager alarmManager;
    BroadcastReceiver myBroadcastReceiver;
    Calendar firingCal;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Register AlarmManager Broadcast receive.
        firingCal= Calendar.getInstance();
        firingCal.set(Calendar.HOUR, 8); // At the hour you want to fire the alarm
        firingCal.set(Calendar.MINUTE, 0); // alarm minute 
        firingCal.set(Calendar.SECOND, 0); // and alarm second
        long intendedTime = firingCal.getTimeInMillis();
    
        registerMyAlarmBroadcast();
        alarmManager.set( AlarmManager.RTC_WAKEUP, intendedTime , AlarmManager.INTERVAL_DAY , myPendingIntent );
    }
    
    private void registerMyAlarmBroadcast()
    {
          Log.i(TAG, "Going to register Intent.RegisterAlramBroadcast");
    
        //This is the call back function(BroadcastReceiver) which will be call when your 
        //alarm time will reached.
        myBroadcastReceiver = new BroadcastReceiver()
        {
            @Override
            public void onReceive(Context context, Intent intent)
            {
                Log.i(TAG,"BroadcastReceiver::OnReceive()");
                Toast.makeText(context, "Your Alarm is there", Toast.LENGTH_LONG).show();
            }
        };
    
        registerReceiver(myBroadcastReceiver, new IntentFilter("com.alarm.example") );
        myPendingIntent = PendingIntent.getBroadcast( this, 0, new Intent("com.alarm.example"),0 );
        alarmManager = (AlarmManager)(this.getSystemService( Context.ALARM_SERVICE ));
    }
    private void UnregisterAlarmBroadcast()
    {
        alarmManager.cancel(myPendingIntent); 
        getBaseContext().unregisterReceiver(myBroadcastReceiver);
    }
    
    @Override
    protected void onDestroy() {
        unregisterReceiver(myBroadcastReceiver);
        super.onDestroy();
    }
    }
    

    编辑:

    如果可以根据用户输入在App中动态更改时间,则只需更改Calender firingCal变量以调整时间。