`
445822357
  • 浏览: 739247 次
文章分类
社区版块
存档分类
最新评论

防止Android程序被系统kill掉的处理方法

 
阅读更多

转载请注明出处:http://blog.csdn.net/cuiran/article/details/38851401


目前遇到一个问题程序需要一直运行,并显示在最前端,但是运行一段时间发现会被系统Kill掉,这样程序就退出回到了桌面,不能实现一直运行的效果。为了实现此效果,也想了一些办法。如下:

1、可以将应用改为系统应用——由于程序需要定期更新,如果被放入系统应用,更新会非常麻烦,故没有采用。

2、在软件的onDestroy()方法中,发送重新启动应用的广播——如果程序是直接被kill掉 不会调用onDestroy方法(如果有发现应用被kill掉还会调用此方法,可以留言告知,非常感谢!)

3、新建一个Service,在后台服务定时去检测对应package是否在运行,若没有运行就发送广播告知。

为了实现效果程序同时实现2,3两种方式。

首先新建一个apk将级别改为系统应用,需要添加

android:sharedUserId="android.uid.system"

在此apk中新建一个BroadcastReceiver用于接收重启程序的广播,收到广播会启动所需要运行的apk

然后在新建Service,在Service实现了对所需package是否运行和是否安装的检测,如果没有运行,再检测是否安装,若安装,会发送广播让其启动应用程序

/**
 * CheckService.java
 * Copyright(C) 2014
 * creator:cuiran 2014-8-26 下午1:20:01
 */
package com.xsdl.count.service;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;


import com.xsdl.count.receiver.Constants;
import com.xsdl.count.util.LogsUtil;




import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.Service;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

/**
 * 后台开启服务定时检测 
 * @author cuiran
 * @version 1.0.0
 */
public class CheckService extends Service {
	private static final String TAG="CheckService";
	private static final String ProcessName = "com.ghyf.mplay"; 
	@Override
	public IBinder onBind(Intent arg0) {
	
		return null;
	}

	/* (non-Javadoc)
	 * @see android.app.Service#onCreate()
	 */
	@Override
	public void onCreate() {
		LogsUtil.i(TAG, "检测服务启动---->>>> ");
		
		taskMail = new TimerTask() {  
		    @Override 
		    public void run() {  
		      
		        Message message = new Message();  
		        message.what = 1;  
		        handlerMail.sendMessage(message);  
		    }  
		};
		timerMail.schedule(taskMail, 15000, 5000); 
		
		
		super.onCreate();
	}
	private final Timer timerMail = new Timer();  
	private TimerTask taskMail;  
	@SuppressLint("HandlerLeak")
	Handler handlerMail = new Handler() {  
	    @Override 
	    public void handleMessage(Message msg) {  
	        // 要做的事情  
	        try {
	        	boolean is=isBackgroundRunning();
	        	LogsUtil.i(TAG, "检测播控器 "+ProcessName+" is "+is);
	        	if(!is){
	        		/**
	        		 * 发送广播通知应用启动
	        		 */
	        		if(checkPackage()){
	        			 Intent myIntent = new Intent(Constants.RESOFTWARE_RECEIVER);  
		       			 myIntent.putExtra("path","test");
		       			 myIntent.setAction(Constants.RESOFTWARE_RECEIVER);  
		       			 sendBroadcast(myIntent);  
	        		}
	       			 
	        	}
			} catch (Exception e) {
				
				e.printStackTrace();
			}
	    } 
	};
	ActivityManager activityManager=null;
	PackageManager packageManager=null;
    PackageInfo pi = null;   
    /**
     * 检测package是否存在<br>
     * 2014-8-26 下午3:58:49
     * @return
     *
     */
	  public boolean checkPackage() {
		  boolean flag=false;
		   packageManager = getPackageManager(); 
	      try { 
              pi = packageManager.getPackageInfo(ProcessName, 0); 
              if(null!=pi){
            	  flag=true;
              }
          } catch (NameNotFoundException e) { 
        	  flag=false;
        	  LogsUtil.e(TAG, "出现异常", e);
          } 
          
		  return flag;
	  }
	  /**
	     * 检测package是否在运行<br>
	     * 2014-8-26 下午3:58:49
	     * @return
	     *
	     */
	private boolean isBackgroundRunning() {
		
		 activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
		
		if (activityManager == null) return false;
			// get running tasks processes
			List<ActivityManager.RunningTaskInfo> processList = activityManager.getRunningTasks(100);
			for (ActivityManager.RunningTaskInfo info : processList) {
				if (info.topActivity.getPackageName().startsWith(ProcessName)) {
					return true;
				}
			}
			return false;
		}
	/* (non-Javadoc)
	 * @see android.app.Service#onDestroy()
	 */
	@Override
	public void onDestroy() {
		
	     try { 
	    	 /**
	    	  * 释放资源
	    	  */
	    	 if(taskMail!=null){
	    		 taskMail.cancel();
	    	 }
	    	 if(timerMail!=null){
	    		 timerMail.cancel();
	    	 }
         } catch (Exception e) { 
       	  LogsUtil.e(TAG, "出现异常", e);
         } 
         
		super.onDestroy();
	}

	
}

启动应用程序可以采用如下两种方式:

第一种是直接通过Android的startActivity

  public  void openCLD(String packageName,Context context) { 
		  PackageManager packageManager = context.getPackageManager(); 
	        PackageInfo pi = null;   
	         
	            try { 
	                 
	                pi = packageManager.getPackageInfo(packageName, 0); 
	            } catch (NameNotFoundException e) { 
	                 LogsUtil.e("pi", "出现异常", e);
	            } 
	            
	            
	            Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null); 
	            resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER); 
	            resolveIntent.setPackage(pi.packageName); 
	 
	            List<ResolveInfo> apps = packageManager.queryIntentActivities(resolveIntent, 0); 
	 
	            ResolveInfo ri = apps.iterator().next(); 
	            if (ri != null ) { 
	                String className = ri.activityInfo.name; 
	 
	                Intent intent = new Intent(Intent.ACTION_MAIN); 
	                intent.addCategory(Intent.CATEGORY_LAUNCHER); 
	 
	                ComponentName cn = new ComponentName(packageName, className); 
	 
	                intent.setComponent(cn); 
	                context.startActivity(intent); 
	            } 
	    } 

第二种是通过执行命令 am start package/package.Activity这种方式启动。


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics