使用AlarmManager将来执行特定任务

时间:2013-05-20 17:07:55

标签: java android broadcastreceiver alarmmanager toast

我是Android的新手,我将不胜感激。

我正在尝试使用警报管理器,以便在将来BroadcastReceiverDatePicker窗口小部件设置的特定时间调用我的TimePicker课程。

但是,我无法让broadcastreceiver类执行其功能。

下面是我放在manifestreceiver类的清单文件中以从OS接收广播消息的代码:

    <receiver android:name="androidapp.scheduler.MyBroadcastReceiver" >
        <intent-filter>
            <action android:name="android.intent.action.MYBROADCASTRECEIVER" >
            </action>
        </intent-filter>
    </receiver>

以下是我在下一个按钮的onclicklistener中放入的代码,以便告知操作系统通话的时间。

            TimePicker myTp = (TimePicker)findViewById(R.id.tpTime);
            cal.set(Calendar.YEAR,myDatePicker.getYear() );
            cal.set(Calendar.MONTH, myDatePicker.getMonth());
            cal.set(Calendar.DAY_OF_MONTH, myDatePicker.getDayOfMonth());
            cal.set(Calendar.HOUR, myTp.getCurrentHour());
            cal.set(Calendar.MINUTE, myTp.getCurrentMinute());
            cal.set(Calendar.SECOND, 0);

            Log.i("SCheduling", cal.getTime().toString());

            Intent intent = new Intent(Scheduling.this, MyBroadcastReceiver.class);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(Scheduling.this, 234324243, intent, 0);
            AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);

            Intent nextForm = new Intent(this,Sender.class);
            nextForm.putExtra("contacts", contacts);
            startActivity(nextForm);    
            Log.i("SCheduling", "everything set");

最后,MybroadcastReceivers类代码如下所示:

public class MyBroadcastReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i("brreceiver", "BroadcastReciever");
        Toast.makeText(context, "schedule set!.",
                Toast.LENGTH_LONG).show();
    }
}

我在这里缺少什么?

2 个答案:

答案 0 :(得分:0)

在以下语句中,将Scheduling.this更改为this.getApplicationContext()

PendingIntent pendingIntent = PendingIntent.getBroadcast(Scheduling.this, 234324243, intent, 0);

答案 1 :(得分:0)

似乎代码是正确的,问题在于模拟器。我仍然不知道模拟器出了什么问题,但我再次测试了代码并且它工作了,我确实收到了日志的输出。