【问题标题】:Stop service and close app停止服务并关闭应用程序
【发布时间】:2017-11-16 19:06:47
【问题描述】:

我的应用使用背景音乐服务。 我有一个退出我的应用程序的按钮,但我找不到任何东西来关闭我的应用程序和我的服务。 我将我的服务绑定到我的活动。

我试过了:

unbindService(serviceConnection);
myService().stopSelf();
stopService(new Intent(this, MediaPlayer.class));

而且绝对没有任何效果!服务继续。

如何销毁我的服务以及如何关闭我的应用程序??

发送

编辑:

我在 onCreate 方法中使用这个

Intent intent = new Intent(this, serviceClass);
bindService(intent, serviceConnection, BIND_AUTO_CREATE);

在 MediaPlayer 类中

public class LocalBinder extends Binder {
        public MediaPlayer getService() {
            return MediaPlayer.this;
        }
    }
public IBinder onBind(Intent intent) {
    Log.i(TAG, "service bound");
    init();
    return mBinder;
}

然后…… 但我不知道我是否真的需要启动服务。绑定服务已经启动了

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return START_NOT_STICKY;
}

现在我做到了

@Override
public void onDestroy() {
    player.stop();
    super.onDestroy();
}

onDestroy 方法只有在我取消绑定服务时才有效! 这根本不起作用:

        getService().stopSelf();
       this.stopService(new Intent(this, MediaPlayer.class));

那么,我该如何停止服务以及如何关闭应用程序?

【问题讨论】:

  • 如何启动您的服务。 stopSelf() 仅在从该服务调用时才起作用。
  • “停止服务”是什么意思。其中一些将停止服务。但是,除非您的服务通过停止播放器正确处理其 onDestroy,否则停止服务不会停止音乐。
  • 问题不清楚...请添加一些代码和解释..
  • 我虽然停止服务也会停止播放器。

标签: android android-activity service destroy


【解决方案1】:

这就是我在我的应用程序中所做的。当您关闭应用程序时,将调用 Activity 中的 onDestroy() 方法。

private ServiceConnection musicServiceConnection = new ServiceConnection() {

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        MusicService.LocalBinder binder = (MusicService.LocalBinder) service;
        musicService = binder.getService();
        musicService.setCallbacks(MainActivity.this);
        musicServiceBound = true;
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        Log.i(TAG, "MusicService service disconnected (unbinded)");
        musicServiceBound = false;
    }
};


@Override
protected void onStart() {
    super.onStart();
    Intent intent1 = new Intent(this, MusicService.class);
    bindService(intent1, musicServiceConnection, Context.BIND_AUTO_CREATE);
}


@Override
protected void onDestroy() {
    super.onDestroy()
    if(musicServiceBound){
        musicService.stopSelf();
        unbindService(musicServiceConnection);
    }
}

您写了myService(),您正在使用() 创建另一个服务。 要以编程方式关闭您的应用程序,您可以参考question

【讨论】:

  • 是服务 onDestroy 吗?
  • Activity onDestroy
  • 您是在某处启动服务还是只是绑定它?
  • 这样您的服务将被正确绑定。您可以查看其他帖子,例如stackoverflow.com/questions/8341667/…
猜你喜欢
  • 1970-01-01
  • 2013-05-15
  • 1970-01-01
  • 1970-01-01
  • 2023-03-02
  • 2015-06-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多