与前台服务进行通信(Android)

30

这是我的第一个问题,但我已经在这里待了一段时间。

我的情况:

我正在构建一个播放音频流和在线播放列表的Android应用程序。现在一切都正常,但我在与我的服务进行通信方面遇到了问题。

音乐是在服务中播放的,使用startForeground启动,因此它不会被杀掉。

我需要从我的活动中与服务通信,以获取曲目名称、图像和其他一些东西。

我的问题是什么:

我认为我需要使用bindService(而不是当前的startService)启动服务,这样活动就可以与它通信。

然而,当我这样做时,关闭活动后我的服务就被杀掉了。

如何同时获得绑定和前台服务?

谢谢!


你尝试过为你的服务创建通知吗?我认为这应该有助于防止它被杀死。 - indivisible
我的回答有帮助吗? - Libin
2个回答

31
不会。 bindService 不会启动服务,只是通过一个service connection来绑定到Service,以便您可以获得服务的实例并对其进行访问/控制。
根据您的要求,我希望您将在服务中拥有MediaPlayer的实例。您也可以从Activity启动服务,然后将其bind。如果service已经运行,则将调用onStartCommand(),您可以检查MediaPlayer实例是否不为null,然后简单地返回START_STICKY
Activity更改如下...
public class MainActivity extends ActionBarActivity {

    CustomService customService = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // start the service, even if already running no problem.
        startService(new Intent(this, CustomService.class));
        // bind to the service.
        bindService(new Intent(this,
          CustomService.class), mConnection, Context.BIND_AUTO_CREATE);
    }

    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            customService = ((CustomService.LocalBinder) iBinder).getInstance();
            // now you have the instance of service.
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            customService = null;
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (customService != null) {
            // Detach the service connection.
            unbindService(mConnection);
        }
    }
}

我有一个类似于MediaPlayer service的应用程序。如果这种方法对你没有帮助,请告诉我。


在我的情况下,如果我在服务上解除绑定,该服务将被杀死。因为唯一绑定到它的活动已关闭/离开视图。这是高度记录的。我正在为我的应用程序做一个下载器系统。但它会杀死服务。当下载器完成时,我在服务中的某个地方调用了stopSelf,所以我的服务根本不会永远运行。有什么想法吗? - Neon Warge
2
OP 询问了 ContextCompat.startForegroundService(),而这个回答只涉及到了 startService(),并没有涉及到 AIDL。 - Someone Somewhere
1
请注意,bindService()确实会创建服务,而不必调用startService()。https://developer.android.com/guide/components/services.html - hyena

13

问题在于,当活动被销毁时,绑定/启动的服务会重新启动,对于音乐播放器来说,这意味着音乐会在一半重新开始。 - juztcode
你是否在前台运行它? - naw
它应该作为前台运行,而不是绑定/启动的服务。 - juztcode

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接