我创建了Service
,并在Activity
点击时开始使用Button
,但Service
在关闭Activity
后停止。那么我该如何继续运行Service
而不停止?
MainActivity.java
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void startService(View v){
Intent i = new Intent(this, NotStickyService.class);
startService(i);
}
public void stopService(View v){
Intent i = new Intent(this, NotStickyService.class);
stopService(i);
}
Service.java
public class NotStickyService extends Service{
MediaPlayer mp;
@Override
public void onCreate() {
showToast("onCreate");
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
showToast("onStart");
mp = new MediaPlayer();
AssetFileDescriptor descriptor;
descriptor = getAssets().openFd("msg.mp3");
mp.setDataSource(descriptor.getFileDescriptor(),
descriptor.getStartOffset(),descriptor.getLength());
descriptor.close();
mp.prepare();
mp.start();
return Service.START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
showToast("onDestroy");
}
private void showToast(String message){
Toast toast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
toast.show();
}
}