Android Get background run services get Running service

Source: Internet
Author: User

The full code can be seen on my GitHub, linked at the end of the article. :




Main:

Package Com.zms.getrunningservice;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.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 Main extends Activity implements Onitemclicklistener {   private static String TAG = "Runningservice";    Private Activitymanager Mactivitymanager = null;    The ProcessInfo model class is used to hold all process information private list<servicemodel> servicemodellist = null;    Private ListView servicelist;    Private TextView Tvtotalserviceno;        public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (r.layout.service_list);        Servicelist = (ListView) Findviewbyid (R.id.listviewservice);        Servicelist.setonitemclicklistener (this);        Tvtotalserviceno = (TextView) Findviewbyid (R.id.tvtotalserviceno);        The Object Mactivitymanager = (Activitymanager) getsystemservice (Context.activity_service) to obtain the Activitymanager service;        Get the running Service Information getrunningserviceinfo ();        Sort the set Collections.sort (Servicemodellist, New Comparatorservicelabel ()); Build adapter object for ListView servicelistadapter Mserviceinfoadapter = new Servicelistadapter (Main.this, serviCemodellist);        Servicelist.setadapter (Mserviceinfoadapter); Tvtotalserviceno.settext (servicemodellist.size () + "a service is running, click Stop."    ");        }//Get system running process information private void Getrunningserviceinfo () {//Set a default service number size int defaultnum = 200; Get all the running processes in the system by calling Activitymanager's Getrunningappservicees () method LIST&LT;ACTIVITYMANAGER.RUNNINGSERVICEINFO&G T        Runservicelist = Mactivitymanager. Getrunningservices (Defaultnum);        The SERVICEINFO model class is used to hold all process information servicemodellist = new arraylist<servicemodel> (); for (Activitymanager.runningserviceinfo runserviceinfo:runservicelist) {//Get information about the process where the service is located int PID = Runserviceinfo.pid; The process ID number of the service where int uid = RUNSERVICEINFO.UID; User ID is similar to Linux permissions, ID is different, such as root//process name, default is the package name or by the property android:process specified String processName = Runser            viceinfo.process; Time value when the service was started long activesince = RunserviCeinfo.activesince;            If the service is connected via the Bind method, the Clientcount represents the number of service connection clients int clientcount = Runserviceinfo.clientcount;            The component information for the service may be pkgname/servicename componentname servicecmp = Runserviceinfo.service; String serviceName = Servicecmp.getshortclassname (); The class name of the service is String pkgname = Servicecmp.getpackagename ();                    Package name//print Log log.i (TAG, "Process ID:" + pid + "process name:" + processName + "process uid:")                    + uid + "\ n" + "service start time Value:" + activesince + "Client binding number:" + clientcount + "\ n" + "component information for this service:"            + ServiceName + "and" + pkgname); Here we use the Service component information, using Packagemanager to get the package name of the application where the service is located, icon, etc. packagemanager Mpackagemanager = this.getpackage Manager ();            Gets the Packagermanager object;           try {//Get the Pkgname information applicationinfo appInfo = Mpackagemanager.getapplicationinfo (             Pkgname, 0);                ServiceModel ServiceModel = new ServiceModel ();                Servicemodel.setappicon (Appinfo.loadicon (Mpackagemanager));                Servicemodel.setapplabel (Appinfo.loadlabel (Mpackagemanager) + "");                Servicemodel.setservicename (ServiceName);                Servicemodel.setpkgname (Pkgname);                Sets the component information for the service Intent Intent = new Intent ();                Intent.setcomponent (SERVICECMP);                Servicemodel.setintent (Intent);                Servicemodel.setpid (PID);                Servicemodel.setprocessname (ProcessName);            Added to the collection Servicemodellist.add (ServiceModel);            } catch (Namenotfoundexception e) {//TODO auto-generated catch block E.printstacktrace (); }}}//Touch to stop @Override public void Onitemclick (adapterview<?> arg0, View arg1, int p Osition, Long Arg3) {//TODO auto-generated method stub final Intent stopserviceintent = servicemodellist.get (position)        . Getintent (); New Alertdialog.builder (Main.this). Settitle ("Stop Service"). Setmessage ("The service can continue to run only after a restart. But this could bring unexpected results to electronic market applications.                    "). Setpositivebutton (" Stop ", new Dialoginterface.onclicklistener () {@Override public void OnClick (Dialoginterface dialog, int which) {//TODO auto-generated method Stu                        b//Stop the service//due to insufficient permissions, in order to avoid an application exception, capture the SecurityException and pop up the dialog box                        try {stopservice (stopserviceintent);  } catch (SecurityException sEx) {//Exception description permission not enough System.out.println ("                            Deny the permission ");                  New Alertdialog.builder (Main.this). Settitle (                  "Insufficient Permissions"). Setmessage ("Sorry, you don't have enough permissions to stop the service"). Create (). Show (); }//Refresh interface//Get running service information GETR                        Unningserviceinfo ();                        Sort the set Collections.sort (Servicemodellist, New Comparatorservicelabel ());                                Build the adapter object for the listview servicelistadapter servicelistadapter = new Servicelistadapter (                        Main.this, servicemodellist);                        Servicelist.setadapter (Servicelistadapter);                    Tvtotalserviceno.settext ("Currently running services in total:" + servicemodellist.size ()); }}). Setnegativebutton ("Cancel", new Dialoginterface.onclicklistener () {@Ove                          Rride public void OnClick (Dialoginterface dialog,              int which) {//TODO auto-generated method stub Dialog.dismiss ();    Cancel dialog box}). Create (). Show (); }//Custom sort Sort by Applabel private class Comparatorservicelabel implements Comparator<servicemodel> {@Ove Rride public int Compare (ServiceModel object1, ServiceModel object2) {//TODO auto-generated method Stu        b return Object1.getapplabel (). CompareTo (Object2.getapplabel ()); }    }}

Reprint Please specify source: Zhou Mushi's csdn blog Http://blog.csdn.net/zhoumushui

My github: Zhou Mushi's GitHub Https://github.com/zhoumushui


Android Get background run services get Running service

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.