I have been searching in the entire web understanding why my background service is not working. When I close the application the service is killed without being called back from the Brodcast Receiver. This guide : https://www.quora.com/How-do-I-keep-an-app-running-in-the-background-in-MIUI shows three different methods and none of them is working for me. I'm sure that the application is perfectly working because it works fine with the emulator, same API 24, and it worked with a huawei aswell, again same API.
XML
<service
android:name="com.arvi.neverendingbackgroundservice.SensorService"
android:enabled="true"
android:exported="true"
android:stopWithTask="false">
</service>
<receiver
android:name="com.arvi.neverendingbackgroundservice.SensorRestartBroadcastReceiver"
android:enabled="true"
android:exported="true"
android:label="RestartServiceWhenStopped">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.QUICKBOOT_POWERON"/>
</intent-filter>
</receiver>
Service
public class SensorService extends Service {
private Context ctx;
TimerCounter tc;
private int counter = 0;
private static final String TAG = SensorService.class.getSimpleName();
public SensorService() {
}
public SensorService(Context applicationContext) {
super();
ctx = applicationContext;
Log.i(TAG, "SensorService class");
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "onCreate()");
tc = new TimerCounter();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
Log.i(TAG, "onStartCommand()");
tc.startTimer(counter);
return START_STICKY;
}
@Override
public void onDestroy() {
Log.i(TAG, "serviceOnDestroy()");
super.onDestroy();
Intent broadcastIntent = new Intent(getApplicationContext(),SensorRestartBroadcastReceiver.class);
sendBroadcast(broadcastIntent);
tc.stopTimerTask();
}
@Override
public void onTaskRemoved(Intent rootIntent) {
Log.i(TAG, "serviceonTaskRemoved()");
// workaround for kitkat: set an alarm service to trigger service again
Intent intent = new Intent(getApplicationContext(), SensorService.class);
PendingIntent pendingIntent = PendingIntent.getService(this, 1, intent, PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime() + 5000, pendingIntent);
super.onTaskRemoved(rootIntent);
}
@Override
public void onLowMemory() {
super.onLowMemory();
Log.i(TAG, "onLowMemory()");
}
}