I try to run a background service and display a persistent notification. When the notification is clicked, the service (providing NanoHTTPD webserver) should be stopped.
The onReceive
never seems to be called when tapping the notification. "Stop" is not logged. (while "Start" is.
My code below is roughly based on https://stackoverflow.com/a/19476094/288568.
public class Webserver extends IntentService {
private final String TAG = "MyAMWebserver";
public static final int PORT = 1234;
public static Boolean isRunning = false;
private MyWebserver server;
private ContentManager contentManager = new ContentManager(this);
private NotificationManager notificationManger;
public Webserver() {
super("webserver-service");
}
//We need to declare the receiver with onReceive function as below
protected BroadcastReceiver stopServiceReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "Stop");
unregisterReceiver(stopServiceReceiver);
stopSelf();
isRunning = false;
notificationManger.cancel(01);
}
};
@Override
public void onCreate() {
super.onCreate(); // if you override onCreate(), make sure to call super().
// If a Context object is needed, call getApplicationContext() here.
try {
server = new MyWebserver();
isRunning = true;
IntentFilter intentFilter = new IntentFilter("myMapWebserver");
Intent intent = new Intent("myMapWebserver");
registerReceiver(stopServiceReceiver, intentFilter);
PendingIntent pendingIntent
= PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new Notification.Builder(getApplicationContext())
.setContentTitle("Webserver Running").setContentText("Click here to Stop Webserver").setOngoing(true)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pendingIntent)
.getNotification();
notificationManger = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManger.notify(01, notification);
Log.d(TAG, "Started");
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void onHandleIntent(Intent intent) {
// This describes what will happen when service is triggered
}
public class MyWebserver extends NanoHTTPD {
....