[英]Android - Check if startup service is running
我的應用程序在啟動時運行服務(Service.java)。 我需要知道何時手動啟動應用程序(在Main.java中)是否仍在運行我的服務。 在onCreate上在Main.java上執行以下代碼:
if(isMyServiceRunning(Service.class)){
System.out.println("Still running");
}
isMyServiceRunning函數:
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
問題是,即使服務仍在運行, isMyServiceRunning
返回false! 怎么解決呢?
與使用該方法不同,我將使用getter / setter在應用程序對象中創建一個布爾成員。 在服務onCreate()中,將設置標志,然后可以從活動內部的任何點查詢該標志。
在您的應用程序對象類(假定為MyApplication.java)中:
private boolean serviceRunning = false;
public boolean isServiceRunning() {
return serviceRunning;
}
public void setServiceRunning(boolean serviceRunning) {
this.serviceRunning = serviceRunning;
}
然后,在內部服務的onCreate()中:
((MyApplication)getApplication()).setServiceRunning(true);
然后,從活動的任何位置檢查服務狀態:
if(((MyApplication)getApplication()).isServiceRunning()){
//do the stuff here
}
希望能幫助到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.