I am playing the music and i want to play it in background also but there is a bug that when i kill the app music restarts and also i checked with some toast that oncreate method of service class is called again , how should i do that
public class MyMusicService extends Service {
MediaPlayer mediaPlayer;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
public MyMusicService() {
super();
}
@Override
public void onCreate() {
super.onCreate();
Toast.makeText(getApplicationContext(),"oncreate",Toast.LENGTH_SHORT).show();
if (mediaPlayer!= null)
{
mediaPlayer.release();
}
mediaPlayer =MediaPlayer.create(this,R.raw.song);
mediaPlayer.setLooping(true);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(getApplicationContext(),"start",Toast.LENGTH_SHORT).show();
mediaPlayer.start();
return START_STICKY;
}
@Override
public void onDestroy() {
Toast.makeText(getApplicationContext(),"destroy",Toast.LENGTH_SHORT).show();
super.onDestroy();
mediaPlayer.stop();
mediaPlayer.release();
}
}