I have an application which uses a persistent notification within a service and runs in the background. While this service is running, I need to be able to call a method/do some action when the notification is clicked. However, I'm not sure how to implement this. I have read through many similar questions/answers, however none were answered clearly or suitably to my purposes. This SO questions comes close to what I am trying to achieve, but the chosen answer is hard to understand.
My service/notification is started in the onCreate() method for my BackgroundService class...
Notification notification = new Notification();
startForeground(1, notification);
registerReceiver(receiver, filter);
and this service is launched from my main activity's button click:
final Intent service = new Intent(Main.this, BackgroundService.class);
bStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if((counter % 2) == 0){
bStart.setText("STOP");
startService(service);
}else {
bStart.setText("BEGIN");
stopService(service);
}
counter++;
}
any advice is appreciated
You'll have to use a BroadcastReceiver for that. Take a look at the following code. Put it in your Service
private MyBroadcastReceiver mBroadcastReceiver;
@Override
onCreate() {
super.onCreate();
mBroadcastReceiver = new MyBroadcastReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
// set the custom action
intentFilter.addAction("do_something");
registerReceiver(mBroadcastReceiver, intentFilter);
}
// While making notification
Intent i = new Intent("do_something");
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, i, 0);
notification.contentIntent = pendingIntent;
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
switch(action) {
case "do_something":
doSomething();
break;
}
}
}
public void doSomething() {
//Whatever you wanna do on notification click
}
This way the doSomething() method will be called when your Notification is clicked.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With