Julian Zienert
Julian Zienert

Reputation: 43

Android: Background Service always shuts down

Recent changes in Androids background task running behaviour makes it very difficult to keep Services alive and continue work in applications when the phone is locked. My Service is only working properly when the screen is on or the phone gets charged. When the phone is locked, the Service shuts down almost immediately or runs way too slow to be useful in any way.

I tried to use "START_STICKY" flag and a startForeground() Notification to keep the Service alive but this doens't help at all. I'm using a Handler that calls dowork() every 5 seconds, which then checks if theres something to do.

I want to perform a simple task on a certain time event: wake up every half/quarter or full hour, do some quick work without CPU limitation, then shut down until next time. The phone should wake up reliable and accurate on time and get "whitelisted" to use some CPU power for around half a minute. I don't do any intense work, that could affect user performance.

public class MyService extends Service {


public MyService() {
    super();

}


@Override
public IBinder onBind(Intent intent) {

    return null;
}

@Override public int onStartCommand(Intent intent, int flags, int startId) {

Intent notificationIntent = new Intent(this, MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); Notification notification = new NotificationCompat.Builder(this) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle("MyService") .setContentText("Service is running") .setPriority(IMPORTANCE_HIGH) .setContentIntent(pendingIntent).build(); startForeground(1, notification); final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { dowork(); handler.postDelayed(this, 5000); } }, 1500); return START_STICKY; }

Upvotes: 3

Views: 878

Answers (1)

Julian Zienert
Julian Zienert

Reputation: 43

For this question i want to refer to Alarm Manager Example . This one is doing it's job pretty well, i finally got it working that way.

Upvotes: 0

Related Questions