Android foreground service gets killed on MI 4 dev

2019-05-28 15:56发布

问题:

I know this question is asked so many times but i didn't find any solution to keep service alive even if my app get killed. My application run on all devices but some devices if i kill the app then my service also killed (Device name MI 4 Version ans asus 5.0.3 )

following is my service code where i have started my foreground service

 @Override
    public int onStartCommand(Intent intent, int flags, int startId) { 
 Notification notification = new NotificationCompat.Builder(this)
                    .setContentTitle("My service started at ")
                    .setTicker("My service started")
                    .setContentText("app")
                    .setSmallIcon(R.drawable.app)
                    .setLargeIcon(Bitmap.createScaledBitmap(icon, 128, 128, false))
                    .setContentIntent(pendingIntent)
                    .setOngoing(true).build();
            startForeground(Constants.FOREGROUND_SERVICE,notification); 
}

回答1:

For this problem, i make many checkpoints for my TestService on various events i.e.

  1. NetworkChangeReceiver
  2. BootReceiver
  3. onCreate method of MainActivity

Then i have a class called ServiceDetector.java

import android.app.ActivityManager;
import android.content.Context;
import java.util.List;
public class ServiceDetector {
    // this method is very important
    public boolean isServiceRunning(Context context, Class<?> serviceClass) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE);

        if (services != null) {
            for (int i = 0; i < services.size(); i++) {
                if ((serviceClass.getName()).equals(services.get(i).service.getClassName()) && services.get(i).pid != 0) {
                    return true;
                }
            }
        }
        return false;
    }
}

Which checks if my service is running, Now if your service is not running then start it again

public void onReceive(Context context, Intent intent) {
        ServiceDetector serviceDetector = new ServiceDetector();
        if (!serviceDetector.isServiceRunning(context, TestService.class)) {
            Intent startServiceIntent = new Intent(context, TestService.class);
            context.startService(startServiceIntent);
        } else {
            Log.i(Constants.TAG, "Service is already running reboot");
        }
    }


回答2:

One workaround you can implement is to restart the service whenever it is removed. ie, using onTaskRemoved callback (link).

@Override
public void onTaskRemoved(Intent rootIntent) {
    // TODO Auto-generated method stub
    Intent restartService = new Intent(getApplicationContext(),
            this.getClass());
    restartService.setPackage(getPackageName());
    PendingIntent restartServicePI = PendingIntent.getService(
            getApplicationContext(), 1, restartService,
            PendingIntent.FLAG_ONE_SHOT);
    AlarmManager alarmService = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);
    alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() +1000, restartServicePI);

}