Android:从onReceive方法设置新的警报

时间:2013-03-11 16:51:09

标签: android service android-activity alarmmanager alarm

我的数据库中有一组提醒(按时间排序)。当我的申请开始时,我致电setAlarm。我需要在onReceive方法中添加代码才能执行以下任务:

  1. 从我的数据库中获取第一个提醒
  2. 获取与提醒相关的延迟
  3. 安排新的闹钟以获取下一个提醒。
  4. 我创建了一个简单的BroadcastReceiver类:

    public class AlarmReceiver extends BroadcastReceiver{
        private static final String DEBUG_TAG= "AlarmReceiver";
    
        public void onReceive(Context arg0, Intent arg1) {
            // TODO Auto-generated method stub
            Log.d(DEBUG_TAG,"ALARM!!!");
                // --mycode--
        }
    }
    

    和Activity类:

    public class AlarmActivity extends Activity {
    
        private Context context;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main_layout);
            context = getApplicationContext();
        }
    
    
        public void setAlarm(View v){
            Intent intent = new Intent(this,AlarmReceiver.class);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
            AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
            alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+ Delay,pendingIntent);
            Log.i("SETTER","Alarm started");
    
        }
    
        public void stopAlarm(View v){
            Intent intent = new Intent(this,AlarmReceiver.class);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
            pendingIntent.cancel();
        }
    }
    

    现在,我希望在--mycode--部分中,从数据库中获取新的延迟(如果存在),并使用此新延迟设置新的警报。 如何从onReceive方法设置新的AlarmManager?

1 个答案:

答案 0 :(得分:2)

您可以通过从上下文访问

在广播接收器中获取AlarmManager
AlarmManager alarmManager = (AlarmManager)arg0.getSystemService(Context.ALARM_SERVICE);

其中arg0是您的上下文变量