Android中查看服務是否開啟的工具類

來源:互聯網
上載者:User

Android中查看服務是否開啟的工具類

 這個也是昨天學習的,做下總結。

檢查服務是否開啟要寫成一個工具類,方便使用,傳服務的名字返回Boolean值,當然,因為需要,還要傳一個上下文context。

說一下這個工具類的幾個關鍵點:

1.方法要傳context和serviceName,context用來getSystemService()操作獲得ActivityManager。注意,這個方法參數要用大寫的Context中的參數:Context.ACTIVITY_SERVICE,要不然會出錯,還不知道哪錯的,花了我10分鐘的時間才知道,謹記下。

2.ActivityManager執行個體可以getRunningService()方法,參數是獲得服務最大數目,一般100就好。

3.上面的方法返回的事一個List,要對他進行遍曆,獲的每一個服務的名字,在比較,返回結果。

 

下面是具體代碼。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

import java.util.List;

 

import android.app.ActivityManager;

import android.app.ActivityManager.RunningServiceInfo;

import android.app.Service;

import android.content.Context;

 

public class ServiceStateUtiles {

     

    public static Boolean isServiceRunning(Context context, String serviceName) {

        //擷取服務方法  參數 必須用大寫的Context!!!

        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);

        List<runningserviceinfo> infos = am.getRunningServices(100);

        for (RunningServiceInfo info : infos) {

            String className = info.service.getClassName();

            if(serviceName.equals(className))

                return true;

        }

        return false;

    }

}</runningserviceinfo>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.