问题
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