I'm having a really strange issue, the broadcast receiver is not working on my own device but is on the android emulator. What does my application is restarting the service by calling the broadcast receiver everytime onDestroy method is called. I even tried to look at developer option on my device to see if the was some restriction activated like "not keep activities", but it was unchecked.
Xml file
<service
android:name="oak.shef.ac.uk.testrunningservicesbackgroundrelaunched.SensorService"
android:enabled="true">
</service>
<receiver
android:name="oak.shef.ac.uk.testrunningservicesbackgroundrelaunched.SensorRestarterBroadcastReceiver"
android:enabled="true"
android:exported="true"
android:label="RestartServiceWhenStopped"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="SensorRestarterBroadcastReceiver" />
</intent-filter>
</receiver>
Service
public class SensorService extends Service {
private Timer timer;
MyThread myThread;
private TimerTask timerTask;
public int counter=0;
public SensorService(Context applicationContext) {
super();
Log.i("HERE", "here I am!");
}
public SensorService() {
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
myThread = new MyThread();
myThread.start();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i("EXIT", "ondestroy!");
Intent restartService = new Intent("SensorRestarterBroadcastReceiver");
sendBroadcast(restartService);
timer.cancel();
myThread.interrupt();
}
public class MyThread extends Thread{
@Override
public void run() {
// TODO Auto-generated method stub
try {
int delay = 10000; // delay for 10 sec.
int period = 10000; // repeat every 10 sec.
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
Log.i("in timer", "in timer ++++ "+ (counter++));
}
}, delay, period);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
Brodcast Receiver
public class SensorRestarterBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.i(SensorRestarterBroadcastReceiver.class.getSimpleName(),
"Restarting Service");
context.startService(new Intent(context, SensorService.class));;
}
}