Ways to get running programs and system services on Android _android

Source: Internet
Author: User

Activitymanager.runningappprocessinfo class vs. getting running applications
each application runs in its own process, but in order to conserve resources or the applications are designed to accomplish a common task, they
May also run in a process.

Knowledge Point Introduction:
Activitymanager.runningappprocessinfo class
Description: Encapsulates the process information that is running
Commonly-asked Fields:
int PID Process ID
The user ID in which the int UID process is located
String processname The process name, either by default to the package name or by the android:process= "" property.
String [] pkglist all application package names running under the process

Demo Description:
After we use Activitymanager to get all of the running process information, that is, to get the application package name (Pkgname) that is running in each process, call the method provided by the Packagemanager class directly through the package names (Pkgname). You can get information about these applications.
Some resource files will not be posted, directly posted the main engineering logic. Notice here we get all the application information at once, then filter the applications to get the objects we need. Readers can iterate through all package names (Pkgname) using the method provided by the Packagemanager class, but this is less efficient.
Screenshot below:
After clicking on a process

To view the application information running by a process, all running process information:

The

shows the project code for the running application is as follows:

 
Package COM.QIN.AMMP; 
Import java.util.ArrayList; 
Import java.util.Collections; 
Import Java.util.HashMap; 
Import java.util.List; 
 
Import Java.util.Map; 
Import android.app.Activity; 
Import Android.app.ActivityManager; 
Import Android.content.Context; 
Import android.content.Intent; 
Import Android.content.pm.ApplicationInfo; 
Import Android.content.pm.PackageInfo; 
Import Android.content.pm.PackageManager; 
Import android.content.pm.PackageManager.NameNotFoundException; 
Import Android.os.Bundle; 
Import Android.util.Log; 
Import Android.view.View; 
Import Android.widget.AdapterView; 
Import Android.widget.ListView; 
Import Android.widget.TextView; 
 
Import Android.widget.AdapterView.OnItemClickListener; 
 
  public class Browserunningappactivity extends activity {private static String TAG = "browserunningappactivity"; 
 
  Private ListView ListView = null; 
  Private list<runningappinfo> mlistappinfo = null; 
   
  Private TextView tvinfo = null; Private PacKagemanager pm; 
    @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 
 
    Setcontentview (r.layout.browse_app_list); 
    ListView = (ListView) Findviewbyid (R.id.listviewapp); 
     
    Tvinfo = (TextView) Findviewbyid (r.id.tvinfo); 
 
    Mlistappinfo = new arraylist<runningappinfo> (); 
    Query all applications for a particular process Intent Intent = getintent (); 
     
    Whether to query a particular PID application int pid = Intent.getintextra ("extra_process_id",-1); 
    if (PID!=-1) {//Mlistappinfo =queryspecailpidrunningappinfo (Intent, PID) for all running applications in a particular regular; 
      else{//Query all running application information: including their process ID and process name Tvinfo.settext ("All running applications have-------");  
    Mlistappinfo = Queryallrunningappinfo (); 
    } browserunningappadapter Browseappadapter = new Browserunningappadapter (this, mlistappinfo); 
  Listview.setadapter (Browseappadapter); //Query All running application information: including their process ID and process name//Here I have directly obtained all the applications installed in the system, then according to the application PKGname filter gets all real run applications private list<runningappinfo> Queryallrunningappinfo () {pm = This.getpackagemanager (); Query for all installed applications list<applicationinfo> listappcations = Pm.getinstalledapplications (Packagemanager.get_uni 
    Nstalled_packages); 
    Collections.sort (Listappcations,new Applicationinfo.displaynamecomparator (PM));//Sort//Save all running package names and the process information it is in map<string, activitymanager.runningappprocessinfo> pgkprocessappmap = new hashmap<string, 
 
    Activitymanager.runningappprocessinfo> (); 
    Activitymanager Mactivitymanager = (activitymanager) getsystemservice (Context.activity_service); Get all running processes in the system by calling the Activitymanager getrunningappprocesses () method List<activitymanager.runningappprocessinfo 
 
    > appprocesslist = Mactivitymanager. getrunningappprocesses (); for (Activitymanager.runningappprocessinfo appprocess:appprocesslist) {int pid = appprocess.pid;//PID S Tring ProcessName = appprocess.processname; 
 
      Process name LOG.I (TAG, "processname:" + processname + "pid:" + pid); string[] Pkgnamelist = appprocess.pkglist; Get the package name for all applications running in the process//output for (int i = 0; i < pkgnamelist.length i++) {String pkgn 
        ame = Pkgnamelist[i]; 
        LOG.I (TAG, "PackageName" + Pkgname + "at index" + i+ "in process" + pid); 
      Add to the Map object Pgkprocessappmap.put (Pkgname, appprocess); }//Save all running application information list<runningappinfo> Runningappinfos = new arraylist<runningappinfo> (); Save the filtered appinfo for (ApplicationInfo app:listappcations) {//If the package name exists, construct a Runningappinfo object if (p Gkprocessappmap.containskey (App.packagename)) {//Get the PackageName pid and processname int pid = pgkproces 
        Sappmap.get (app.packagename). PID; 
        String processname = Pgkprocessappmap.get (app.packagename). ProcessName; 
      Runningappinfos.add (Getappinfo (app, PID, ProcessName)); } 
    return Runningappinfos; 
 
 
    ////a specific regular application of all running applications private list<runningappinfo> queryspecailpidrunningappinfo (Intent Intent, int pid) { 
    string[] Pkgnamelist = Intent.getstringarrayextra ("Extra_pkgnamelist"); 
     
    String processname = Intent.getstringextra ("Extra_process_name"); 
         
    Update UI Tvinfo.settext (the process ID is "+PID +" running applications are common: "+pkgnamelist.length"); 
   
    PM = This.getpackagemanager (); Save all running application information list<runningappinfo> Runningappinfos = new arraylist<runningappinfo> (); Save filtered appinfo for (int i = 0; I<pkgnamelist.length i++) {//query specific ApplicationInfo object based on package name Applica 
     Tioninfo AppInfo; 
      try {appInfo = Pm.getapplicationinfo (Pkgnamelist[i], 0); 
     Runningappinfos.add (Getappinfo (AppInfo, PID, processname)); 
     catch (Namenotfoundexception e) {//TODO auto-generated catch block E.printstacktrace (); 
    }//0 The representative does not have any markings; 
}    return Runningappinfos; }//Constructs a Runningappinfo object and assigns private Runningappinfo Getappinfo (applicationinfo app, int pid, String proces 
    sname) {Runningappinfo appInfo = new Runningappinfo (); 
    Appinfo.setapplabel ((String) App.loadlabel (PM)); 
    Appinfo.setappicon (App.loadicon (PM)); 
 
    Appinfo.setpkgname (App.packagename); 
    Appinfo.setpid (PID); 
 
    Appinfo.setprocessname (ProcessName); 
  return appInfo; 
 } 
}

Activitymanager.runningserviceinfo class Gets the service that is running
Activitymanager.runningserviceinfo class: Encapsulates the running service information

Getting all the services that are actually running in the system is achieved by invoking the Activitymanager method, as follows:

list<activitymanager.runningserviceinfo> getrunningservices (int maxnum)
Function: Return all running services
Parameter: Maxnum represents the number of services we want to return, generally to a slightly larger value, for example, 50.

Activitymanager.runningserviceinfo class
Commonly-asked Fields:

The time when the long Activesince service was first activated, including how to start and bind
int Clientcount If the service is connected by means of a bind method, Clientcount represents the number of service connection clients
int Crashcount The number of crashes occurred during the service run
If Boolean foreground is true, the service executes in the background
int PID If not 0, indicates the process ID number of the service (PS: 0) I do not know--for guidance)
The int UID User ID is similar to the user rights of Linux, such as root
String process Name, default is package name or specified by attribute android:process
ComponentName Service Gets the service's component information containing pkgname/servicename information

Packagemanger class
Description: Encapsulates the operation of application information
The method for obtaining application information is as follows:
Public Abstractapplicationinfo Getapplicationinfo (String packagename, int flags)
Parameters: PackageName Package Name
Flags The ApplicationInfo is this flag mark, which can usually be directly given to the constant 0
Function: Returns the ApplicationInfo object
Demo Description:
We have obtained the service information which is running in the system, including the package name, the icon, the service class name and so on. In order to achieve the settings under the application module is running the service effect, we click on a service, theoretically can stop the service, but due to insufficient permissions permissions, may report SecurityException exception, resulting in an exception to the application.

There are two types of issues about insufficient permissions:
1. In the Androidmanifest.xml file, when you specify the Android:permission property for the <activity/> or <service/> node, when you operate in another process, You need to declare the permission permission.
2, the system authority, this we have nothing to say.
Screenshot below:

