与前台服务android通信

时间:2014-04-11 16:19:13

标签: android service bind foreground aidl

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

我有什么:

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

音乐正在服务中播放,以startForeground开头,所以它不会被杀死。

我需要通过我的活动与服务进行沟通,以获取曲目名称,图片和更多内容。

我的问题是什么:

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

但是,当我这样做时,关闭活动后我的服务就会被杀死。

我怎样才能同时获得两者?绑定和前台服务?

谢谢!

2 个答案:

答案 0 :(得分:15)

没有。 bindService无法启动服务。它只会使用Service绑定到service connection,这样您就可以使用instance服务来访问/控制它。

根据您的要求,我希望您将使用MediaPlayer的实例。您也可以从Activity然后bind启动该服务。如果service已在运行onStartCommand(),则会调用MediaPlayer实例不为空,然后返回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有类似的申请。如果这种方法对您没有帮助,请告诉我。

答案 1 :(得分:10)

引用Android documentation

  

一旦所有客户解除绑定,绑定服务就会被销毁,除非服务也已启动

关于已启动绑定之间的区别,请查看https://developer.android.com/guide/components/services.html

因此,您必须使用startService然后bindService创建服务,就像@Libin在他/她的示例中所做的那样。然后,该服务将一直运行,直到您使用stopServicestopSelf或直到Android决定它需要资源并杀死您为止。