Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop service from its own foreground notification

I have a Service running. and in its onStartCommand I am doing startforeground to avoid killing by system.

public int onStartCommand(Intent intent, int flags, int startId) {
    if (ACTION_STOP_SERVICE.equals(intent.getAction())) {
        Log.d(TAG,"called to cancel service");
        manager.cancel(NOTIFCATION_ID);
        stopSelf();
    }
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    builder.setContentTitle("abc");
    builder.setContentText("Press below button to stoP.");
    builder.setPriority(NotificationCompat.PRIORITY_HIGH);
    builder.setSmallIcon(R.drawable.ic_launcher);

    Intent stopSelf = new Intent(this, SameService.class);
    stopSelf.setAction(this.ACTION_STOP_SERVICE);
    PendingIntent pStopSelf = PendingIntent.getService(this, 0, stopSelf,0);
    builder.addAction(R.drawable.ic_launcher, "Stop", pStopSelf);
    manager.notify(NOTIFCATION_ID, builder.build());
}

but after pressing button , PendingIntent is not working and my activity is not getting stopped by it.

Can someone please tell, what wrong am I doing here or any other solution to stop service from the foreground notification made by self.

Thanks

like image 787
SimpleCoder Avatar asked May 24 '15 10:05

SimpleCoder


People also ask

How do I turn off foreground notifications?

User can dismiss notification by default Starting in Android 13 (API level 33), users can dismiss the notification associated with a foreground service by default. To do so, users perform a swipe gesture on the notification.

How do you stop a foreground service?

Inside the onReceive() method I call stopforeground(true) and it hides the notification. And then stopself() to stop the service.

What is foreground service notification Android?

Foreground services are an advanced Android concept which allows you to display notifications to your users when running long lived background tasks. The notification acts like any other notification, however it cannot be removed by the user and lives for the duration of the service.


3 Answers

Answering my own question for sake of other finders like me.

Problem was in the line below

 PendingIntent pStopSelf = PendingIntent.getService(this, 0, stopSelf,0); 

This 0 in the end was cause of the problem . I have replaced this with PendingIntent.FLAG_CANCEL_CURRENT and it worked now.

The corrected code is :

PendingIntent pStopSelf = PendingIntent.getService(this, 0, stopSelf,PendingIntent.FLAG_CANCEL_CURRENT); 

Please check FLAG_CANCEL_CURRENT or FLAG_UPDATE_CURRENT for more explanation.

like image 124
SimpleCoder Avatar answered Oct 04 '22 01:10

SimpleCoder


The above idea will not work properly. Service should stop it's thread first, so sometimes You'l see strange behavior. You should put some flag inside your loop/computation method and call "return;" , and than You may stop service by stopself() or just wait untill it finish itself. If need example I can show. So please ask.

like image 39
Віталій Шимко Avatar answered Oct 04 '22 01:10

Віталій Шимко


if u are using the Service then the service can not stop by itself its runs in the background u have to stop that in this code m stoping the service on notification button click it works for me.. Please Try this

public class AlarmSoundService extends Service {
    public static final int NOTIFICATION_ID = 1;

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


    @Override
    public int onStartCommand(final Intent intent, int flags, int startId) {
        if (intent != null) {
            if (intent.getAction().equals(Constants.ACTION_START)) {
                final Handler handler = new Handler();
                Timer timer = new Timer();
                TimerTask doAsynchronousTask = new TimerTask() {
                    @Override
                    public void run() {
                        handler.post(new Runnable() {
                            public void run() {
                                try {
                                    Date date = new Date();
                                    List<Event> list = SharedPref.getInstance(getApplicationContext()).getEvents();
                                    for (int i = 0; i < list.size(); i++) {
                                        Event a = list.get(i);
                                        SimpleDateFormat format = new SimpleDateFormat("MM/dd/yy", Locale.getDefault());
                                        String currentDate = format.format(date);
                                        if (a.getDate().equals(currentDate)) {
                                            date = new Date();
                                            format = new SimpleDateFormat("hh:mm a", Locale.ENGLISH);
                                            if (a.getTime().equals(format.format(date))) {
                                                playAlarmNotification(a.getTitle(), a.getDescription());
                                            }
                                        }
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    }
                };
                timer.schedule(doAsynchronousTask, 0, 1000);
            } else if (intent.getAction().equals(Constants.ACTION_STOP)) {
                stopForegroundService();
            }
        }
        return START_STICKY;
    }

    public void playAlarmNotification(String Title, String Description) {

        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        Intent stopnotificationIntent = new Intent(this, AlarmSoundService.class);
        stopnotificationIntent.setAction(Constants.ACTION_STOP);
        PendingIntent Intent = PendingIntent.getService(this, 0, stopnotificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "channel_id")
                .setSmallIcon(R.drawable.ic_access_time_black_24dp)
                .setContentTitle(Title)
                .setContentText(Description)
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setColor(Color.BLUE)
                .setDefaults(Notification.DEFAULT_ALL)
                .setFullScreenIntent(pendingIntent, true)
                .setAutoCancel(true)
                .setContentIntent(pendingIntent)
                .addAction(android.R.drawable.ic_media_pause, "Stop", Intent);


        Notification notification = builder.build();

        if (Build.VERSION.SDK_INT >= 26) {
            NotificationChannel channel = new NotificationChannel("channel_id", "background_service", NotificationManager.IMPORTANCE_DEFAULT);
            channel.setDescription("hello");
            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.createNotificationChannel(channel);
        }
        startForeground(NOTIFICATION_ID, notification);
    }

    private void stopForegroundService() {

        stopForeground(true);
        stopSelf();
    }

}
like image 34
Abhishek Rana Avatar answered Oct 04 '22 01:10

Abhishek Rana