Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android實現防止被系統回收的Service

Android實現防止被系統回收的Service

編輯:關於Android編程

MainActivity如下:
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描述:
 * 實現防止被系統回收的Service.
 * 在某些情況下Service會被系統kill掉.在網上找了不少方法,雖然都號稱
 * 可以避免被系統回收,但貌似都不夠可靠.
 * 在此換一種方式來實現,思路:
 * 利用AlarmManager定時間隔(比如5S,20S)來不斷的startService().
 * (1)如果該服務被回收,那麼會調用Service的onCreate()和onStart()
 * (2)如果未該服務被回收,則只會調用Service的onStart()
 * 利用該方式曲線實現防止被系統回收Service
 * 
 * 測試環境:
 * Android:2.3.6 + ME525+
 * 
 * 測試方法:
 * 1 部署應用到設備
 * 2 重啟設備
 * 3 設備重啟後,點擊進入該應用.點擊界面上的Button
 * 4 查看Log
 * 
 * 
 * 注意事項:
 * 1 4.0及其以上請注意開機廣播監聽的實現
 * 2 注意權限
 *   
 *     
 *   
 * 備注說明:
 * 1 在殺死某進程時有時需要判斷該進程所屬的Activity是否正在屏幕上顯示
 *   該方法請參見getTopActivityNameAndProcessName()
 * 2 若有其余的方法,請留言指教.多謝.
 * 
 */
public class MainActivity extends Activity {
	private Button mButton;
	private long lastTime = 0;
	private Context mContext;

	@Override
	protected 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() {
			@Override
			public void onClick(View view) {
				if ((System.currentTimeMillis() - lastTime) > 2000) {
					lastTime = System.currentTimeMillis();
					cleanMemory(mContext);
				}

			}
		});
	}

	//模擬服務被系統回收
	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("------>殺掉本應用");
					int pid = runningAppProcessInfo.pid;
					Process.killProcess(pid);
				}
			}
		}

	}
	
	//獲取棧頂Activity及其所屬進程
	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("\\.");
	    	 //棧頂Activity的名稱
	    	 topActivityName=temp[temp.length-1];
	    	 int index=topActivityClassName.lastIndexOf(".");
	    	//棧頂Activity所屬進程的名稱
	    	 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;
//監聽開機廣播
public class BootCompletedBroadcastReceiver extends BroadcastReceiver {
	@Override
	public void onReceive(Context context, Intent intent) {
		//接收到開機廣播
		if(intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){
			sendCheckServiceBroadcast(context);
		}

	}
	
	//發送廣播
	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);
		//每間隔20秒發送廣播startService
		alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstime,20 * 1000, pendingIntent);
	}
	
}

CheckServiceBroadcastReceiver如下:
package cc.c;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
//檢查Service
public class CheckServiceBroadcastReceiver extends BroadcastReceiver {
	@Override
	public 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;
//執行業務邏輯的Service
public class ServiceSubclass extends Service {

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		System.out.println("------>service onCreate()");
	}
	
	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		System.out.println("------>service onStart()");
	}
	

}

main.xml如下:


    


AndroidManifest.xml如下:



    
    
    
    
     
      

    
        
            
                

                
            
        

        
        
            
                
            
        
        
         
        
            
                
            
        
        
        
        
            
                
            
        
        
        
    



  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved