与前台服务android通信

问题描述 投票:12回答:2

这是第一个问题,但我已经有一段时间了。

我有什么:

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

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

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

我的问题是什么:

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

但是,当我这样做时,我的服务在关闭Activity后被杀死。

我怎样才能得到这两个?绑定和前台服务?

谢谢!

android service bind foreground aidl
2个回答
15
投票

没有.bindService不会开始服务。它将与Service绑定到service connection,这样你就可以获得服务的instance来访问/控制它。

根据您的要求,我希望您将使用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有类似的应用。如果这种方法对您没有帮助,请告诉我。


10
投票

引用Android documentation

除非服务也已启动,否则绑定服务将在所有客户端解除绑定后销毁

关于开始和绑定之间的区别只是看看https://developer.android.com/guide/components/services.html

所以,你必须使用startServicebindService创建服务,就像@Libin在他/她的例子中所做的那样。然后,服务将一直运行,直到你使用stopServicestopSelf或直到Android决定它需要资源并杀死你。

© www.soinside.com 2019 - 2024. All rights reserved.