我有一个由绑定活动启动的前台服务。当活动forast创建服务时,如果用户启动服务,它将通过调用以下代码使其成为前台
public void makeForgroundService() {
notificationBuilder = new NotificationCompat.Builder(this);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
sessionId, new Intent(this, MainActivity.class), 0);
notificationBuilder.setContentTitle("My Test Service ")
.setContentText("Service now Running")
.setSmallIcon(R.drawable.newicon)
.setContentIntent(pendingIntent);
// notificationManager = (NotificationManager)
// getSystemService(Context.NOTIFICATION_SERVICE);
notify_id = sessionId;
Log.e(TAG,"making foreGrounf : sessionId = "+String.valueOf(notify_id));
startForeground(notify_id, notificationBuilder.build());
isForeground = true;
}
现在当活动再次启动时,它绑定到服务,(因为服务已经在运行并且是前台)。现在我想取消通知,在 getService 调用上尝试过,但不工作!
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// Log.e(TAG, "Inside onServiceConnected");
myService = ((MyService.MyBinder) service).getService();
if(myService.isForeground){
Log.e(TAG,"From Activity,removing notification : "+myService.notify_id);
NotificationManager nm = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
nm.cancel(myService.notify_id);
}
}
笔记
我不想stopForground
MyService。只需要隐藏或取消通知。
更新:
如果 stopForground 是唯一的方法,stopForground 会让在前台活动期间可能被杀死的服务吗?我可以在活动的 onDestroy 设置 StartForground 吗?这是一种(正确的)方式吗?