停止服务并关闭应用程序

Stop service and close app

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

我试过了:

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

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

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

发送

编辑:

我在onCreate方法中使用了这个

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

并且在 MediaPlayer 中 class

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));

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

这就是我在我的应用程序中所做的。当您关闭您的应用程序时,将调用 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.