当我清除所有最近的应用程序时,Android系统会在Android v7.1.2上终止我的应用程序服务

时间:2018-07-12 10:23:57

标签: android android-background android-backup-service

enter image description here我想创建一个在后台运行的应用程序。我已经尝试了所有stackoverflow解决方案。当我自己清除该应用程序时,这些解决方案都可以使用。但是当我执行“清除所有最近的应用程序”时。服务停止。我正在使用Android v7.1.2 Android牛轧糖。

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
            log("Received start command flags:%d, startId:%d", flags, startId);
            Notification.Builder builder = new Notification.Builder(SOSService.this);
            builder.setSmallIcon(R.mipmap.ic_launcher)
                    .setContentText("Ambysure SOS App is running")
                    .setAutoCancel(false);
            Notification notification = builder.getNotification();
            notification.flags |= Notification.FLAG_NO_CLEAR
                    | Notification.FLAG_ONGOING_EVENT; 
            startForeground(100, notification);
            return START_STICKY;
        }



@Override
public void onDestroy() {
    super.onDestroy();
    Log.i("EXIT", "ondestroy!");
    Intent myIntent = new Intent(getApplicationContext(), SOSService.class);
    PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 0, myIntent, 0);
    AlarmManager alarmManager1 = (AlarmManager) getSystemService(ALARM_SERVICE);
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.add(Calendar.SECOND, 10);
    alarmManager1.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
    Toast.makeText(getApplicationContext(), "Start Alarm", Toast.LENGTH_SHORT).show();
}

@Override
public void onTaskRemoved(Intent rootIntent) {
    super.onTaskRemoved(rootIntent);
    Log.i("TASKREMOVED", "onTaskRemoved!");
    Intent myIntent = new Intent(getApplicationContext(), SOSService.class);
    PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 0, myIntent, 0);
    AlarmManager alarmManager1 = (AlarmManager) getSystemService(ALARM_SERVICE);
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.add(Calendar.SECOND, 10);
    alarmManager1.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
   Log.i("TASKREMOVED", "Start Alarm!");
}

2 个答案:

答案 0 :(得分:1)

某些手机不允许在后台运行app,例如oppo,小米,华为等。要解决此问题,请尝试Link

答案 1 :(得分:1)

感谢@ code4rox。我正在使用小米手机,因此需要启用自动启动权限。下面的代码运行良好。

if (Build.BRAND.equalsIgnoreCase("Xiaomi")) {
    Intent intent1 = new Intent();
    intent1.setComponent(new ComponentName("com.miui.securitycenter", "com.miui.permcenter.autostart.AutoStartManagementActivity"));
    startActivity(intent1);
}