问题
Can anyone tell me how can I stop this alarm?
I'm trying to stop it by using a handler but it didn't stop it continues to repeat?
Here's my code:
//=================================== After Updating =================================
Button bStart, bStop ;
long mCurrentTime;
Calendar calendar;
TextView tv;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bStart = (Button) findViewById (R.id.button1);
bStop = (Button) findViewById (R.id.button2);
tv = (TextView) findViewById (R.id.textView1);
final Intent intent = new Intent(AlarmNewActivity.this, RepeatingAlarm.class);
final PendingIntent sender = PendingIntent.getBroadcast(AlarmNewActivity.this, 0, intent, 0);
final AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
bStart.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
mCurrentTime = calendar.getTimeInMillis();
//tv.setText(""+ mCurrentTime );
new Handler().postDelayed(new Runnable() {
public void run() {
bStop.performClick();
tv.setText(""+ mCurrentTime );
}
}, ( mCurrentTime + 30 * 1000 ));
am.setRepeating(AlarmManager.RTC_WAKEUP,
mCurrentTime + 10 *1000, 5*1000, sender);
}
});
//==================================================================================
bStop.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
am.cancel(sender);
}
});
}
}
回答1:
Hi you can use the following command passing your pending intent:
am.cancel(yourPendingIntent);
I have written a good tutorial on AlarmManager some months ago that you can find at this link
回答2:
make alarm manager global so that the various functions are referencing the same object
Button bStart, bStop ;
long mCurrentTime;
Calendar calendar;
TextView tv;
AlarmManager am
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
...
...
Intent intent = new Intent(AlarmNewActivity.this, RepeatingAlarm.class);
PendingIntent sender = PendingIntent.getBroadcast(AlarmNewActivity.this, 0, intent, 0);
am = (AlarmManager)getSystemService(ALARM_SERVICE);
.....
来源:https://stackoverflow.com/questions/10485358/stopping-alarm-android-application