我的应用程序有一个按钮:“前景”。通过单击前景按钮,前景服务附加了一个通知(在单击时启动)。点击我的通知应该停止我的服务(使用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());
}
我知道代码很乱,但它只是一个样本。那么为什么有我的服务的引用,但只有你关闭活动并试图破坏服务?
答案 0 :(得分:0)
尝试从OnDestroy中删除代码 -
notificationManager.cancelAll();
notificationManager = null;
并在调用stopSelf()
之前将其放在destruct()中