Android中获取正在运行的服务-------ActivityManager.RunningServiceInfo的使用

时间:2023-03-09 06:58:15
Android中获取正在运行的服务-------ActivityManager.RunningServiceInfo的使用

关于PackageManager和ActivityManager的使用 ,自己也写了一些DEMO 了,基本上写的线路参考了Settings模块下的

应用程序,大家如果真正的有所兴趣,建议大家看看源码,不过丑化说在前面,我自己也没怎么看过这方面的源码,只在

需要的时候,才跑过去翻翻。

今天,在耐着最后一点性子,写下了这篇博文,基本上完成了整个应用程序功能模块的介绍,大家也在此系列上慢慢拓展。

  ActivityManager.RunningServiceInfo类:  封装了正在运行的服务信息

 

获取系统里所有真正运行的服务是通过调用ActivityManager方法来得到的,具体方法如下:

List<ActivityManager.RunningServiceInfo> getRunningServices (int maxNum)

                         功能:返回所有正在运行的服务

参数:   maxNum 代表我们希望返回的服务数目大小,一般给个稍大的值即可, 例如,50 。 

ActivityManager.RunningServiceInfo 类

  常用字段:

long   activeSince        服务第一次被激活的时间, 包括启动和绑定方式

int      clientCount          如果该Service是通过Bind方法方式连接,则clientCount代表了service连接客户端的数目

int      crashCount          服务运行期间,出现死机的次数

boolean   foreground   若为true,则该服务在后台执行

int        pid                          如果不为0,表示该service所在的进程ID号( PS:为0的话我也不清楚 - - 求指点)

int        uid                          用户ID 类似于Linux的用户权限,例如root等

String   process                 进程名,默认是包名或者由属性android:process指定

ComponentName  service          获得该Service的组件信息 包含了pkgname / servicename信息

 

PackageManger类

   说明: 封装了对应用程序信息的操作

获得应用程序信息的的方法如下:

public abstractApplicationInfo  getApplicationInfo(String  packageName, int flags)

参数:packagename 包名

flags 该ApplicationInfo是此flags标记,通常可以直接赋予常数0即可

功能:返回ApplicationInfo对象

        关于PackageManger更多信息,请查看<Android中获取应用程序(包)的信息-----PackageManager的使用(一)>

 

   Task任务的使用,我也就不在赘述了,大家可以仔细看下SDK,在此推荐一篇博客来帮助大家理解。

          《Android系统的进程,任务,服务的信息

Demo说明:

 

         我们获取了系统里正在运行的服务信息,包括包名,图标,service类名等。为了达到Settings下应用程序模块中的

正在运行服务的效果,我们点击某一服务后,理论上来说是可以停止该服务的,但是由于权限permissions不够,可能报

SecurityException异常,导致应用程序发生异常。

关于权限不够的问题,可以分为两种:

1、 在AndroidManifest.xml文件中,为<activity/>或<service/>节点指定android:permission属性时,在其他进程中操作时,

需要 声明该permission权限 。 具体可以参考下面这篇文章:

  《android 自定义权限 permission》

2、 系统权限,这个咱就没什么话说了。 可以参考下面这篇文章。

                                   《android.uid.system 获取系统权限 》

 

 

    截图如下:(加上了水印,请谅解)

Android中获取正在运行的服务-------ActivityManager.RunningServiceInfo的使用

