我知道这个问题被问了很多次,但我没有找到任何解决方案来保持服务,即使我的应用程序被杀死。
我的应用程序在所有设备上运行,但是一些设备如果我杀死该应用程序,那么我的服务也会被杀死(设备名称 MI 4 版本和 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 设置了许多检查点
IE。
- 网络变更接收器
- 引导接收器
- MainActivity 的 onCreate 方法
然后我有一个名为 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");
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)