the best to do this is create custom service that extends your service not intent Service. and start a separate thread in your service. start service in the launching of app
One more important this dont bind it to any object cause service will be killed once your object destroyed.
then onStartCommand() method return START_STICKY
I will give you the sample implementation.
public class CustomService extends Service {
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
return START_STICKY;
}
@Override
public void onTaskRemoved(Intent rootIntent) {
// TODO Auto-generated method stub
Intent restartService = new Intent(getApplicationContext(),
this.getClass());
restartService.setPackage(getPackageName());
PendingIntent restartServicePI = PendingIntent.getService(
getApplicationContext(), 1, restartService,
PendingIntent.FLAG_ONE_SHOT);
//Restart the service once it has been killed android
AlarmManager alarmService = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() +100, restartServicePI);
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
//start a separate thread and start listening to your network object
}
}
onTaskRemoved restarts your service after 100milli seconds once it is killed. START_STICKY doesnt work in kitkat. You have to implement onTAskRemoved. And one more thing if the user goes to app settings and stops your service then there is no way you can restart it