【问题标题】:Android: setting new Alarm from onReceive methodAndroid:从 onReceive 方法设置新的警报
【发布时间】:2013-03-11 16:51:08
【问题描述】:

我的数据库中有一组提醒(按时间排序)。当我的应用程序启动时,我打电话给setAlarm。我需要在onReceive 方法中添加代码才能完成这些任务:

  1. 从我的数据库中获取第一个提醒
  2. 获取与提醒相关的延迟
  3. 安排新的闹钟以获取下一个提醒。

我创建了一个简单的 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?

【问题讨论】:

  • 你能详细解释一下它很难得到吗

标签: android service android-activity alarmmanager alarm


【解决方案1】:

您可以通过从上下文中访问广播接收器中的AlarmManager

AlarmManager alarmManager = (AlarmManager)arg0.getSystemService(Context.ALARM_SERVICE);

arg0 是你的上下文变量

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多