我正在我的应用程序中运行前台服务,我需要确定它们是否在我的活动中运行。 从我的搜索中我发现这是一个选项:
private fun isMyServiceRunning(serviceClass: Class<*>): Boolean {
val manager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
for (service in manager.getRunningServices(Int.MAX_VALUE)) {
if (serviceClass.name == service.service.className) {
return true
}
}
return false
}
但是:
getRunningServices(Int):已弃用。
所以我使用三种方法之一。
检查服务是否正在运行的最正确方法是什么?
在服务本身中创建一个静态布尔值。 在onCreate中使其为真; 在 onDestroy() 中将其设置为 false;
public class ActivityService extends Service {
public static boolean IS_ACTIVITY_RUNNING = false;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
IS_ACTIVITY_RUNNING = true;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(!IS_ACTIVITY_RUNNING)
stopSelf();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
IS_ACTIVITY_RUNNING = false;
}}
现在,您可以通过 boolean ActivityService.IS_ACTIVITY_RUNNING 检查您的 Activity 是否正在运行
在 kotlin 中这对我有用->
@Suppress("DEPRECATION")
fun <T> Context.isServiceRunning(service: Class<T>): Boolean {
return (getSystemService(ACTIVITY_SERVICE) as ActivityManager)
.getRunningServices(Integer.MAX_VALUE)
.any { it -> it.service.className == service.name }
}
在此之后你可以调用该函数,例如->
context.isServiceRunning(MyService::class.java)
您可以在
SharedPreferences
的 onCreate
方法中创建一个 Service
并在其中附加一些布尔值。
getSharedPreferences( getString( R.string.app_name ) , Context.MODE_PRIVATE )
.edit()
.putBoolean( getString( R.string.service_running_status_key ) , true )
.apply()
类似地,在
onDestroy
方法中,将 false
附加到同一个键。然后,您可以使用 SharedPreferences.getBoolean
检查 Service
是否在前台运行。
在 kotlin 中,在伴生对象中创建一个 @JvmStatic 布尔状态。然后在onCreate中设置为ture,在onDestroy中设置为false。然后你就可以阅读了。
class ScreenRecorderService : LifecycleService(){
companion object {
private var running = false
@JvmStatic
fun start(context: Context) {
context.startService(Intent(context, ScreenRecorderService::class.java))
}
@JvmStatic
fun stop(context: Context) {
context.stopService(Intent(context, ScreenRecorderService::class.java))
}
}
override fun onCreate() {
super.onCreate()
running = true
}
override fun onDestroy() {
super.onDestroy()
running = false
}
}