簡體   English   中英

為什么在我調用stopService后服務仍然(似乎仍)有效

[英]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 ,你需要調用offdisconnectSocket您先前在創建initSocketIO 另外,如果您自己在服務中啟動了任何后台線程,則需要確保在onDestroy中將其關閉。

服務已銷毀,但Socket.IO的偵聽器仍處於活動狀態。 記住要關閉Socket.IO並關閉后台線程。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM