I have developed an app that plays bgm service even after hitting the home button or switching to another activity. The problem is when I remove the app through recent apps - the service is still running.
How do I make it stop when I remove the app through recent apps? Is it possible to do that?
here is my code:
public class MixPage extends Activity {
private ToggleButton creekToggle;
SharedPreferences creekPref;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mix);
creekToggle = (ToggleButton) findViewById(R.id.creek);
creekPref = getSharedPreferences("creekPref", MODE_PRIVATE);
creekToggle.setChecked(creekPref.getBoolean("is creek on",false));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void playCreek(View view) {
// Is the toggle on?
boolean on = ((ToggleButton) view).isChecked();
if (on) {
Intent objCreek = new Intent(this, PlayCreek.class);
startService(objCreek);
SharedPreferences.Editor editorCreek=creekPref.edit();
editorCreek.putBoolean("is creek on", true);
editorCreek.commit();
Toast.makeText(getApplicationContext(), "Creek is Playing", Toast.LENGTH_SHORT).show();
} else {
Intent objCreek = new Intent(this, PlayCreek.class);
stopService(objCreek);
SharedPreferences.Editor editorCreek=rainPref.edit();
editorCreek.putBoolean("is creek on", false);
editorCreek.commit();
Toast.makeText(getApplicationContext(), "Creek is Stopped", Toast.LENGTH_SHORT).show();
}
}
PlayCrickets.java
public class PlayCrickets extends Service {
private static final String LOGCAT = null;
MediaPlayer objPlayer;
public void onCreate() {
super.onCreate();
Log.d(LOGCAT, "Service Started!");
objPlayer = MediaPlayer.create(this,R.raw.crickets);
}
public int onStartCommand(Intent intent, int flags, int startId) {
objPlayer.setLooping(true);
objPlayer.start();
Log.d(LOGCAT, "Media Player started!");
if(objPlayer.isLooping() != true){
Log.d(LOGCAT, "Problem in Playing Audio");
return 1;
}
public void onStop() {
objPlayer.stop();
objPlayer.release();
}
public void onPause() {
objPlayer.stop();
objPlayer.release();
}
public void onDestroy(){
objPlayer.stop();
objPlayer.release();
}
@Override
public IBinder onBind(Intent objIndent) {
return null;
}
@Override
public void onTaskRemoved(Intent rootIntent) {
System.out.println("onTaskRemoved called");
super.onTaskRemoved(rootIntent);
objPlayer.stop();
objPlayer.release();
//stop service
this.stopSelf();
}
}
You need to override
Service.onTaskRemoved(Intent rootIntent)
in your service class. This method will get called when a task belonging to service application is removed from recent screen. Do this:Hope this will help.
In your Manifest add stopWithTask attribute where you have define your service:
If Above approach doest work then do reverse
So your service's method onTaskRemoved will be called. (Remember, it won't be called if you set stopWithTask to true).