获取正在运行的服务

手机上安装的App,在后台运行着很多不同功能的服务,最常见的例如消息推送相关的服务。如何查看这些服务?如何判断某个服务是否正在运行?如何停止某一个服务呢?请看下面的方法:

package com.example.servicelistdemo;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ListView lv = (ListView) findViewById(R.id.lvService);
        List<String> serviceList = new ArrayList<String>();

        //获取服务列表
        ActivityManager activityManager = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningServiceInfo> runningServicesList = activityManager.getRunningServices(Integer.MAX_VALUE);
        for(RunningServiceInfo si: runningServicesList){
            serviceList.add(si.service.getClassName());
        }

        ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, serviceList);
        lv.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }

    /**
     * 用来判断服务是否运行.
     *
     * @param ctx       Context
     * @param className 判断的服务的名字 "com.xxx.xx..XXXService"
     * @return true 在运行, false 不在运行
     */
    public static boolean isServiceRunning(Context ctx, String className) {
        boolean isRunning = false;
        ActivityManager manager = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningServiceInfo> servicesList = manager.getRunningServices(Integer.MAX_VALUE);
        Iterator<RunningServiceInfo> iterator = servicesList.iterator();
        while (iterator.hasNext()) {
            RunningServiceInfo service = (RunningServiceInfo) iterator.next();
            if (className.equals(service.service.getClassName())) {
                isRunning = true;
            }
        }
        return isRunning;
    }

    /**
     * 停止服务.
     *
     * @param ctx       Context
     * @param className 服务的名字 
     * @return true 在运行, false 不在运行
     */
    public static boolean stopRunningService(Context ctx, String className) {
        Intent intent_service = null;
        boolean ret = false;
        try {
            intent_service = new Intent(ctx, Class.forName(className));
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (intent_service != null) {
            ret = ctx.stopService(intent_service);
        }
        return ret;
    }
}

代码很好理解,就不详细分析了,运行效果图如下:
手机服务列表

posted on 2017-10-20 19:00  lishbo  阅读(290)  评论(0编辑  收藏  举报