Android 活动可见时隐藏前台服务的通知

Android 活动可见时隐藏前台服务的通知,android,service,notifications,foreground,Android,Service,Notifications,Foreground,它们是否可以作为前台服务启动服务,并在活动可见时隐藏通知 以音乐播放器为例,当应用程序打开时,您不需要通知(即按钮),但只要音乐播放器在后台,就会显示通知 我知道,如果我不在前台运行我的服务,该怎么做。。。但在前台运行时,服务本身需要通知并显示它,我自己无法管理通知 如何解决该问题?使用以下步骤: 1.使用ActivityManager获取当前包名(即在顶部运行的活动) 2.检查是否是您的应用程序,然后不显示通知 3.否则,如果不是您的应用程序,则显示通知 ActivityManager man

它们是否可以作为前台服务启动服务,并在活动可见时隐藏通知

以音乐播放器为例,当应用程序打开时,您不需要通知(即按钮),但只要音乐播放器在后台,就会显示通知

我知道,如果我不在前台运行我的服务,该怎么做。。。但在前台运行时,服务本身需要通知并显示它,我自己无法管理通知

如何解决该问题?

使用以下步骤:

1.使用ActivityManager获取当前包名(即在顶部运行的活动)

2.检查是否是您的应用程序,然后不显示通知

3.否则,如果不是您的应用程序,则显示通知

ActivityManager manager =(ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
                            List<ActivityManager.RunningTaskInfo> tasks = manager.getRunningTasks(1);
                            String topActivityName = tasks.get(0).topActivity.getPackageName();
                            if(!(topActivityName.equalsIgnoreCase("your package name"))){
 //enter notification code here
}
ActivityManager=(ActivityManager)getSystemService(Context.ACTIVITY_服务);
List tasks=manager.getRunningTasks(1);
字符串topActivityName=tasks.get(0.topActivity.getPackageName();
if(!(topActivityName.equalsIgnoreCase(“您的包名”)){
//在此处输入通知代码
}

你可以这样做。此方法的一个先决条件是,您的活动必须绑定服务

首先,您启动服务前台

private Notification mNotification;

public void onCreate() {
   ...
   startForeground(1, mNotification);
}
然后在活动中绑定和解除绑定服务,如下所示<代码>绑定\u调整\u与\u活动对于保持服务在绑定到可见活动的时间内保持活动状态非常重要

public void onStart() {
    ...
    Intent intent = new Intent(this, PlayerService.class);
    bindService(intent, mConnection, BIND_ADJUST_WITH_ACTIVITY);
}

public void onStop() {
    ...
    unbindService(mConnection);
}
现在是最后的过去。当至少有一个客户端连接到服务时,停止前台,当最后一个客户端断开连接时,启动前台

@Override
public void onRebind(Intent intent) {
    stopForeground(true); // <- remove notification
}

@Override
public IBinder onBind(Intent intent) {
    stopForeground(true); // <- remove notification
    return mBinder;
}

@Override
public boolean onUnbind(Intent intent) {
    startForeground(1, mNotification); // <- show notification again
    return true; // <- important to trigger future onRebind()
}
若在自动创建标志打开的情况下启动服务,并且最后一个客户端解除绑定,则服务将自动停止。如果要保持服务运行,必须使用
startService()
方法启动它。基本上,您的代码如下所示

    Intent intent = new Intent(this, PlayerService.class);
    startService(intent);
    bindService(intent, mConnection, BIND_ADJUST_WITH_ACTIVITY);

为已经启动的服务调用
startService()
对其没有影响,因为我们不会覆盖
onCommand()
方法。

似乎是我想要的。。。只有一个缺点,我必须在我真正需要它之前启动服务…刚刚完成实现。它应该很有效。答案已更新。我以前尝试过,但效果不理想。。。我会检查更改并再次查看。。。顺便说一句,不绑定服务并在activities onPause/onResume中发送更改服务前台状态的意图将不起作用,因为活动处于活动状态时服务可能会被终止?这真的会发生吗?或者这也行吗?我的项目中也需要它,所以我让它起作用了。onUnbind()返回true,onRebind()隐藏通知。关于你的问题。绑定服务是必须的。如果它不受约束,那么它被杀死的概率会高得多。这种情况确实发生在具有较小容量或RAM的设备上。还有一个问题。。。startService说,它将覆盖onBind管理的默认服务生存期。。。但是你说,onBind是必要的,以保持服务的活力?
    Intent intent = new Intent(this, PlayerService.class);
    startService(intent);
    bindService(intent, mConnection, BIND_ADJUST_WITH_ACTIVITY);