Android-enabled Service to prevent system Recycle

Source: Internet
Author: User

MainActivity is as follows:

Package cc. c; import java. util. list; import android. OS. bundle; import android. OS. process; import android. view. view; import android. view. view. onClickListener; import android. widget. button; import android. app. activity; import android. app. activityManager; import android. app. activityManager. runningAppProcessInfo; import android. app. activityManager. runningTaskInfo; import android. content. componentName; import android. content. context;/*** Demo Description: * implements a Service to prevent the Service from being recycled by the system. * In some cases, the Service will be killed by the system. I have found many methods on the Internet. Although they all claim that * can be recycled by the system, it seems that they are not reliable enough. * Another method is provided here. The idea is: * use AlarmManager regular intervals (such as 5 S and 20 S) to continuously start service (). * (1) if the Service is recycled, onCreate () and onStart () * (2) of the Service will be called. if the Service is not recycled, only the onStart () * of the Service will be called to use this method to implement a curve to prevent the Service from being recycled by the system. ** test environment: * Android: 2.3.6 + ME525 + ** Test method: * 1 deploy the application to the device * 2 restart the device * 3 after the device restarts, click to enter the application. click Button ** 4 on the interface to view the Log ** Note: * 1 4.0 and above, please pay attention to the implementation of the boot broadcast listener * 2 pay attention to permissions *
 *
 ** Note: * 1 when killing a process, you sometimes need to determine whether the Activity to which the process belongs is displayed on the screen * For details about this method, see getTopActivityNameAndProcessName () * 2 if you have other methods, please leave a message. thank you. **/public class MainActivity extends Activity {private Button mButton; private long lastTime = 0; private Context mContext; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); init ();} private void init () {mContext = this; lastTime = System. currentTimeMillis (); mButton = (Button) findViewById (R. id. button); mButton. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View view) {if (System. currentTimeMillis ()-lastTime)> 2000) {lastTime = System. currentTimeMillis (); cleanMemory (mContext) ;}}) ;}// simulation service is recycled by the System private void cleanMemory (Context context) {RunningAppProcessInfo runningAppProcessInfo = null; activityManager activityManager = (ActivityManager) context. getSystemService (Context. ACTIVITY_SERVICE); List
 
  
RunningAppProcessInfoList = activityManager. getRunningAppProcesses (); if (runningAppProcessInfoList! = Null) {for (int I = 0; I <runningAppProcessInfoList. size (); ++ I) {runningAppProcessInfo = runningAppProcessInfoList. get (I); String processName = runningAppProcessInfo. processName; if (processName. startsWith ("cc. c ") {System. out. println ("------> kill this application"); int pid = runningAppProcessInfo. pid; Process. killProcess (pid) ;}}// obtain the Activity on the top of the stack and its Process public static String getTopActivityNameAndProcessName (Context context) {String processName = null; String topActivityName = null; activityManager activityManager = (ActivityManager) (context. getSystemService (android. content. context. ACTIVITY_SERVICE); List
  
   
RunningTaskInfos = activityManager. getRunningTasks (1); if (runningTaskInfos! = Null) {ComponentName f = runningTaskInfos. get (0 ). topActivity; String topActivityClassName = f. getClassName (); String temp [] = topActivityClassName. split ("\\. "); // name of the stack top Activity topActivityName = temp [temp. length-1]; int index = topActivityClassName. lastIndexOf (". "); // name of the process to which the stack top Activity belongs: processName = topActivityClassName. substring (0, index); System. out. println ("----> topActivityName =" + topActivityName + ", processName =" + processName);} return topActivityName + "," + processName ;}}
  
 

BootCompletedBroadcastReceiver:

Package cc. c; import android. app. alarmManager; import android. app. pendingIntent; import android. content. broadcastReceiver; import android. content. context; import android. content. intent; import android. OS. systemClock; // listen to the boot broadcast public class BootCompletedBroadcastReceiver extends BroadcastReceiver {@ Overridepublic void onReceive (Context context, Intent intent) {// receive the boot broadcast if (intent. getAction (). equals (Intent. ACTION_BOOT_COMPLETED) {sendCheckServiceBroadcast (context) ;}// send broadcast private void sendCheckServiceBroadcast (Context context) {Intent intent = new Intent (context, CheckServiceBroadcastReceiver. class); intent. setAction ("com.cn. checkServicebroadcasreceiver "); PendingIntent pendingIntent = PendingIntent. getBroadcast (context, 0, intent, 0); long firstime = SystemClock. elapsedRealtime (); AlarmManager alarmManager = (AlarmManager) context. getSystemService (Context. ALARM_SERVICE); // send the broadcast startServicealarmManager every 20 seconds. setRepeating (AlarmManager. ELAPSED_REALTIME_WAKEUP, firstime, 20*1000, pendingIntent );}}

CheckServiceBroadcastReceiver is as follows:
Package cc. c; import android. content. broadcastReceiver; import android. content. context; import android. content. intent; // check Servicepublic class CheckServiceBroadcastReceiver extends BroadcastReceiver {@ Overridepublic void onReceive (Context context, Intent intent) {if (intent. getAction (). equals ("com.cn. checkServicebroadcasreceiver ") {Intent serviceIntent = new Intent (); serviceIntent. setAction ("cn.com. servicesubclass "); context. startService (serviceIntent );}}}

ServiceSubclass:

Package cc. c; import android. app. service; import android. content. intent; import android. OS. IBinder; // Servicepublic class ServiceSubclass extends Service {@ Overridepublic IBinder onBind (Intent arg0) {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 is as follows:
     
  
 


AndroidManifest. xml is as follows:
 
     
          
      
       
      
                            
                                  
               
                  
          
              
                               
           
                   
          
              
                               
           
                  
          
              
                               
           
                      
 


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.