与前台服务android通信

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

我有什么:

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

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

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

我的问题是什么:

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

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

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

谢谢!

解决方法

不,bindService不会启动服务.它只是通过服务连接绑定到服务,因此您将拥有访问/控制它的服务实例.

根据您的要求,我希望您将使用MediaPlayer的实例.您也可以从Activity启动服务,然后绑定它.如果服务已经运行onStartCommand()将被调用,您可以检查MediaPlayer实例是否为null然后只返回START_STICKY.

改变你这样的活动..

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服务类似的应用程序.如果这种方法对您没有帮助,请告诉我.

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...