android - 与前台服务android通信

标签 android service bind foreground aidl

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

我有什么:

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

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

我需要通过我的 Activity 与服务进行通信,以获取轨道名称、图像和其他一些内容。

我的问题是什么:

我认为我需要使用 bindService(而不是我当前的 startService)启动我的服务,以便 Activity 可以与之对话。

但是,当我这样做时,我的服务会在关闭 Activity 后被终止。

我怎样才能两者兼得?绑定(bind)和前台服务?

谢谢!

最佳答案

没有。 bindService 不会启动服务。它只会通过 service connection 绑定(bind)到 Service,因此您将拥有服务的 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 类似的应用程序。如果这种方法对您没有帮助,请告诉我。

关于android - 与前台服务android通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23017767/

相关文章:

javascript - jquery中如何获取ul的内容变化事件

c++ - 重构嵌套绑定(bind)以使用 lambda 函数

android - 同心旋转叠加图像

symfony - Symfony2 服务的外观模式

javascript - 为什么我不能在回调中引用我的 jQuery 对象?

android - 经度和纬度在服务中显示 0.0

Spring:在启动时配置应初始化哪些服务 bean 的最佳方法是什么?

android - 为什么 ARM 11 或更早版本不支持 Adob​​e Flash 播放器?

java - 如何在 Android 中获取更详细的位置名称?

javascript - QuickConnect 与 Phonegap