[英]Why the Service still ( Seem to Be )alive after I call stopService
我有我的应用程序服务,并将其用于Socket.IO。 我不想允许绑定,所以:
/**
* You must always implement this method, but if you don't want to allow binding
* then you should return null.
*/
@Override
public IBinder onBind(@NonNull Intent intent) {
return null;
}
@Override
public int onStartCommand(@NonNull Intent intent, int flags, int startId) {
return START_NOT_STICKY;
}
然后在onCreate()中初始化Socket.IO:
@Override
public void onCreate() {
super.onCreate();
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Log.d(TAG, "Service Create");
//...More
setForeground();
initSocketIO();
}
private void setForeground() {
Intent notificationIntent = new Intent(this, LiveTabActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
//getNotification() is deprecated in API16
if (Build.VERSION.SDK_INT >= 16) {
Notification notification = new Notification.Builder(context)
.setContentTitle(getString(R.string.app_name))
.setContentText(getString(R.string.service_running))
.setSmallIcon(R.drawable.defimgs)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.md1))
.setContentIntent(pendingIntent).build();
startForeground(100, notification);
return;
}
Notification notification = new Notification.Builder(context)
.setContentTitle(getString(R.string.app_name))
.setContentText(getString(R.string.service_running))
.setSmallIcon(R.drawable.defimgs)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.md1))
.setContentIntent(pendingIntent).getNotification();
startForeground(100, notification);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "Service onDestroy");
//...more
}
在initSocketIO()中,我初始化Socket.IO的数据,以便可以接收服务器的消息。当服务接收到该消息时,它将具有一个日志并推送一个通知。
之后该应用程序运行良好。但是在此应用程序中,我想为用户提供注销帐户的功能。因此,当用户选择注销该应用程序时,应停止该服务。
但是,当我在Activity中使用stopService()停止服务时,我可以在LogCat中看到“ Service onDestroy”,但该服务仍然有效! 因为当服务从服务器收到消息时,我可以在LogCat中看到Log in!
即使我使用EventBus将事件发送到此服务以使该服务自行调用stopSelf,也仍然存在此问题。
那么,如何停止以Foreground开头的服务? 谢谢你的帮助。
您没有在代码中显示它,但是听起来您仍然有一个活动的socketIO侦听器。 在onDestroy
,你需要调用off
和disconnect
的Socket
您先前在创建initSocketIO
。 另外,如果您自己在服务中启动了任何后台线程,则需要确保在onDestroy
中将其关闭。
服务已销毁,但Socket.IO的侦听器仍处于活动状态。 记住要关闭Socket.IO并关闭后台线程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.