如何查看后台服务是否正在运行?
我想要一个切换服务状态的Android活动——它让我打开它,如果它是关闭的,如果它是关闭的。
如何查看后台服务是否正在运行?
我想要一个切换服务状态的Android活动——它让我打开它,如果它是关闭的,如果它是关闭的。
当前回答
在serviceclass内部定义:
public static Boolean serviceRunning = false;
然后在onStartCommand(…)
public int onStartCommand(Intent intent, int flags, int startId) {
serviceRunning = true;
...
}
@Override
public void onDestroy()
{
serviceRunning = false;
}
然后,调用if(serviceclass。serviceRunning == true)。
其他回答
另一种方法是使用kotlin。启发了其他用户的回答
fun isMyServiceRunning(serviceClass: Class<*>): Boolean {
val manager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
return manager.getRunningServices(Integer.MAX_VALUE)
.any { it.service.className == serviceClass.name }
}
作为kotlin扩展
fun Context.isMyServiceRunning(serviceClass: Class<*>): Boolean {
val manager = this.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
return manager.getRunningServices(Integer.MAX_VALUE)
.any { it.service.className == serviceClass.name }
}
使用
context.isMyServiceRunning(MyService::class.java)
对于这里给出的用例,我们可以简单地使用stopService()方法的返回值。如果存在指定的服务并且该服务被终止,则返回true。否则返回false。因此,如果结果为false,您可以重新启动服务,否则可以确保当前服务已停止。(收集如果你看一下这个就更好了。
同样,如果使用pending intent(例如使用AlarmManager),人们可能会发现另一种替代方法更干净:
public static boolean isRunning(Class<? extends Service> serviceClass) {
final Intent intent = new Intent(context, serviceClass);
return (PendingIntent.getService(context, CODE, intent, PendingIntent.FLAG_NO_CREATE) != null);
}
CODE是一个常量,您在类中私有地定义它,以标识与您的服务相关联的挂起意图。
如果你有一个多模块的应用程序,你想知道服务是否从一个模块运行,这取决于包含该服务的模块,你可以使用这个函数:
fun isServiceRunning(context: Context, serviceClassName: String): Boolean {
val manager = ContextCompat.getSystemService(
context,
ActivityManager::class.java
) ?: return false
return manager.getRunningServices(Integer.MAX_VALUE).any { serviceInfo ->
serviceInfo.service.shortClassName.contains(vpnServiceClassName)
}
}
MyService服务用法:
isServiceRunning(context, "MyService")
如果服务类名称更改而调用函数没有相应更改,则此函数可能无法正常工作。
/**
* Check if the service is Running
* @param serviceClass the class of the Service
*
* @return true if the service is running otherwise false
*/
public boolean checkServiceRunning(Class<?> serviceClass){
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE))
{
if (serviceClass.getName().equals(service.service.getClassName()))
{
return true;
}
}
return false;
}