I am trying to create a service that runs on the background, checks information and give notifications when needed. I have tried several examples on the internet which are basically the same, but I don't get them to work.
I have a service and a BroadcastReceiver. When I start the app, the service is created and a time logs at each tick. So, this works fine. At the onDestroy I have set up a new intent which I send with the "sendBroadcast(...)". The BroadcastReceiver-class has a override on onReceive, which should log a simple text. But I never see the text.
The service
public class ServiceNoDelay extends Service {
public int counter = 0;
Context context;
public ServiceNoDelay(Context applicationContext) {
super();
context = applicationContext;
Log.i("HERE", "here service created!");
}
public ServiceNoDelay() {
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
startTimer();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i("EXIT", "ondestroy!");
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("com.custom.package.RestartSensor");
sendBroadcast(broadcastIntent);
stoptimertask();
Log.i("EXIT", "Broadcast send!");
}
private Timer timer;
private TimerTask timerTask;
public void startTimer() {
//set a new Timer
timer = new Timer();
//initialize the TimerTask's job
initializeTimerTask();
//schedule the timer, to wake up every 1 second
timer.schedule(timerTask, 1000, 1000); //
}
public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
Log.i("in timer", "in timer ++++ " + (counter++));
}
};
}
public void stoptimertask() {
//stop the timer, if it's not already null
if (timer != null) {
timer.cancel();
timer = null;
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
The BroadcastReceiver
public class SensorRestarterBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.i(SensorRestarterBroadcastReceiver.class.getSimpleName(), "Service Stops! Oops!!!!");
context.startService(new Intent(context, ServiceNoDelay.class));
}
}
The manifest-part
<service
android:name=".ServiceNoDelay"
android:enabled="true" />
<receiver
android:name=".SensorRestarterBroadcastReceiver"
android:enabled="true"
android:exported="true"
android:label="RestartServiceWhenStopped">
<intent-filter>
<action android:name="com.custom.package.RestartSensor" />
</intent-filter>
</receiver>
The part of code I call in the MainActivity
ServiceNoDelay mSensorService = new ServiceNoDelay(getApplicationContext());
Intent mServiceIntent = new Intent(getApplicationContext(), mSensorService.getClass());
startService(mServiceIntent);
I expect that logcat will display "Service Stops! Oops!!!!" when the app closes, so I can reactivate the service again.
If I am looking a the wrong path to show notifications after the app is closed; I am open to suggestions.