一些设备(如vivo)在杀死应用程序后会杀死我的前台服务?

6

我的前台服务在某些设备上,如vivo,在杀死应用程序后被终止了,有没有任何解决方法可以使其保持活动状态?

我正在使用前台服务,例如:

public class MyService extends IntentService {

    private final String TAG = "IntentService";
    private PowerManager.WakeLock wakeLock;

    public MyService() {
        super("MyService");
        setIntentRedelivery(true);
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        Log.d(TAG, "onHandleIntent: Service running");
        for (int i = 0; i < 20; i++) {
            Log.d(TAG, "onHandleIntent: service running status: " + i);
            SystemClock.sleep(3000);
        }
    }

    @Override
    public void onCreate() {
        Log.d(TAG, "onCreate: IntentService Created");
        super.onCreate();

        PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        this.wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                "Service: WakeLock");
        this.wakeLock.acquire();
        Log.d(TAG, "onCreate: Wakelock acquired");


        Notification notification = new NotificationCompat.Builder(this, App.NOTIFICATION_CHANNEL_ID)
                .setContentTitle("Intent Service")
                .setContentText("Service running in background")
                .setSmallIcon(android.R.drawable.sym_def_app_icon)
                .build();
        startForeground(12, notification);
    }

    @Override
    public void onDestroy() {
        Log.d(TAG, "onDestroy: IntentService Destroyed");
        super.onDestroy();
        this.wakeLock.release();
        Log.d(TAG, "onDestroy: Wakelock released");
    }
}


1
请让用户更改其电池节省设置。 - Tenclea
1
即使电池电量处于正常模式,前台服务也会在应用程序被杀死时立即停止。 - Anurag Mishra
1
还是不行。 - Anurag Mishra
1
@IgorSkryl 如何让应用在后台运行? - Anurag Mishra
2
应用商店链接:https://play.google.com/store/apps/details?id=ch.blinkenlights.android.vanilla 和 Github 链接:https://github.com/vanilla-music/vanilla 开源应用程序。 - Abdur Rehman
显示剩余5条评论
1个回答

0

我使用了一个变通方法使其有效。

像这样注册一个假的静态隐式接收器:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

<receiver android:name=".SampleBroadcast">
   <intent-filter>
      <action android:name="android.intent.action.BOOT_COMPLETED" />
   </intent-filter>
</receiver>

我的示例广播文件:

public class SampleBroadcast extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
            Log.d("Foreground App", "Boot Completed");
        }

    }
}

这使得我的应用程序被放置在操作系统的自启动部分。
现在,当我启动我的服务时,即使我杀死应用程序,它仍然在运行。

这个在我的情况下不起作用,你能分享一下如何使用的详细信息吗? - Faizan Ahmad

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接