2、判定服务运行工具类
package kim.hsl.two_progress_alive; import android.app.Activity; import android.app.ActivityManager; import android.content.Context; import android.text.TextUtils; import org.w3c.dom.Text; import java.util.List; public class ServiceUtils { /** * 判定 Service 是否在运行 * @param context * @return */ public static boolean isServiceRunning(Context context, String serviceName){ if(TextUtils.isEmpty(serviceName)) return false; ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); // 最多获取 200 个正在运行的 Service List<ActivityManager.RunningServiceInfo> infos = activityManager.getRunningServices(200); // 遍历当前运行的 Service 信息, 如果找到相同名称的服务 , 说明某进程正在运行 for (ActivityManager.RunningServiceInfo info: infos){ if (TextUtils.equals(info.service.getClassName(), serviceName)){ return true; } } return false; } }
3、清单文件
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="kim.hsl.two_progress_alive"> <uses-permission android:name="android.permission.FOREGROUND_SERVICE" /> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.Two_Progress_Alive"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!-- 本地提权前台服务 Service --> <service android:name=".LocalForegroundService" android:enabled="true" android:exported="true"></service> <!-- 本地服务 , API 18 ~ 25 以上的设备, 关闭通知到专用服务 --> <service android:name=".LocalForegroundService$CancelNotificationService" android:enabled="true" android:exported="true"></service> <!-- 远程提权前台服务 Service --> <service android:name=".RemoteForegroundService" android:enabled="true" android:exported="true" android:process=":remote"></service> <!-- 远程服务 , API 18 ~ 25 以上的设备, 关闭通知到专用服务 --> <service android:name=".RemoteForegroundService$CancelNotificationService" android:enabled="true" android:exported="true" android:process=":remote"></service> <!-- JobScheduler 拉活 --> <service android:name=".KeepAliveJobService" android:enabled="true" android:exported="true" android:permission="android.permission.BIND_JOB_SERVICE"></service> </application> </manifest>