gpt4 book ai didi

Android 前台服务在 MI 4 设备(版本 5.0.2)上被杀死

转载 作者:搜寻专家 更新时间:2023-11-01 07:47:14 25 4
gpt4 key购买 nike

我知道这个问题被问了很多次,但我没有找到任何解决方案来保持服务,即使我的应用程序被杀死。 我的应用程序在所有设备上运行,但某些设备如果我终止该应用程序,那么我的服务也会终止(设备名称 MI 4 版本 ans asus 5.0.3)

以下是我启动前台服务的服务代码

 @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);
}

最佳答案

对于这个问题,我在各种事件上为我的 TestService 创建了很多检查点即

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

然后我有一个名为 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;
}
}

检查我的服务是否正在运行,现在如果你的服务没有运行则重新启动它

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");
}
}

关于Android 前台服务在 MI 4 设备(版本 5.0.2)上被杀死,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41462286/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com