我尝试运行后台服务并显示持久通知。单击通知后,应停止服务(提供NanoHTTPD网络服务器)。
点击通知时似乎永远不会调用onReceive
。 "停止"未记录。 (而#34;开始"是。
下面的代码大致基于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 {
....