Android Cleanup device Memory specific complete demo sample (i)

Source: Internet
Author: User

Mainactivity such as the following:
Package Come.on;import Android.app.activity;import Android.content.context;import android.content.intent;import Android.os.bundle;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.Button; Import android.widget.edittext;/** * Demo Description: * Memory cleanup and Memory tool class * Detailed code see Tool class Memoryutils * */public class Mainactivity extends    Activity {private Button mbutton;private Context mcontext;private EditText medittext;        @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.main);    Init ();    } private void Init () {mcontext=this;    Intent intent=new Intent ("Come.on.service");        The service is useless and can be removed startservice (intent);    medittext= (EditText) Findviewbyid (R.id.edittext);    mbutton= (Button) Findviewbyid (R.id.button); Mbutton.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {memoryutils.cleanmemory (MC    Ontext,medittext);}); }   }

Memoryutils such as the following:
Package Come.on;import Java.util.list;import Java.io.filereader;import android.os.process;import Java.io.ioexception;import Java.io.bufferedreader;import Android.widget.edittext;import Android.content.Context; Import Java.io.inputstreamreader;import Android.app.activitymanager;import Android.content.componentname;import Android.app.activitymanager.memoryinfo;import Android.app.activitymanager.runningtaskinfo;import android.app.activitymanager.runningappprocessinfo;/** * Description of the document: * Memory Tool class * contains content: * 1 memory cleanup is a few ways to kill a process * 2 get the total memory size and its available size * 3 inferred stack top activity name and its owning process name * * Note permissions: * <uses-permission android:name= "Android.permission.GET_TASKS"/> * <uses-perm  Ission android:name= "Android.permission.KILL_BACKGROUND_PROCESSES"/> * * Document Date: * May 30, 2014 10:01:55 * */public class memoryutils {//----------> Below are several ways to kill a process public static void Cleanmemory (Context context,edittext EditText) {long Beforecleanmemory=getavailmemory (context); SYSTEM.OUT.PRINTLN ("---> Pre-Clean available memory size:" +beforecleanmemory+ "M"); Activitymanager Activitymanager = (activitymanager) context.getsystemservice (Context.activity_service); Runningappprocessinfo runningappprocessinfo = null; list<runningappprocessinfo> runningappprocessinfolist = activitymanager.getrunningappprocesses (); for (int i = 0 ; I < runningappprocessinfolist.size (); ++i) {runningappprocessinfo = Runningappprocessinfolist.get (i); String ProcessName = runningappprocessinfo.processname;//calls the method that kills the process System.out.println ("---> Start cleanup:" +processname); Killprocessbyrestartpackage (context, processName);} Long aftercleanmemory=getavailmemory (context); SYSTEM.OUT.PRINTLN ("---> Available memory size after clean up:" +aftercleanmemory+ "M"); SYSTEM.OUT.PRINTLN ("---> Save memory Size:" + (aftercleanmemory-beforecleanmemory) + "M") edittext.settext ("Total cleanup:" + ( aftercleanmemory-beforecleanmemory) + "M");} Use the Activitymanager.restartpackage () method to kill the process//the method actually calls the Activitymanager.killbackgroundprocesses () method public static void Killprocessbyrestartpackage (Context context,string packagename) {Activitymanager ActiviTymanager = (Activitymanager) context.getsystemservice (Context.activity_service); Activitymanager.restartpackage ( PackageName); System.GC ();} Using Process.killprocess (PID) to kill the process//NOTE://1 this way can commit suicide, that is, kill the process//2 this way can kill other ordinary application process//3 the way not to kill the system-level application is System/app application public static void killprocessbykillprocess (int pid) {process.killprocess (PID);} Use adb shell command to kill process public static void Killprocessbyadbshell (int pid) {String cmd = "adb shell kill-9" + pid; System.out.println ("-------> cmd=" + cmd); try {java.lang.Process Process = Runtime.getruntime (). exec (cmd); I Nputstreamreader InputStreamReader = new InputStreamReader (Process.getinputstream ()); BufferedReader BufferedReader = new BufferedReader (InputStreamReader); String line = null;while (line = Bufferedreader.readline ())! = null) {System.out.println ("----> Exec Shell:" + line);} Bufferedreader.close ();}  catch (IOException e) {e.printstacktrace ();}} Use the SU process's command to kill the process//1 get the SU process (super process)//Runtime.getruntime (). EXEC ("su"); 2 using the SU process to run commands//Process.getoutputStream (). Write (Cmd.getbytes ());p ublic static void killprocessbysu (int pid) {try {java.lang.Process Process = Runtime.getruntime (). EXEC ("su"); String cmd = "kill-9" + pid; System.out.println ("-------> cmd =" + cmd);p rocess.getoutputstream (). Write (Cmd.getbytes ()); if (Process.waitfor ( ) = 0) {System.out.println ("-------> su.waitfor ()! = 0");} else {System.out.println ("-------> Su.waitfor () ==0") ;}} catch (Exception e) {e.printstacktrace ();}} ----------> above for several ways to kill the process//get current process name public static String Getcurrentprocessname (context context) {int PID = Android.os.Process.myPid (); Activitymanager Activitymanager = (activitymanager) context.getsystemservice (Context.activity_service); for ( Runningappprocessinfo runningAppProcessInfo:activityManager.getRunningAppProcesses ()) {if ( Runningappprocessinfo.pid = = pid) {String Processname=runningappprocessinfo.processname;return processName ;}} return null;} Get stack top activity name public static String Gettopactivityname (Context context) {String topactivityname = null; Activitymanager Activitymanager = (Activitymanager) (Context.getsystemservice (android.content.Context.ACTIVITY_ SERVICE)); list<runningtaskinfo> Runningtaskinfos = activitymanager.getrunningtasks (1); if (Runningtaskinfos! = null) { ComponentName f = runningtaskinfos.get (0). topactivity; String topactivityclassname = F.getclassname (); String temp[] = topactivityclassname.split ("\ \"); Topactivityname = Temp[temp.length-1];} return topactivityname;} Gets the name of the process that the stack top activity belongs to, public static string Gettopactivityprocessname (context context) {string processName = null; Activitymanager Activitymanager = (Activitymanager) (Context.getsystemservice (android.content.Context.ACTIVITY_ SERVICE)); list<runningtaskinfo> Runningtaskinfos = activitymanager.getrunningtasks (1); if (Runningtaskinfos! = null) { ComponentName componentname = runningtaskinfos.get (0). topactivity; String topactivityclassname = Componentname.getclassname (); int index = Topactivityclassname.lastindexof ("."); ProcessName = topactivityclassname.substring (0, index);} return processName;} Gets the total memory size public static long Gettotalmemory () {//System memory information file string FilePath = "/proc/meminfo"; String lineString; string[] Stringarray;long totalmemory = 0;try {FileReader FileReader = new FileReader (FilePath); BufferedReader BufferedReader = new BufferedReader (filereader,1024 * 8);//Read Meminfo first line, get total system memory size linestring = Bufferedreader.readline ();//Split Stringarray = Linestring.split ("\\s+") according to space;//Get Total system memory, Unit Kbtotalmemory = Integer.valueof (Stringarray[1]). Intvalue (); Bufferedreader.close (); catch (IOException e) {}return totalmemory/1024;} Get available memory size public static long getavailmemory (context context) {Activitymanager activitymanager= (Activitymanager) Context.getsystemservice (Context.activity_service); Memoryinfo memoryinfo = new Memoryinfo () Activitymanager.getmemoryinfo (memoryinfo); return memoryinfo.availmem/(1024 * 1024);}}

Servicesubclass such as the following:
Package Come.on;import Android.app.service;import Android.content.intent;import Android.os.ibinder;public class Servicesubclass extends Service {@Overridepublic ibinder onbind (Intent Intent) {return null;} @Overridepublic void OnCreate () {super.oncreate (); SYSTEM.OUT.PRINTLN ("---> Service onCreate ()");} @Overridepublic void OnStart (Intent Intent, int startid) {Super.onstart (Intent, Startid); SYSTEM.OUT.PRINTLN ("---> Service onStart ()");}}

Main.xml such as the following:
<?xml version= "1.0" encoding= "Utf-8"? ><relativelayout xmlns:android= "http://schemas.android.com/apk/res/ Android "Android:layout_width=" Fill_parent "android:layout_height=" fill_parent "> <textview androi D:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:text= "Test memory Cleanup" Android:lay Out_centerhorizontal= "true" android:layout_margintop= "25dip" android:textsize= "20sp"/> <ed        Ittext android:id= "@+id/edittext" android:layout_width= "160dip" android:layout_height= "50dip" Android:layout_centerhorizontal= "true" android:layout_margintop= "100dip" android:gravity= "center" an Droid:textsize= "20sp"/> <button android:id= "@+id/button" android:layout_width= "Wrap_co          Ntent "android:layout_height=" wrap_content "android:text=" Clean Memory "android:layout_centerinparent=" true " Android:textsize= "20SP"       /> </RelativeLayout> 

Androidmanifest.xml such as the following:
<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http://schemas.android.com/apk/res/ Android "package=" Come.on "android:versioncode=" 1 "android:versionname=" 1.0 "> <uses-sdk android:minsdkv    ersion= "/> <uses-permission android:name=" Android.permission.RECEIVE_BOOT_COMPLETED "/> <uses-permission android:name= "Android.permission.ACCESS_CHECKIN_PROPERTIES"/> <uses-permission android: Name= "Android.permission.RECORD_AUDIO"/> <uses-permission android:name= "Android.permission.INTERNET"/> & Lt;uses-permission android:name= "Android.permission.ACCESS_NETWORK_STATE"/> <uses-permission android:name= " Android.permission.ACCESS_WIFI_STATE "/> <uses-permission android:name=" android.permission.CHANGE_NETWORK_ State "/> <uses-permission android:name=" Android.permission.READ_PHONE_STATE "/> <uses-permission androi D:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/>    <uses-permission android:name= "Android.permission.KILL_BACKGROUND_PROCESSES"/> <uses-permission android: Name= "Android.permission.GET_TASKS"/> <application android:icon= "@drawable/A" Android : label= "@string/app_name" > <activity android:label= "@string/app_name" android:name= ". M Ainactivity "> <intent-filter > <action android:name=" Android.intent.action.MAIN "/&                Gt <category android:name= "Android.intent.category.LAUNCHER"/> </intent-filter> </activity&        Gt <service android:name= ".            Servicesubclass "> <intent-filter> <action android:name=" Come.on.service "/> </intent-filter> </service> </application></manifest>


Android Cleanup device Memory specific complete demo sample (i)

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.