老规矩,资源文件不在贴了。 主工程逻辑如下:

 

  1. package com.qin.runservice;
  2. import java.util.ArrayList;
  3. import java.util.Collections;
  4. import java.util.Comparator;
  5. import java.util.List;
  6. import android.app.Activity;
  7. import android.app.ActivityManager;
  8. import android.app.AlertDialog;
  9. import android.app.Dialog;
  10. import android.content.ComponentName;
  11. import android.content.Context;
  12. import android.content.DialogInterface;
  13. import android.content.Intent;
  14. import android.content.pm.ApplicationInfo;
  15. import android.content.pm.PackageManager;
  16. import android.content.pm.PackageManager.NameNotFoundException;
  17. import android.os.Bundle;
  18. import android.os.Debug;
  19. import android.util.Log;
  20. import android.view.ContextMenu;
  21. import android.view.Menu;
  22. import android.view.MenuItem;
  23. import android.view.View;
  24. import android.view.ContextMenu.ContextMenuInfo;
  25. import android.widget.AdapterView;
  26. import android.widget.ListView;
  27. import android.widget.TextView;
  28. import android.widget.AdapterView.OnItemClickListener;
  29. public class BrowseRunningServiceActivity extends Activity implements
  30. OnItemClickListener {
  31. private static String TAG = "RunServiceInfo";
  32. private ActivityManager mActivityManager = null;
  33. // ProcessInfo Model类 用来保存所有进程信息
  34. private List<RunSericeModel> serviceInfoList = null;
  35. private ListView listviewService;
  36. private TextView tvTotalServiceNo;
  37. public void onCreate(Bundle savedInstanceState) {
  38. super.onCreate(savedInstanceState);
  39. setContentView(R.layout.browse_service_list);
  40. listviewService = (ListView) findViewById(R.id.listviewService);
  41. listviewService.setOnItemClickListener(this);
  42. tvTotalServiceNo = (TextView) findViewById(R.id.tvTotalServiceNo);
  43. // 获得ActivityManager服务的对象
  44. mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
  45. // 获得正在运行的Service信息
  46. getRunningServiceInfo();
  47. // 对集合排序
  48. Collections.sort(serviceInfoList, new comparatorServiceLable());
  49. System.out.println(serviceInfoList.size() + "-------------");
  50. // 为ListView构建适配器对象
  51. BrowseRunningServiceAdapter mServiceInfoAdapter = new
  52. BrowseRunningServiceAdapter(BrowseRunningServiceActivity.this, serviceInfoList);
  53. listviewService.setAdapter(mServiceInfoAdapter);
  54. tvTotalServiceNo.setText("当前正在运行的服务共有:" + serviceInfoList.size());
  55. }
  56. // 获得系统正在运行的进程信息
  57. private void getRunningServiceInfo() {
  58. // 设置一个默认Service的数量大小
  59. int defaultNum = 20;
  60. // 通过调用ActivityManager的getRunningAppServicees()方法获得系统里所有正在运行的进程
  61. List<ActivityManager.RunningServiceInfo> runServiceList = mActivityManager
  62. .getRunningServices(defaultNum);
  63. System.out.println(runServiceList.size());
  64. // ServiceInfo Model类 用来保存所有进程信息
  65. serviceInfoList = new ArrayList<RunSericeModel>();
  66. for (ActivityManager.RunningServiceInfo runServiceInfo : runServiceList) {
  67. // 获得Service所在的进程的信息
  68. int pid = runServiceInfo.pid; // service所在的进程ID号
  69. int uid = runServiceInfo.uid; // 用户ID 类似于Linux的权限不同,ID也就不同 比如 root等
  70. // 进程名,默认是包名或者由属性android:process指定
  71. String processName = runServiceInfo.process;
  72. // 该Service启动时的时间值
  73. long activeSince = runServiceInfo.activeSince;
  74. // 如果该Service是通过Bind方法方式连接,则clientCount代表了service连接客户端的数目
  75. int clientCount = runServiceInfo.clientCount;
  76. // 获得该Service的组件信息 可能是pkgname/servicename
  77. ComponentName serviceCMP = runServiceInfo.service;
  78. String serviceName = serviceCMP.getShortClassName(); // service 的类名
  79. String pkgName = serviceCMP.getPackageName(); // 包名
  80. // 打印Log
  81. Log.i(TAG, "所在进程id :" + pid + " 所在进程名:" + processName + " 所在进程uid:"
  82. + uid + "\n" + " service启动的时间值:" + activeSince
  83. + " 客户端绑定数目:" + clientCount + "\n" + "该service的组件信息:"
  84. + serviceName + " and " + pkgName);
  85. // 这儿我们通过service的组件信息,利用PackageManager获取该service所在应用程序的包名 ,图标等
  86. PackageManager mPackageManager = this.getPackageManager(); // 获取PackagerManager对象;
  87. try {
  88. // 获取该pkgName的信息
  89. ApplicationInfo appInfo = mPackageManager.getApplicationInfo(
  90. pkgName, 0);
  91. RunSericeModel runService = new RunSericeModel();
  92. runService.setAppIcon(appInfo.loadIcon(mPackageManager));
  93. runService.setAppLabel(appInfo.loadLabel(mPackageManager) + "");
  94. runService.setServiceName(serviceName);
  95. runService.setPkgName(pkgName);
  96. // 设置该service的组件信息
  97. Intent intent = new Intent();
  98. intent.setComponent(serviceCMP);
  99. runService.setIntent(intent);
  100. runService.setPid(pid);
  101. runService.setProcessName(processName);
  102. // 添加至集合中
  103. serviceInfoList.add(runService);
  104. } catch (NameNotFoundException e) {
  105. // TODO Auto-generated catch block
  106. System.out.println("--------------------- error -------------");
  107. e.printStackTrace();
  108. }
  109. }
  110. }
  111. // 触摸可停止
  112. @Override
  113. public void onItemClick(AdapterView<?> arg0, View arg1, int position,
  114. long arg3) {
  115. // TODO Auto-generated method stub
  116. final Intent stopserviceIntent = serviceInfoList.get(position)
  117. .getIntent();
  118. new AlertDialog.Builder(BrowseRunningServiceActivity.this).setTitle(
  119. "是否停止服务").setMessage(
  120. "服务只有在重新启动后,才可以继续运行。但这可能会给电子市场应用程序带来意想不到的结果。")
  121. .setPositiveButton("停止", new DialogInterface.OnClickListener() {
  122. @Override
  123. public void onClick(DialogInterface dialog, int which) {
  124. // TODO Auto-generated method stub
  125. // 停止该Service
  126. //由于权限不够的问题,为了避免应用程序出现异常,捕获该SecurityException ,并弹出对话框
  127. try {
  128. stopService(stopserviceIntent);
  129. } catch (SecurityException sEx) {
  130. //发生异常 说明权限不够
  131. System.out.println(" deny the permission");
  132. new AlertDialog.Builder(BrowseRunningServiceActivity.this).setTitle(
  133. "权限不够").setMessage("对不起,您的权限不够,无法停止该Service").create().show();
  134. }
  135. // 刷新界面
  136. // 获得正在运行的Service信息
  137. getRunningServiceInfo();
  138. // 对集合排序
  139. Collections.sort(serviceInfoList, new comparatorServiceLable());
  140. // 为ListView构建适配器对象
  141. BrowseRunningServiceAdapter mServiceInfoAdapter = new BrowseRunningServiceAdapter(
  142. BrowseRunningServiceActivity.this,
  143. serviceInfoList);
  144. listviewService.setAdapter(mServiceInfoAdapter);
  145. tvTotalServiceNo.setText("当前正在运行的服务共有:"
  146. + serviceInfoList.size());
  147. }
  148. }).setNegativeButton("取消",
  149. new DialogInterface.OnClickListener() {
  150. @Override
  151. public void onClick(DialogInterface dialog,
  152. int which) {
  153. // TODO Auto-generated method stub
  154. dialog.dismiss(); // 取消对话框
  155. }
  156. }).create().show();
  157. }
  158. // 自定义排序 根据AppLabel排序
  159. private class comparatorServiceLable implements Comparator<RunSericeModel> {
  160. @Override
  161. public int compare(RunSericeModel object1, RunSericeModel object2) {
  162. // TODO Auto-generated method stub
  163. return object1.getAppLabel().compareTo(object2.getAppLabel());
  164. }
  165. }
  166. }

     代码下载地址:http://download.csdn.net/detail/qinjuning/3846097

     

         终于完成了这几块功能的介绍,这些功能的具体使用都挺类似的,最重要的是看你有没有耐心去把他们做出来。

作为一个小小程序员,我还是一步一步来做吧。。