簡體   English   中英

如何在android中檢查服務是否已經運行?

[英]How to check if a service is already running or not in android?

在我的項目中,我在單擊按鈕時啟動服務。 但是,當單擊該按鈕時,我不想再次啟動該服務,除非前一個按鈕已經停止。 所以我需要先檢查服務是否正在運行。 我使用以下方法

private boolean isMyServiceRunning() {
    ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if ("com.example.MyService".equals(service.service.getClassName())) {
            return true;
        }
    }
    return false;
}

但它不適合我,它不會給出任何異常,但總是返回false。 我現在應該怎么辦?

我認為您的服務未列在正在運行的服務中的原因是您啟動服務的方式。 以下提議您采用方法的線程相同

You MUST call startService for your service to be properly registered and
passing BIND_AUTO_CREATE will not suffice.

如下:

Intent bindIntent = new Intent(this,ServiceTask.class);
startService(bindIntent);
bindService(bindIntent,mConnection,0);

試試這個,看看它是否適合你。

您的方法返回false,因為在停止之后,如果沒有任何客戶端綁定到服務,則系統會破壞進程。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM