How can I get the context of other activity?

拥有回忆 提交于 2019-12-25 05:13:57

问题


I'm working on the alarm app, and have trouble removing an existing alarm. I have to create the same pending intent to remove the alarm in the activity which lists all alarms in my app, but It doesn't work as I expected. I want to get the "Context" from the activity which I used to add an alarm.

Here is the code to add an alarm from ListAddActivity.

private void addAlarm()
{
    final int ALARM_CODE = this.getAlarmCode(1);
    final int HOUR_OF_DAY = vo.getHour1();
    final int MINUTE = vo.getMinute1();

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

    Calendar calendar = CalendarCreator.getCalendar(HOUR_OF_DAY, MINUTE);
    Intent intent = new Intent(ListAddActivity.this, PushMainActivity.class);

    PendingIntent pendingIntent = PendingIntent.getActivity(
            ListAddActivity.this, ALARM_CODE, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
            calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY,
            pendingIntent);
}

Here is the code to remove an scheduled alarm from ListMainActivity.

private void removeAlarm(int number)
{
    final int alarmCode = AlarmCodeCreator.CreateNum(1, clickedPosition, 0);
    System.out.println(alarmCode);
    AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(getApplicationContext(),
            PushMainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(
            getApplicationContext(), alarmCode, intent, 
            PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.cancel(pendingIntent);
}

As you can see, I made my own algorithm to create an alarmCode, so I can retrieve it, and had the same flag, too. However, getting the same "Context" is the one that I'm struggling with.


回答1:


This has nothing to do with contexts. The intent you schedule was created with getActivity. That is a different kind of intent than the one created with getBroadcast. You cannot use the latter to cancel the former.

(Edited to add code)

Intent intent = new Intent(
    getApplicationContext(),
    PushMainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
    ListAddActivity.this,
    ALARM_CODE,
    intent,
    PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.cancel(pendingIntent);


来源:https://stackoverflow.com/questions/22270231/how-can-i-get-the-context-of-other-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!