I have a service to scan Bluetooth Low Energy devices and show a notification. This works if the app is started or the the app is in background. But if the app was removed from background, the service is running but the bluetooth scan dont work. Can a service do something if the app is killed? Thank you.
2 Answers
Not clear about the question.
But based on my understanding about the above question, please find my inputs as follows. In extreme case if the Android system requires the memory, based on the importance of the processes it starts removing the processes in the order of least significant way. In this case if your app gets killed then there is no way the service from that app will continue to run. It also gets killed.
But one can put the process in which the service is running as Foreground process by startForground() method by which it is less likely gets killed.
If service component of the application & the whole application are running in two different processes & the process running the whole app gets killed but the process with the service running is still there then one need to check the dependencies such as BluetoothAdapter component or such things got killed by the app process & make sure that the service is stand alone component running in different process.

- 131
- 3
Thank you for the answer. The problem was that the Application Context was not available. I found a solution for this. I start a Alarmmanager and send every 15 minutes an intent. This intent is handled by my own receiver which is declared in the AndroidManifest.xml. If the intent is handled, the Application Context is available and i can start the service.
Start AlarmManager
Intent alarmIntent = new Intent(MyApp.getAppContext(),AlarmBroadcastReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(MyApp.getAppContext(), 0, alarmIntent, 0);
AlarmManager alarmMgr = (AlarmManager)MyApp.getAppContext().getSystemService(Context.ALARM_SERVICE);
alarmMgr.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
AlarmManager.INTERVAL_FIFTEEN_MINUTES,
AlarmManager.INTERVAL_FIFTEEN_MINUTES, pi);
Code for the Receiver
package com.example;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class AlarmBroadcastReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context arg0, Intent arg1) {
}
}
Declare Receiver in AndroidManifest.xml
<receiver
android:enabled="true"
android:name="com.example.AlarmBroadcastReceiver"
android:exported="false">
<intent-filter>
<action android:name="com.example.AlarmBroadcastReceiver.checkservice" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>

- 2,963
- 3
- 17
- 22