在特定时间段运行后台服务

时间:2017-06-19 09:53:08

标签: android

我想为10:00 AM to 8:00 PM运行服务类,我尝试使用AlarmManager,但它无法正常工作,我该怎么做?

任何人请帮助我。

    public void alrammanager(){

            Log.d(TAG, "onStartCommand");
            Toast.makeText(HomePage.this, "alarm manager start", Toast.LENGTH_LONG).show();
            alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
            Intent intent = new Intent(context, MyService.class);
            alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
            // Set the alarm to start at 8:30 a.m.

            calendar = Calendar.getInstance();
            calendar.setTimeInMillis(System.currentTimeMillis());
            calendar.set(Calendar.HOUR_OF_DAY, 10);
            calendar.set(Calendar.MINUTE, 00);

            // setRepeating() lets you specify a precise custom interval--in this case, // 20 minutes.
            int secondsreperts = 30;
            alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
            secondsreperts * 1000, alarmIntent);
}

1 个答案:

答案 0 :(得分:1)

尝试这种方式来运行服务。

Calendar calender = Calendar.getInstance();
int hourofday = calender.get(Calendar.HOUR_OF_DAY);    

    if (hourofday >10  && hourofday <20){    //between 10am. and 8pm.

        //start running services


    }
    else{

        //stop running services 10am. and 8pm.
    }