Dim*_*Dim 6 android android-service kotlin
I am running foreground services in my app and I need to deremine if they running in my activity. From my searches I found that this is the option:
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
}
Run Code Online (Sandbox Code Playgroud)
but:
getRunningServices(Int): is deprecated.
So I am using one of 3 ways.
What is the most correct way to check if service is running?
小智 9
在服务本身中创建一个静态布尔值。在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;
}}
Run Code Online (Sandbox Code Playgroud)
现在,您可以通过 boolean ActivityService.IS_ACTIVITY_RUNNING 检查您的活动是否正在运行
| 归档时间: |
|
| 查看次数: |
8796 次 |
| 最近记录: |