无法取消CountDownTimer。 我引用此链接CountDownTimer
CountDownTimer mtimer = new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
Toast.makeText(getApplicationContext(), "seconds remaining: " + millisUntilFinished / 1000, Toast.LENGTH_SHORT).show();
Log.e("seconds remaining:", String.valueOf(millisUntilFinished / 1000));
}
public void onFinish() {
Toast.makeText(getApplicationContext(), "Done!", Toast.LENGTH_SHORT).show();
Log.e("Finish called "," GG");
// Trigger();
}
};
我打电话给mtimer.start();但无法取消mtimer.cancel();
GeofenceBroadcastReceiver.java
public class GeofenceBroadcastReceiver extends BroadcastReceiver {
CountDownTimer mtimer = null;
public int GEOFENCE_RADIUS ; // in meters
public int MINUTE;
public int GEOFENCE_DURATION ;
@Override
public void onReceive(Context context, Intent intent) {
SharedPreferences localShared = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
GEOFENCE_RADIUS = localShared.getInt("SelectedRadius", -1);
GEOFENCE_DURATION= localShared.getInt("SelectedDuration",-1);
Log.e("RECIEVER GEO DURATION", String.valueOf(GEOFENCE_DURATION));
GeofencingEvent event = GeofencingEvent.fromIntent(intent);
String transition = mapTransition(event.getGeofenceTransition());
Log.e("transition",transition);
Log.e("getGeofenceTransition", String.valueOf(event.getGeofenceTransition()));
NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new NotificationCompat.Builder(context)
.setVibrate(new long[] { 1000, 1000, 500,500 })
.setSmallIcon(R.drawable.start)
.setContentTitle("Geofence Notification!")
.setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND)
.setContentText(transition)
.setTicker("Geofence action")
.build();
nm.notify(0, notification);
}
public String mapTransition( int event) {
MINUTE = (GEOFENCE_DURATION * 60 * 1000);
Log.e("MINUTE", String.valueOf(MINUTE));
mtimer = new CountDownTimer(MINUTE, 1000) {
public void onTick(long millisUntilFinished) {
Toast.makeText(getApplicationContext(), "seconds remaining: " + millisUntilFinished / 1000, Toast.LENGTH_SHORT).show();
Log.e("seconds remaining:", String.valueOf(millisUntilFinished / 1000));
}
public void onFinish() {
Toast.makeText(getApplicationContext(), "Done!", Toast.LENGTH_SHORT).show();
Log.e("Finish called "," GG");
Trigger();
}
};
switch (event) {
case Geofence.GEOFENCE_TRANSITION_ENTER:{
mtimer.start();
}
return "ENTER";
case Geofence.GEOFENCE_TRANSITION_EXIT:{
mtimer.cancel();
}
return "EXIT";
default:
return "UNKNOWN";
}
}
在switch case语句中,我可以在检测到ENTER时启动Timer,但是我无法取消Timer。