简体   繁体   中英

AlarmManager is not cancelling android

I am trying to cancel my alarmmanager which I have registered before. I am registering my alarmmanager as below:

Intent i = new Intent(SetProfileOnlineActivity.this, GpsPingService.class);
PendingIntent pendingIntent = PendingIntent.getService(SetProfileOnlineActivity.this, 1545,
                                                            i, 0);
alarmManager.set(AlarmManager.RTC, System.currentTimeMillis() + 5000, pendingIntent);

and i am trying to cancel it using following code:

Intent i = new Intent(SetProfileOnlineActivity.this, GpsPingService.class);
PendingIntent p = PendingIntent.getService(SetProfileOnlineActivity.this, 1545, i, 0);
alarmManager.cancel(p);

But it's not cancelling. For debugging it I had putted this code in try catch block but it can't catch any error. Please let me know the reason why it's happening and how can I solve it?

UPDATE

May be it is duplicate but i can not understand what is the difference between the answer which is given in this question and which i have tried. So, it's not duplicate question because i have already done the thing which is suggested in this answer.

UPDATE 1

Full Code

I am starting my service using following block of code:

AlertDialog.Builder builder = new AlertDialog.Builder(SetProfileOnlineActivity.this);
                                    builder.setTitle("Need More Accuracy?");
                                    builder.setMessage("Hello user, you have set too small area for geofence. May be it will " +
                                            "perform action with delay in time. If you want to get more accuracy in action" +
                                            " then press \"YES\" button. More accuracy will consume more bettery then normal.");
                                    builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            startService(new Intent(SetProfileOnlineActivity.this, GpsPingService.class));


                                            try {

                                                Intent i = new Intent(SetProfileOnlineActivity.this, GpsPingService.class);
                                                PendingIntent pendingIntent = PendingIntent.getService(SetProfileOnlineActivity.this, 1545,
                                                        i, PendingIntent.FLAG_UPDATE_CURRENT);
                                                AlarmManager alarmManager = (AlarmManager)getSystemService(SetProfileOnlineActivity.ALARM_SERVICE);

                                                alarmManager.set(AlarmManager.RTC, System.currentTimeMillis() + 5000, pendingIntent);
                                                Log.e("JK-->> ", "Alarmmanager setted!");
                                            } catch (Exception e) {
                                                Log.e("JK-->>", "Error gpsping register -->> " + e.toString());
                                            }

                                            dialog.dismiss();
                                        }
                                    });
                                    builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            try {
                                                Intent i = new Intent(SetProfileOnlineActivity.this, GpsPingService.class);
                                                PendingIntent p = PendingIntent.getService(SetProfileOnlineActivity.this, 1545, i, PendingIntent.FLAG_UPDATE_CURRENT);
                                                AlarmManager alarmManager = (AlarmManager)getSystemService(SetProfileOnlineActivity.ALARM_SERVICE);
                                                alarmManager.cancel(p);
                                                stopService(i);

                                            } catch (Exception e) {
                                                Log.e("JK-->>", "Cancel alarmmanager error-->> " + e.getMessage().toString());
                                            }
                                            dialog.dismiss();
                                        }
                                    });
                                    AlertDialog alertDialog = builder.create();
                                    alertDialog.show();

Service class:

public class GpsPingService extends Service {

    LocationManager locationManager;
    LocationListener locationListener;
    FusedLocationProviderClient fusedLocationProviderClient;
    LocationRequest locationRequest;

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e("JK-->>", "Gpsping Service stopped!");
    }

    @Override
    public void onCreate() {
        Log.e("JK-->>", "Gpsping Service started!");
    }

    public GpsPingService() {
        Log.e("JK-->>", "constructor");
    }

    @SuppressLint("MissingPermission")
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e("JK-->>", "Gpsping Service onstartcommand!");
        try {


            Intent i = new Intent(this, GpsPingService.class);
            PendingIntent pendingIntent = PendingIntent.getService(this, 1545,
                    i, 0);

            AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
            alarmManager.set(AlarmManager.RTC, System.currentTimeMillis() + 5000, pendingIntent);


            locationRequest = new LocationRequest()
                    .setInterval(1000)
                    .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                    .setFastestInterval(1000);

            LocationCallback locationCallback = new LocationCallback() {
                @Override
                public void onLocationResult(LocationResult locationResult) {
                    Log.e("JK-->>", "location updated by gpsping service-->> " + locationResult.getLastLocation().getLatitude() +
                            " " + locationResult.getLastLocation().getLongitude());
                    Toast.makeText(getApplicationContext(), "Location changed!", Toast.LENGTH_SHORT).show();
                }
            };

            fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getApplicationContext());
            fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());

        } catch (Exception e) {
            Log.e("JK-->>Gpsping-->> ", e.getMessage());
        }
        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

Try creating a different AlarmManager ;

Intent i = new Intent(SetProfileOnlineActivity.this, GpsPingService.class);
PendingIntent pendingIntent = PendingIntent.getService(SetProfileOnlineActivity.this, 1545,i, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, System.currentTimeMillis() + 5000, pendingIntent);

And when you cancel it you do this :

Intent i = new Intent(SetProfileOnlineActivity.this, GpsPingService.class);
PendingIntent p = PendingIntent.getService(SetProfileOnlineActivity.this, 1545, i, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(p);

Doing this is working for me.

I think you provide a wrong flag to PendingIntent . According documentation

May be FLAG_ONE_SHOT, FLAG_NO_CREATE, FLAG_CANCEL_CURRENT, FLAG_UPDATE_CURRENT, FLAG_IMMUTABLE or any of the flags as supported by Intent.fillIn() to control which unspecified parts of the intent that can be supplied when the actual send happens.

Try using PendingIntent.FLAG_UPDATE_CURRENT when you create alarm, then cancel it.

PendingIntent.getService(SetProfileOnlineActivity.this, 1545, i, PendingIntent.FLAG_UPDATE_CURRENT);

Also i see that you get context from service itself. Check context for null , or maybe is not running.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM