Android How to stop AlarmManager in other Activity

我的未来我决定 提交于 2019-12-07 15:03:40

问题


I am using a service which is called in Activity 'A' repeatedly created by AlarmManager. My service is checking repeatedly response from server, when response is true new Activity B is started. Now when activity B is started i want to stop service as well as AlarmManager. how can i do this??

my 'A' activity code for calling service is following

    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.SECOND, 40);

    Intent intent = new Intent(this, response.class);

    // Add extras to the bundle
    intent.putExtra("foo", "bar");
    // Start the service
    // startService(intent);

    pintent = PendingIntent.getService(this, 0, intent, 0);

    alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    int i;
    i = 15;
    alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
            i * 1000, pintent);

    startService(intent);

I have also tried this code snippet in Activity 'B' to stop AlarmManager but fail

      Intent sintent = new Intent(this, response.class);
     pintent = PendingIntent.getService(this, 0, sintent, 0);
     alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
     stopService(sintent);
     alarm.cancel(pintent);

回答1:


In Activity B you should create sIntent with the same context as you created it in Activity A.

So in Activity A I would add this

private static Context context;

public static Context getAppContext(){
    return ActivityA.context;
}

and inside onCreate() method of Activity A, initialize context

context=getApplicationContext();

And in Activity B create sIntent like this:

Intent intent = new Intent(ActivityA.getAppContext(), ServiceClass.class);
intent.putExtra("fsasf", "bar");
PendingIntent pintent = PendingIntent.getService(this, 0, intent, 0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
stopService(intent);
alarm.cancel(pintent);


来源:https://stackoverflow.com/questions/27015294/android-how-to-stop-alarmmanager-in-other-activity

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