运行 activity 销毁后的绑定服务

Running Bindservice after the activity is destroyed

我正在创建一个活页夹类型的音乐播放器 service.I 知道如果我使用活页夹我应该在 activity 中使用 stopSelf 但是有什么方法可以 运行 activity destroy.I 上的服务在我的 activity.if 中有一个搜索栏 我在 OnDestroy 中使用 startService 我在服务中遇到错误。

主要活动

private ServiceConnection music=new ServiceConnection(){

    @Override
    public void onServiceConnected(ComponentName p1, IBinder p2)
    {
        // TODO: Implement this method
        MusicBinder binder=(MusicBinder)p2;
        registerReceiver(broadcastReciever, new IntentFilter(MusicService.BROADCAST_ACTION));
        musicSrv = binder.getService();
        musicSrv.setList(songList);
        musicBound = true;
    }

    @Override
    public void onServiceDisconnected(ComponentName p1)
    {
        // TODO: Implement this method
        if (mBroadCastIsRegistered)
        {
            try
            {
                unregisterReceiver(broadcastReciever);
                mBroadCastIsRegistered = false;}
            catch (Exception e)
            {
                e.printStackTrace();
                Toast.makeText(getApplicationContext(), e.getClass().getName() + "" + e.getMessage(), Toast.LENGTH_LONG).show();
            }
        }
        musicBound = false;
    }
};

清单

<service
  android:name=".Musicservice"/>

我正在用线程启动服务。

您可以从 activity 启动服务然后绑定服务。这样 activity 可以在完成后解除绑定,但音乐服务将继续播放直到调用 stop self 。所以使用这两种机制都需要停止。

嗯,据我所知,Servive 属于**线程,它是在线程中创建的**。

因此,如果您想在 Activity 关闭后保留服务 运行,则必须从其他地方启动它。我会推荐一个 Application 子类,或者您可以从 Activity 中使用: new Thread(){...startServiceHere...}.start();

Thread t = new Thread(){
public void run(){
getApplicationContext().bindService(
    new Intent(getApplicationContext(), MyAndroidUpnpServiceImpl.class),
    serviceConnection,
    Context.BIND_AUTO_CREATE
);}
};
t.start();

//从@Samuh 复制的服务代码

如@bhiku 所述,您可以启动服务,然后使用 serviceConnection 回调将 activity 绑定到 运行 服务。

  // so start your service
  val audioPlayerServiceIntent = Intent(this, AudioPlayerService::class.java)
  Util.startForegroundService(this, audioPlayerServiceIntent)
        

  val serviceConnection = object : ServiceConnection {
    override fun onServiceConnected(name: ComponentName?, binder: IBinder?) {
       if (binder is AudioPlayerService.PlayerBinder) {
            playerView.player = binder.getExoPlayerInstance()
       }
    }

    override fun onServiceDisconnected(p0: ComponentName?) {

    }
  }
  // then bind your activity to the running service
  bindService(Intent(this, AudioPlayerService::class.java), serviceConnection, Context.BIND_AUTO_CREATE)