我想在特定时间安排任务在不同的日子(星期一,星期二等)在android

时间:2012-06-22 06:57:22

标签: android broadcastreceiver scheduled-tasks alarmmanager

目前我正在开发 BroadcastReceiver,Service& Android中的AlarmManager 开发了我项目中的一项功能。我需要在特定日期的特定时间安排一些任务。

例如: -

周一 - 上午9:00& 05:00 PM

周二 - 上午9:00& 05:00 PM

周三 - 上午9:00& 05:00 PM

周四 - 上午9:00& 05:00 PM

周五 - 上午9:00& 05:00 PM

周六 - 上午10:00&晚上10点

周日 - 上午10:00&晚上10点


到目前为止我所做的是创造了一项活动&广播接收器。点击按钮后,每隔60秒广播接收器将被调用。这是我的代码片段。但是我想按照上面描述的那个周安排我的任务。任何人都可以请帮助我如何安排上述任务。

代码: -

public class AlarmDemoActivity extends Activity {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button buttonStart = (Button)findViewById(R.id.start);
        buttonStart.setOnClickListener(new Button.OnClickListener(){

            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                Intent myIntent = new Intent(getBaseContext(),
                        MyScheduledReceiver.class);

                PendingIntent pendingIntent
                = PendingIntent.getBroadcast(getBaseContext(),
                        0, myIntent, 0);

                AlarmManager alarmManager
                = (AlarmManager)getSystemService(ALARM_SERVICE);
                Calendar calendar = Calendar.getInstance();
                calendar.setTimeInMillis(System.currentTimeMillis());
                calendar.add(Calendar.SECOND, 10);
                long interval = 60 * 1000; //
                alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                        calendar.getTimeInMillis(), interval, pendingIntent);
                finish();
            }});
    }
}

BroadcastReceiver: -

public class MyScheduledReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        /*Intent scheduledIntent = new Intent(context, MyScheduledActivity.class);
        scheduledIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(scheduledIntent);*/

        System.out.println("Make Phone Silent");
    }

}

欢迎所有建议和提示。

2 个答案:

答案 0 :(得分:3)

我会在很高的层次上提出这个想法。你必须弄清楚自己的编码:

1.在共享偏好设置中保存用户首选项(我认为你已经在做了)

2.使用Alarm Manager的设置方法安排第一个警报 Refer this for details on this method

3.当闹钟响起时,再次使用set方法,使用共享首选项中的下一个时间段再次安排下一个闹钟

答案 1 :(得分:1)

您不需要每60秒调用一次,您可以设置使用日历实例触发警报并设置正确日期的时间,以便警报管理器在指定日期触发广播意图次。

请注意,如果手机已关闭,则会重置警报管理器,因此您必须将警报存储在任何持久存储中,并为BOOT_COMPLETED操作注册广播接收器以恢复警报。

您可以小间隔进行测试,这样您就不必等待一整天:)