The main engineering 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.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 implements Onitemclicklistener {private static String TAG = "Runservice 
 
  Info "; 
  Private Activitymanager Mactivitymanager = null; 
 
  The ProcessInfo model class is used to hold 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); 
 
    The object that obtains the Activitymanager service Mactivitymanager = (Activitymanager) getsystemservice (Context.activity_service); 
    Get the running Service Information getrunningserviceinfo (); 
 
    Sort the set Collections.sort (Serviceinfolist, New comparatorservicelable ()); System.out.println (ServiceinfOlist.size () + "-------------"); Building adapter objects for ListView browserunningserviceadapter Mserviceinfoadapter = new Browserunningserviceadapter (brow 
 
    Serunningserviceactivity.this, serviceinfolist); 
 
    Listviewservice.setadapter (Mserviceinfoadapter); 
  Tvtotalserviceno.settext ("Currently running services are common:" + serviceinfolist.size ()); 
    //Get the process information that the system is running private void Getrunningserviceinfo () {//Set the quantity size of a default service int defaultnum = 20; Get all running processes list<activitymanager.runningserviceinfo> RU in the system by calling the Activitymanager Getrunningappservicees () method 
 
    Nservicelist = Mactivitymanager. Getrunningservices (Defaultnum); 
 
    System.out.println (Runservicelist.size ()); 
 
    The SERVICEINFO model class is used to hold all process information serviceinfolist = new arraylist<runsericemodel> (); for (Activitymanager.runningserviceinfo runserviceinfo:runservicelist) {//Get information about the process where the service is located int pid = Runserviceinfo.pid; Process ID number int UID = run for serviceServiceinfo.uid; User IDs are similar to Linux permissions, IDs are different, such as root//process name, by default the package name or by the attribute android:process specified String processname = Runserviceinfo  
 
      . process; 
 
      The time value at startup of the service is long activesince = runserviceinfo.activesince; 
 
      If the service is connected by means of a bind method, Clientcount represents the number of service connection clients int clientcount = Runserviceinfo.clientcount; 
      The component information obtained for the service may be pkgname/servicename componentname servicecmp = Runserviceinfo.service; String serviceName = Servicecmp.getshortclassname (); Service's class name String Pkgname = Servicecmp.getpackagename ();  Package name//print Log log.i (TAG, "Process ID: + PID +" process name: "+ processname +" "Process uid:" + uid + "\ \") + "Service startup time value: + activesince +" Client binding number: "+ clientcount +" \ n "+" component information for this service: "+ Servicena 
 
      Me + "and" + pkgname); Here we use the Service component information, using Packagemanager to obtain the service's application package name, icon, etc. packagemanager Mpackagemanager = This.getpackagemana GER (); BeenTake Packagermanager object; try {//Get the Pkgname information applicationinfo appInfo = Mpackagemanager.getapplicationinfo (Pkgnam 
 
        E, 0); 
        Runsericemodel runservice = new Runsericemodel (); 
        Runservice.setappicon (Appinfo.loadicon (Mpackagemanager)); 
        Runservice.setapplabel (Appinfo.loadlabel (Mpackagemanager) + ""); 
        Runservice.setservicename (ServiceName); 
        Runservice.setpkgname (Pkgname); 
        Set the component information for the service Intent Intent = new Intent (); 
        Intent.setcomponent (SERVICECMP); 
 
        Runservice.setintent (Intent); 
        Runservice.setpid (PID); 
 
        Runservice.setprocessname (ProcessName); 
 
      Add to the collection Serviceinfolist.add (Runservice); catch (Namenotfoundexception e) {//TODO auto-generated catch block System.out.println ("------------- 
        --------error-------------"); 
      E.printstacktrace (); "}}//Touch can stop @Override public voID Onitemclick (adapterview<?> arg0, View arg1, int position, long Arg3) {//TODO auto-generated method 
 
    Stub final Intent stopserviceintent = serviceinfolist.get (position). Getintent (); New Alertdialog.builder (Browserunningserviceactivity.this). Settitle ("Stop Service"). Setmessage ("Service only after reboot, can continue to run. But this may bring unexpected results to electronic market applications.  "). Setpositivebutton (" Stop ", new Dialoginterface.onclicklistener () {@Override public void 
            OnClick (dialoginterface dialog, int which) {//TODO auto-generated Method Stub//Stop the service Because of insufficient permissions, to avoid an application exception, capture the SecurityException and pop up the dialog to try {stopservice (Stopservic 
            Eintent);  
              The catch (SecurityException sEx) {//Exception description permission is not sufficient System.out.println ("deny the permission"); New Alertdialog.builder (Browserunningserviceactivity.this). Settitle ("Insufficient Permissions"). SetMessage ("Sorry, you don't have enough permissions to stop the service"). Create (). Show (); 
            //Refresh the interface//get the running Service Information getrunningserviceinfo (); 
            Sort the set Collections.sort (Serviceinfolist, New comparatorservicelable ()); 
                Building adapter objects for ListView browserunningserviceadapter Mserviceinfoadapter = new Browserunningserviceadapter ( 
            Browserunningserviceactivity.this, serviceinfolist); 
            Listviewservice.setadapter (Mserviceinfoadapter); 
          Tvtotalserviceno.settext ("Currently running services are common:" + serviceinfolist.size ()); 
              }). Setnegativebutton ("Cancel", new Dialoginterface.onclicklistener () {@Override public void OnClick (Dialoginterface dialog, int which) {//TODO Auto-gen erated method Stub Dialog.dismiss (); Cancel dialog box}}. Create (). Show (); 
 
    ///Custom sort Applabel Sort Private class Comparatorservicelable implements Comparator<runsericemodel> { @Override public int Compare (Runsericemodel object1, Runsericemodel object2) {//TODO auto-generated method s 
    Tub return Object1.getapplabel (). CompareTo (Object2.getapplabel ()); 
 } 
 
  } 
 
}

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.