Get the running service in Android --- use of activitymanager. runningserviceinfo

Source: Internet
Author: User

 

Reprinted please indicate the source:Http://blog.csdn.net/qinjuning

 

For the use of packagemanager and activitymanager, I have also written some demos. Basically, the lines I have written refer to

If you are really interested in the application, we suggest you look at the source code, but I have not read the source code in this regard, just in

Only when necessary can I roll over the system.

Today, I wrote this blog post with my patience at the last point. I have basically completed the introduction of the entire functional module of the application, and we will gradually expand on this series.

 

Activitymanager. runningserviceinfo class: encapsulates the Running Service Information

 

You can call the activitymanager method to obtain all truly running services in the system. The specific method is as follows:

 

List <activitymanager. runningserviceinfo>Getrunningservices(Int
Maxnum)

Function: returns all running services.

Parameter: maxnum indicates the number of services we want to return. Generally, a slightly larger value is provided, for example, 50. 

Activitymanager. runningserviceinfo class

Common fields:

 

Long time when the activesince service is activated for the first time, including the start and binding methods

Int clientcount if the service is connected using the bind method, clientcount indicates the number of clients connected by the Service.

Number of times the int crashcount service crashes during running

Boolean Foreground: if it is true, the service is executed in the background.

If the int PID is not 0, it indicates the ID of the process where the service is located (if PS: 0, I am not sure--For instructions)

The Int uid user ID is similar to Linux User Permissions, such as root.

String process name. The default value is the package name or is specified by the Android: process attribute.

ComponentnameServiceThe component information of the service contains pkgname.
/Servicename Information

 

Packagemanger class

Note: operations on application information are encapsulated.

The method for obtaining application information is as follows:

Public abstractapplicationinfoGetapplicationinfo(String
Packagename, int flags)

Parameter: packagename package name

Flags the applicationinfo is the flags mark, which can usually be directly assigned a constant0You can.

Function: returns the applicationinfo object.

 

For more information about packagemanger, see<Obtain Application (Package) Information in Android ----- use of packagemanager (1)>

 

Use of task,I will not go into details here. You can take a closer look at the SDK and recommend a blog here to help you understand it.

Process, task, and service information of the android System

 

 

Demo description:

 

We obtained the running service information in the system, including the package name, icon, and service class name. To enable

The service is running. After clicking a service, the service can be stopped theoretically. However, due to insufficient permission permissions, a message may be reported.

SecurityexceptionException.

 

Insufficient permissions can be divided into two types:

1. In the androidmanifest. xml file, specifyAndroid:PermissionWhen operating in other processes,

The permission must be declared. For details, refer to the following article:

Android custom permission

 

2,System PermissionsThere's nothing to say. Refer to the following article.

Android. uid. system get system Permissions

 

As follows:(Please forgive me for adding a watermark)

 

 

 

Old Rules: resource files are not pasted. The main project logic is as follows:

 

 

