保留或杀死未使用的服务

时间:2014-01-04 14:47:26

标签: android android-service

我在音乐播放器中使用Service来处理MediaPlayer。以下是我在Activity处理服务的行为:

boolean serviceStarted = false; // I store this in saveInstanstanceState

protected void onResume(){
    super.onStart();
    // mBound is boolean that is set in onServiceConnected
    if(!mBound){ 
        Intent intent = new Intent(getApplicationContext(), MyService.class);
        if(!serviceStarted){ 
             startService(intent);
             serviceStarted = true;
        }
        bindService(intent);
    }
}

protected onPause(){
    super.onPause();
    if(mBound){
        unbindService(mConnection); // mConnection is my ServiceConnection
        mBound = false;
    }
}

现在我已经认识到,如果用户从最近使用的应用程序中删除了我的应用程序,则服务不会被终止。但是,由于我认为用户希望(至少)通过从最近使用的应用程序中删除音乐来停止音乐,我想在那里杀死该服务。
因此我已将此添加到Activity

boolean orientationChange = false;

public Object onRetainCustomNonConfigurationInstance() {
    orientationChange = true;
    return super.onRetainCustomNonConfigurationInstance();
}

protected void onDestroy(){
     if(!orientationChange){
            stopService(new Intent(getApplicationContext(), MyService.class));  
     }
} 

现在可以使用,但由于onRetainCustomNonConfigurationInstance()已被弃用,我不想保留此内容。但是我也不想在方向改变时杀死服务。
我还有其他什么可能性?

1 个答案:

答案 0 :(得分:0)

在您的服务中使用某种情况进行一段时间的循环。 如果要停止服务,请将此条件更改为false。这将阻止您的服务执行代码,操作系统将停止您的服务。

相关问题