我有一个服务,我从一个活动开始和绑定 . 在Activity的OnDestroy方法中,我取消绑定到服务 . 服务显示通知,我使用startForeground()将其放在前台 . 在Service的onUnbind()方法中,我调用stopself()和stopForeground(true) . 但似乎服务并没有停止工作 . 该应用程序已关闭,通知已消失,但android studio中的android内存监视器仍在继续 . 为什么会这样?如果我在调用stopForeground()的服务中创建一个函数,并在Activity的OnDestroy之前调用它,那么应用程序就会正常关闭 . 内存监视器停止 .
OnCreate()中的MainActivity:
service = new Intent(MainActivity.this, Service.class);
service.setAction("START");
startService(service);
if(myservice == null)
{
Intent k = new Intent(this,Service.class);
bindService(k, myConnection, Context.BIND_AUTO_CREATE);
}
OnDestroy中的MainActivity()
unbindService(myConnection);
服务OnCreate()
Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.setAction("new");
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
Bitmap icon = BitmapFactory.decodeResource(getResources(),
R.drawable.ic_launcher);
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle("Myservice")
.setTicker("service")
.setContentText("Monitoring")
.setSmallIcon(R.drawable.ic_launcher)
.setLargeIcon(Bitmap.createScaledBitmap(icon, 128, 128, false))
.setContentIntent(pendingIntent)
.setOngoing(true).build();
startForeground(101, notification);
1 回答
1)服务在后台运行所以
onDestroy()
方法需要在服务上调用方法 .2)你想关闭应用程序关闭服务然后你需要实现
onTaskRemoved()
并调用3)并且你想停止活动关闭活动然后
onDestroy()
活动方法你需要调用跟随代码 .