Android Service setForeground While Display Sleeps
- by c12
I have a background Android Service that's purpose is to communicate with another device (non-phone) using a Bluetooth socket. Everything works fine except that the service gets stopped and restarted by the OS when the phone display is sleeping. This restart sometimes leaves a 15-20 minute gaps where there is no communication between the Service and the Bluetooth device and I need to be able to query the device every minute. Is startForeground the proper approach?
Attempted to use:
startForeground(int, Notification) //still see gaps when phone sleeps
Service:
public class ForegroundBluetoothService extends Service{
private boolean isStarted = false;
@Override
public void onDestroy() {
super.onDestroy();
stop();
}
/**
* @see android.app.Service#onBind(android.content.Intent)
*/
@Override
public IBinder onBind(Intent intent) {
return null;
}
/**
* @see android.app.Service#onStartCommand(android.content.Intent, int, int)
*/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
loadServiceInForeground();
return(START_STICKY);
}
private void loadServiceInForeground() {
if (!isStarted) {
isStarted=true;
Notification notification = new Notification(R.drawable.icon, "Service is Running...", System.currentTimeMillis());
Intent notificationIntent = new Intent(this, MainScreen.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, "Notification Title",
"Service is Running...", pendingIntent);
startForeground(12345, notification);
try{
queryTheBluetoothDevice();
} catch(Exception ex){
ex.printStackTrace();
}
}
}
private void stop() {
if (isStarted) {
isStarted=false;
stopForeground(true);
}
}
}