I am in the main activity. There is a Login button bLogin
. When it is pressed, a Logout button is displayed bLogout
. The onClick
methods for the two buttons are as follows:
bLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
llLogin.setVisibility(View.GONE);
llLogout.setVisibility(View.VISIBLE);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 327,
new Intent(getApplicationContext(), AlarmReceiver.class), PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);
}
});
bLogout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
llLogout.setVisibility(View.GONE);
llLogin.setVisibility(View.VISIBLE);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 327,
new Intent(getApplicationContext(), AlarmReceiver.class), PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
manager.cancel(pendingIntent);
boolean alarmUp = (PendingIntent.getBroadcast(getApplicationContext(), 327,
new Intent(getApplicationContext(), AlarmReceiver.class), PendingIntent.FLAG_NO_CREATE) != null);
if(!alarmUp){
Toast.makeText(getBaseContext(), "up", Toast.LENGTH_SHORT).show();
}
}
});
As can be seen in the code above, when bLogin
is pressed, I set the alarm, and when bLogout
is pressed, I cancel the alarm.
alarmUp
is used to check if the alarm is set. But the problem is that the alarm is never cancelled because the Toast
at the end is never displayed. Also, the work that should be done by the app when the alarm is not set is never done on pressing Logout.
I can't seem to figure out what might be wrong. The PendingIntent
s are the same for both when the alarm is set, and when it is cancelled.
Don't know what's wrong with your code, but if you want to cancel the pending intent you can use
to cancel the pending intent. I think it'll do the same think as cancelling your AlarmManager. Although you might need to change the way you check the way your alarm is set.
Hope this helps.