Package COM. qin. runservice; import Java. util. arraylist; import Java. util. collections; import Java. util. comparator; import Java. util. list; import android. app. activity; import android. app. activitymanager; import android. app. alertdialog; import android. app. dialog; import android. content. componentname; import android. content. context; import android. content. dialoginterface; import android. content. intent; import android Oid. content. PM. applicationinfo; import android. content. PM. packagemanager; import android. content. PM. packagemanager. namenotfoundexception; import android. OS. bundle; import android. OS. debug; import android. util. log; import android. view. contextmenu; import android. view. menu; import android. view. menuitem; import android. view. view; import android. view. contextmenu. contextmenuinfo; import android. widget. adapterview; Import android. widget. listview; import android. widget. textview; import android. widget. adapterview. onitemclicklistener; public class browserunningserviceactivity extends activity implementsonitemclicklistener {Private Static string tag = "runserviceinfo"; private activitymanager mactivitymanager = NULL; // The processinfo model class is used to save all process information. Private list <runsericemodel> serviceinfolist = NULL; private listview Listviewservice; private textview tvtotalserviceno; Public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. browse_service_list); listviewservice = (listview) findviewbyid (R. id. listviewservice); listviewservice. setonitemclicklistener (this); tvtotalserviceno = (textview) findviewbyid (R. id. tvtotalserviceno); // gets the activitymanager service object mactivitymanager = (Activitymanager) getsystemservice (context. activity_service); // get the running service information getrunningserviceinfo (); // sort the collections. sort (serviceinfolist, new comparatorservicelable (); system. out. println (serviceinfolist. size () + "-------------"); // create an adapter object browserunningserviceadapter mserviceinfoadapter = new browserunningserviceadapter (browserunningserviceactivity. this, serviceinfolist); listviewser Vice. setadapter (mserviceinfoadapter); tvtotalserviceno. settext ("currently running services:" + serviceinfolist. size ();} // obtain the information about the running processes of the system. Private void getrunningserviceinfo () {// set the default service quantity. Int defanum num = 20; // call the getrunningappservicees () method of activitymanager to obtain the list of all running processes in the System <activitymanager. runningserviceinfo> runservicelist = mactivitymanager. getrunningservices (defaultnum); system. out. println (runservicelis T. size (); // serviceinfo model class used to save all process information serviceinfolist = new arraylist <runsericemodel> (); For (activitymanager. runningserviceinfo runserviceinfo: runservicelist) {// obtain the information of the process where the service is located. Int pid = runserviceinfo. PID; // ID of the process where the service is located: int uid = runserviceinfo. UID; // the user ID is similar to the Linux permission, and the ID is also different, such as root. // process name. The default value is package name or string processname = runserviceinfo specified by the attribute Android: process. process; // The time when the service is started lo Ng activesince = runserviceinfo. activesince; // if the service is connected using the bind method, clientcount indicates the number of clients that the service connects to. Int clientcount = runserviceinfo. clientcount; // The component information of the service may be pkgname/servicenamecomponentname servicecmp = runserviceinfo. service; string servicename = servicecmp. getaskclassname (); // service class name string pkgname = servicecmp. getpackagename (); // package name // print loglog. I (TAG, "process ID:" + PID + "process name: "+ Processname +" process uid: "+ uid +" \ n "+" service Start Time Value: "+ activesince +" number of client bindings: "+ clientcount +" \ n "+" component information of the Service: "+ servicename +" and "+ pkgname); // here we use the component information of the service, packagemanager is used to obtain the package name and icon of the application where the service is located. packagemanager mpackagemanager = This. getpackagemanager (); // obtain the packagermanager object; try {// obtain the information of this pkgname applicationinfo appinfo = mpackagemanager. getapplicationinfo (pkgname, 0 ); Runsericemodel runservice = new runsericemodel (); runservice. setappicon (appinfo. loadicon (mpackagemanager); runservice. setapplabel (appinfo. loadlabel (mpackagemanager) + ""); runservice. setservicename (servicename); runservice. setpkgname (pkgname); // sets the Service's component information intent = new intent (); intent. setcomponent (servicecmp); runservice. setintent (intent); runservice. setpid (PID); runservice. setprocessname (P Rocessname); // Add it to serviceinfolist in the set. add (runservice);} catch (namenotfoundexception e) {// todo auto-generated catch blocksystem. out. println ("--------------------- error -------------"); E. printstacktrace () ;}}// you can stop @ overridepublic void onitemclick (adapterview <?> Arg0, view arg1, int position, long arg3) {// todo auto-generated method stubfinal intent stopserviceintent = serviceinfolist. get (position ). getintent (); New alertdialog. builder (browserunningserviceactivity. this ). settitle ("Stop Service "). setmessage ("the service can continue to run only after it is restarted. However, this may bring unexpected results to e-market applications. "). Setpositivebutton ("stop", new dialoginterface. onclicklistener () {@ overridepublic void onclick (dialoginterface dialog, int which) {// todo auto-generated method stub // stop the service due to insufficient permissions, to avoid exceptions in the application, capture the securityexception and pop up the try {stopservice (stopserviceintent);} catch (securityexception sex) {// if an exception occurs, the system is not authorized enough. out. println ("deny the permission"); New alertdialog. builder (browserunningserviceactivity. this ). settitle ("insufficient Permissions "). setmessage ("sorry, you are not authorized enough to stop this service "). create (). show () ;}// refresh the interface // get the running service information getrunningserviceinfo (); // sort the collections. sort (serviceinfolist, new comparatorservicelable (); // create an adapter object browserunningserviceadapter mserviceinfoadapter = new browserunningserviceadapter (browserunningserviceactivity. this, serviceinfolist); listviewservice. setadapter (mserviceinfoadapter); tvtotalserviceno. settext ("currently running services:" + serviceinfolist. size ());}}). setnegativebutton ("cancel", new dialoginterface. onclicklistener () {@ overridepublic void onclick (dialoginterface dialog, int which) {// todo auto-generated method stubdialog. dismiss (); // cancel dialog box }}). create (). show () ;}// custom sorting private class comparatorservicelable implements comparator <runsericemodel >{@ overridepublic int compare (runsericemodel object1, runsericemodel object2) by applabel) {// todo auto-generated method stubreturn object1.getapplabel (). compareto (object2.getapplabel ());}}}

Code:Http://download.csdn.net/detail/qinjuning/3846097

Finally, we have completed the introduction of these functions. The specific usage of these functions is quite similar. The most important thing is to see if you have the patience to make them out.

As a small programmer, let me do it step by step ..

 

 

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.