As per my Searching :
To run a service in back ground you have to create a STICKY service with flag START_STICKY.
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Do your task here
return START_STICKY;
}
An START_STICKY service can run in background without any activity presence . And you can communicate with service with callbacks.
But, the issue is :
When I killed the application, And Since I am using START_STICKY, onCreate() and onStartCommand() method called again.
But, What If I wanna to continue running service without destroying it when application killed ?
Actually, I am using media player. code is as below :
Service :
public class MyService extends Service {
private MediaPlayer media;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "on create", Toast.LENGTH_SHORT).show();
media = MediaPlayer.create(this, Settings.System.DEFAULT_RINGTONE_URI);
media.setLooping(true);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "on start command", Toast.LENGTH_SHORT).show();
if (media!=null && !media.isPlaying()) {
media.start();
}else{
Toast.makeText(this, "media is not playing", Toast.LENGTH_SHORT).show();
}
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
media.stop();
Toast.makeText(this, "service on destroy", Toast.LENGTH_SHORT).show();
}
Service Calls :
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void startMethod(View v) {
startService(new Intent(this, MyService.class));
}
public void stopMethod(View v) {
stopService(new Intent(this, MyService.class));
}
}
So, How media player keeps running without any stop ? Right now, it stops when i am killing the app and starting again when onCreate() and onStartCommand() methods of Service is calling again since i am using START_STICKY.