AlarmManager不是来自MainActivity

时间:2016-07-03 10:18:43

标签: java android android-intent alarmmanager android-pendingintent

当我在AlarmManager内创建MainActivity时,它可以正常工作。另一项活动在指定时间开始:

AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent = new Intent(MainActivity.this, AlarmActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, iterator, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP, key, pendingIntent);

但如果我这样做不是来自MainActivity,而是来自AlarmActivity类本身,那么在达到预定时间后,没有任何事情发生。

Intent intent = new Intent(**this**, AlarmActivity.class);

PendingIntent pendingIntent = PendingIntent.getActivity(**this**, ...);

问题最有可能出现在上下文中,但如果意图不是从MainActivity创建的,那么应该是什么情境?可能无法创建MainActivity,因为Alarm Activity可以在不启动主应用程序的情况下运行。我尝试使用thisAlarm Activity.this以及getApplicationContext()

更新
我在alarmActivity上有一个推迟按钮。当我按下它时警报正在更新,活动正在关闭。

public void hold(View view)
{
    long hold = 0;
    long currentTime = new Date().getTime();

    if (spinner.getSelectedItemPosition() == 0)
        //hold = 5 * 60 * 1000;
        hold = 5000; //for test
    else if (spinner.getSelectedItemPosition() == 1)
        hold = 10 * 60 * 1000;
    else if (spinner.getSelectedItemPosition() == 2)
        hold = 15 * 60 * 1000;
    else if (spinner.getSelectedItemPosition() == 3)
        hold = 30 * 60 * 1000;
    else if (spinner.getSelectedItemPosition() == 4)
        hold = 60 * 60 * 1000;

    currentTime += hold;

    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    Intent intent = new Intent(this, AlarmActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    alarmManager.set(AlarmManager.RTC_WAKEUP, currentTime, pendingIntent);

    this.finish();
}

1 个答案:

答案 0 :(得分:0)

首先在你的清单中,注册一个这样的接收者:

public class AlarmReciever extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {

    Print("intent "+intent.getAction());
    Log.d("Alarm ", "Alarm triggered!");



    Intent activityIntent = new Intent(context, ActivityToOpen.class).putExtra("byAlarm","yes");
    context.startActivity(activityIntent); //start



}

现在创建一个扩展广播接收器的类:

AlarmManager am = (AlarmManager)     DialerService.this.getSystemService(Context.ALARM_SERVICE);
    Print("inside scheduleAlarm  "+interval);
    logger.writeLog("inside schedule alarm and interval is "+interval);
    am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+oneHour*interval, getPendingIntent(yourContext,AlarmID));



 private PendingIntent getPendingIntent(Context context, int id) {
    Intent intent =  new Intent(context, AlarmReciever.class)
            .putExtra("alarmId", id);
    return PendingIntent.getBroadcast(context, id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}

}

以下是警报的代码:

{{1}}

在您的待定意图中,您必须提供AlarmReceiver类而不是您的活动。