0

我正在开发一个安排发送消息的 Android 应用程序。我正在使用警报管理器。我的主要部分代码如下:

mConfirm.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        Intent intent = 
            new Intent(getApplicationContext(),MyNotificationService.class);

        mMessage = mEditTextMessage.getText().toString();
        mNumber = mEditTextNumber.getText().toString();
        c.set(mYear, mMonth, mDay);
        c.set(Calendar.HOUR_OF_DAY, mHour);
        c.set(Calendar.MINUTE, mMinutes);

        Bundle bundle = new Bundle();
        bundle.putCharSequence("number", mNumber);
        bundle.putCharSequence("message", mMessage);
        intent.putExtras(bundle);

        AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
        PendingIntent pendingIntent = 
            PendingIntent.getService(getApplicationContext(), 0, intent, 0);
        alarmManager.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), 
            pendingIntent);
    }
});

我应该如何实现 MyNotificationService 类,以便它在设定的时间发送消息?该类应该是服务还是广播接收器?

4

2 回答 2

2

下面的代码将允许您每 5 秒调用一次广播接收器。您可以使用 set() 或 setTimeZone() 方法在特定时间进行设置。

AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
intent.putExtra("abc", Boolean.FALSE);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
//After after 5 seconds
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 5 , pi);

AlarmManagerBroadcastReceiver 类是一个广播器。

于 2013-05-01T13:57:00.037 回答
1

您可以使用广播接收器从意图接收消息。您可以创建一个接收器类,您可以在其中接收消息。

Intent intent=new Intent(MyReceiver.ACTION_REFRESH_ALARM);
pendingIntent=PendingIntent.getBroadcast(this, 0, intent, 0);
alarmManager=(AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,0,pendingIntent);

public class MyReceiver extends BroadcastReceiver
{

   public static final String ACTION_REFRESH_ALARM ="com.paad.network.ACTION_REFRESH_ALARM";

@Override
public void onReceive(Context context, Intent intent) {

             //Extract Messages
}}
于 2013-05-01T14:00:29.867 回答