停止服务并关闭应用

时间:2017-11-16 19:06:47

标签: android android-activity service destroy

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

我试过了:

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

绝对没有任何作用!服务还在继续。

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

的Tx

编辑:

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

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

1 个答案:

答案 0 :(得分:0)

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

相关问题