我有以下启动服务的代码:
package com.example.serviceapp;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class MyService extends Service {
private static final String TAG = "MyService";
MediaPlayer player;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
player = MediaPlayer.create(this, R.raw.music);
player.setLooping(false); // Set looping
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
player.start();
/*
* START_STICKY: Constant to return from onStartCommand(Intent, int,
* int): if this service's process is killed while it is started (after
* returning from onStartCommand(Intent, int, int)), then leave it in
* the started state but don't retain this delivered intent.
*/
return START_STICKY;
}
@Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
player.stop();
}
}
但是当应用程序进程被杀死时,服务停止并重新启动,为什么?
这就是我启动/停止服务的方式:
public class MainActivity extends Activity {
private static final String TAG = "ServicesDemo";
Button buttonStart, buttonStop;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonStart = (Button) findViewById(R.id.buttonStart);
buttonStop = (Button) findViewById(R.id.buttonStop);
buttonStart.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "onClick: starting srvice");
startService(new Intent(getApplicationContext(),
MyService.class));
}
});
buttonStop.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "onClick: stopping srvice");
stopService(new Intent(getApplicationContext(), MyService.class));
}
});
}
}