Android How to stop AlarmManager in another activity

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

My "A" code for calling the service is as follows

    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 also tried this piece of code in Activity 'B' to stop AlarmManager but it fails

      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);

      

+3


source to share


1 answer


In Activity B, you must create an sIntent with the same context that you created in Activity A.

So, in Activity A, I would add this

private static Context context;

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

      

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



context=getApplicationContext();

      

And in Activity B, create an 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);

      

+2


source







All Articles