java - 不要在 Activity 销毁时销毁绑定(bind)服务

标签 java android android-activity service

目前,我需要一个绑定(bind)(音乐)服务,因为我需要与之交互。但我也希望它不会停止,即使所有组件都已解除绑定(bind)。

作为Android Developer Guide

"[...] Multiple components can bind to the service at once, but when all of them unbind, the service is destroyed."

指南还说

"[...] your service can work both ways—it can be started (to run indefinitely) and also allow binding."

在我的应用程序中,服务在应用程序启动时启动。 我只想通过用户单击我在自定义通知中显示的关闭按钮来销毁此服务。但目前,当我销毁我的 MainActivity 时,该服务也会停止。

这是我现在所在的位置,当我想创建我的服务时调用它:

public void createServiceConnection(){
     musicConnection = new ServiceConnection(){
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            MusicService.MusicBinder binder = (MusicService.MusicBinder)service;
            musicSrv = binder.getService();
            attachMusicService();
        }
    };
}

...这叫做:

public void attachMusicService(){
    playerFragment.setMusicService(musicSrv);
    musicSrv.attach(context); //need this for my listeners, nevermind
    bindService(context);
}

...这叫做:

    public void bindService(Context act){
        if(playIntent==null){
            playIntent = new Intent(act, MusicService.class);
            act.startService(playIntent);

            act.bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
        }else{
            act.startService(playIntent);
            act.bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
        }

//finished. I can do stuff with my Service here.
    }

我是不是误会了什么? 我觉得服务应该继续运行,即使 Activity 被破坏,因为我首先创建了一个启动服务然后绑定(bind)到它。

最佳答案

从自定义应用程序类绑定(bind)到您的服务。我不认为在绑定(bind)到它的 Activity 被销毁后(当调用 onDestroy 时)你可以保持服务 Activity 。如果 Activity 暂停 (onPause),您可以通过从服务调用 startForeground 来保持服务 Activity

关于java - 不要在 Activity 销毁时销毁绑定(bind)服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36116948/

相关文章:

android - Linux 中的 LT_INIT(...) 是什么?

java - 如何在重写 Activity 的方法之一的同时启动 Activity?

android - 如何在我的 Activity 中显示弹出窗口?

Java 对具有多个参数的对象进行排序

android - 在android中使用媒体播放器时如何避免音频剪辑重复之前的延迟

java - 如何仅通过一个方法调用来重置所有对象值?

android - 在 imageview 中显示来自 Intent 的 jpg 图像

android - 透明 active ,带有淡淡的灰色

java - 如何在 Java 中重置迭代器?

java - jbpm-6.2.0-SNAPSHOT 安装失败