I have read this SO question but it didnt help me...Android Background Service is restarting when application is killed. but answer mentioned here is not helping me at all. Please consider this
I want to create a service for background music and want to play it even if my app is closed. so i write following code...
package elsner.com.mediaplayer;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
/**
* Created by nteam on 6/2/16.
*/
public class BackGround extends Service {
MediaPlayer mPlayer;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
Log.i("niral", "Service Create");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("niral", "Service Start");
final Handler h = new Handler();
final long delayInMilliseconds = (6000*10);
new Thread(new Runnable() {
@Override
public void run() {
mPlayer = MediaPlayer.create(getApplicationContext(), R.raw.aayat);
mPlayer.start();
h.postDelayed(new Runnable() {
public void run() {
mPlayer.stop();
}
}, delayInMilliseconds);
}
}).start();
return START_NOT_STICKY;
}
}
All works fine until i kill app from background. As soon as i kill app from background my service is restarted and music file will play from top.
I kill the application by swiping away the app in the Recent Apps.
Please help me.