繁体   English   中英

服务永远不会收集垃圾

[英]Service never gets garbage collected

我的应用程序有一个按钮:“前景”。 通过单击前台按钮,将显示一条附加到前台服务的通知(在单击时开始)。 单击我的通知应该停止我的服务(使用PendingIntent),以便能够进行垃圾收集,但是事实并非如此。 Android Studio告诉我,NotificationManager拥有对我的服务的引用。 奇怪的是,只有在我关闭主要活动后单击通知,它才会发生。

我的服务代码:

public class TestService extends IntentService {
public static final String ACTION_GO_FOREGROUND = "GO_FOREGROUND";
public static final String ACTION_DESTROY = "DESTROY";

private NotificationManagerCompat notificationManager;

public TestService() {
    super("Name");
}

@Override
public void onCreate() {
    super.onCreate();

    notificationManager = NotificationManagerCompat.from(this);
}

@Override
public void onDestroy() {
    super.onDestroy();

    notificationManager.cancelAll();
    notificationManager = null;
}

@Override
protected void onHandleIntent(Intent intent) {

}

@Override
public int onStartCommand(Intent intent, int flags, final int startId) {
        switch (intent.getAction()) {
            case ACTION_GO_FOREGROUND:
                fg();
                break;
            case ACTION_DESTROY:
                destruct();
                break;
        }

    return START_STICKY;
}

private void destruct() {
    stopForeground(true);
    stopSelf();
}

private void fg() {
    Intent intent = new Intent(this, TestService.class);
    intent.setAction(ACTION_DESTROY);

    // Create the notification.
    android.support.v7.app.NotificationCompat.Builder notificationBuilder = new android.support.v7.app.NotificationCompat.Builder(this);
    notificationBuilder.setSmallIcon(R.mipmap.ic_launcher);
    notificationBuilder.setTicker("Ticker");
    notificationBuilder.setContentTitle("Title");
    notificationBuilder.setContentText("Content text");
    notificationBuilder.setContentIntent(PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));

    startForeground(1, notificationBuilder.build());
}

我知道代码很乱,但这只是示例。 那么,为什么仅在您关闭活动并尝试销毁服务的情况下才引用我的服务?

尝试从OnDestroy删除代码-

notificationManager.cancelAll();
notificationManager = null; 

并在调用stopSelf()之前将其放在destruct()中

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM