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

pro*_*m85 12 service notifications android foreground

他们是一种将服务作为前台服务启动并在活动可见时隐藏通知的方法吗?

考虑一个音乐播放器,当应用程序打开时,您不需要通知(即按钮),但每当音乐播放器在后台时,都应显示通知.

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

我该如何解决这个问题?

ser*_*nka 10

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

首先,您启动服务前台.

private Notification mNotification;

public void onCreate() {
   ...
   startForeground(1, mNotification);
}
Run Code Online (Sandbox Code Playgroud)

然后在您的活动中绑定和解除绑定服务,如下所示.BIND_ADJUST_WITH_ACTIVITY对于在可见活动中绑定的时间保持服务是很重要的.

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

public void onStop() {
    ...
    unbindService(mConnection);
}
Run Code Online (Sandbox Code Playgroud)

现在这是最后的过去.当至少一个客户端连接到服务时,您停止前台,并在最后一个客户端断开连接时启动前台.

@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()
}
Run Code Online (Sandbox Code Playgroud)

绑定服务时,您必须考虑Android应用的规则.如果绑定未启动的服务,除非您BIND_AUTO_CREATE在flag之外指定flag,否则该服务不会自动启动BIND_ADJUST_WITH_ACTIVITY.

    Intent intent = new Intent(this, PlayerService.class);
    bindService(intent, mConnection, BIND_AUTO_CREATE 
            | BIND_ADJUST_WITH_ACTIVITY);
Run Code Online (Sandbox Code Playgroud)

如果在启用自动创建标志的情况下启动服务,并且最后一个客户端解除绑定,则服务将自动停止.如果要保持服务运行,则必须使用startService()方法启动它.基本上,您的代码将如下所示.

    Intent intent = new Intent(this, PlayerService.class);
    startService(intent);
    bindService(intent, mConnection, BIND_ADJUST_WITH_ACTIVITY);
Run Code Online (Sandbox Code Playgroud)

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