如何查看后台服务是否正在运行?
我想要一个切换服务状态的Android活动——它让我打开它,如果它是关闭的,如果它是关闭的。
如何查看后台服务是否正在运行?
我想要一个切换服务状态的Android活动——它让我打开它,如果它是关闭的,如果它是关闭的。
当前回答
如果服务属于另一个进程或APK,则使用基于ActivityManager的解决方案。
如果您可以访问它的源,只需使用基于静态字段的解决方案。但是我建议使用Date对象来代替布尔值。在服务运行时,只需将其值更新为'now',当它完成时将其设置为null。从活动中,您可以检查它是否为空或日期太旧,这将意味着它没有运行。
您还可以从您的服务发送广播通知,表明正在运行以及进一步的信息,如进度。
其他回答
另一种方法是使用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)
摘自Android文档:
比如sendBroadcast(Intent),但是如果有任何接收器 这个函数将阻塞并立即分发它们 返回之前。
你可以把这次入侵看成是"ping "服务。因为我们可以同步广播,所以我们可以在UI线程上同步广播并获得结果。
服务
@Override
public void onCreate() {
LocalBroadcastManager
.getInstance(this)
.registerReceiver(new ServiceEchoReceiver(), new IntentFilter("ping"));
//do not forget to deregister the receiver when the service is destroyed to avoid
//any potential memory leaks
}
private class ServiceEchoReceiver extends BroadcastReceiver {
public void onReceive (Context context, Intent intent) {
LocalBroadcastManager
.getInstance(this)
.sendBroadcastSync(new Intent("pong"));
}
}
活动
bool serviceRunning = false;
protected void onCreate (Bundle savedInstanceState){
LocalBroadcastManager.getInstance(this).registerReceiver(pong, new IntentFilter("pong"));
LocalBroadcastManager.getInstance(this).sendBroadcastSync(new Intent("ping"));
if(!serviceRunning){
//run the service
}
}
private BroadcastReceiver pong = new BroadcastReceiver(){
public void onReceive (Context context, Intent intent) {
serviceRunning = true;
}
}
当然,在许多应用程序中,赢家是服务上的静态布尔字段,在service . oncreate()中设置为true,在service . ondestroy()中设置为false,因为它要简单得多。
自Android 8(或Oreo)以来,API getRunningServices已弃用。 当然,你可以使用@SuppressWarnings("deprecation")来消除警告。
如果您的服务不需要有多个实例,那么如何在没有getrunningservices的情况下使用:使用单例模式。
public class MyMusicService extends Service {
private static MyMusicService instance = null;
public static boolean isMyMusicServiceRunning() {
return instance != null;
}
然后你可以调用MyMusicService。ismymusicservicerun从您的活动或其他地方。
检测服务是否正在运行的唯一有效/最快/干净的方法是创建PING/PONG功能。
在服务内部实现Messenger或AIDL方法:isAlive()——它返回服务的状态。
不要实现广播,因为它们可能被错过。
onDestroy并不总是在服务中调用,所以这是无用的!
例如:只需要对Eclipse做一点更改就可以再次运行应用程序。使用SIG: 9强制退出应用程序。