-1

How can I start and stop service from notification just by tapping it(No button), I somehow managed to start the pending intent, but don't know where to put stop service()/stopself() command.

PendingIntent pi = PendingIntent.getService(MainActivity.this,0, new Intent(MainActivity.this, MainService.class), 0);

    final Notification notification = new NotificationCompat.Builder(MainActivity.this)
            .setTicker("MY FIRST NOTIFICATION TOGGLE")
            .setSmallIcon(R.drawable.ic_blur_on_black_24dp)
            .setContentTitle("Click to toggle on/off")
            .setContentText("Click Again")
            .setContentIntent(pi)
            .setOngoing(true)
            .build();

    final NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Ravi Kilnake
  • 175
  • 2
  • 14
  • 2
    try [this](https://stackoverflow.com/questions/11270898/how-to-execute-a-method-by-clicking-a-notification) – Jyoti JK Feb 10 '18 at 11:30
  • Joe, I managed to understand few things from this, but it feels so advance to me and I don't want to put the additional button beneath it. I wanted to "click once= turn activity on, click the notification again= turn activity off" and notification stays in notification bar just like debugging message when phone is connected to the PC – Ravi Kilnake Feb 10 '18 at 12:18

1 Answers1

0

Add action to your notification:

final Notification notification = new 

NotificationCompat.Builder(MainActivity.this)
            .setTicker("MY FIRST NOTIFICATION TOGGLE")
            .setSmallIcon(R.drawable.ic_blur_on_black_24dp)
            .setContentTitle("Click to toggle on/off")
            .setContentText("Click Again")
            .setContentIntent(pi)
            .setOngoing(true)
            .addAction(R.drawable.some_icon, "start service", pi)
            .build();
godot
  • 3,422
  • 6
  • 25
  • 42