号bindService
将无法启动服务。它只会绑定到Service
与service connection
,以便您将有服务的instance
访问/控制它。
根据您的要求,我希望您的服务中有MediaPlayer
的实例。你也可以从Activity
开始服务,然后bind
它。如果service
已经运行onStartCommand()
将被调用,您可以检查是否MediaPlayer
实例不为空,然后简单地返回START_STICKY
。
更改您Activity
这样的..
public class MainActivity extends ActionBarActivity {
CustomService customService = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// start the service, even if already running no problem.
startService(new Intent(this, CustomService.class));
// bind to the service.
bindService(new Intent(this,
CustomService.class), mConnection, Context.BIND_AUTO_CREATE);
}
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
customService = ((CustomService.LocalBinder) iBinder).getInstance();
// now you have the instance of service.
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
customService = null;
}
};
@Override
protected void onDestroy() {
super.onDestroy();
if (customService != null) {
// Detach the service connection.
unbindService(mConnection);
}
}
}
我有MediaPlayer
service
类似的应用程序。让我知道如果这种方法不能帮助你。
您是否尝试过为您的服务制作通知?我认为这应该有助于阻止它被杀害。 – indivisible
我的回答有帮助吗? – Libin