安卓应用kill 自身并启动

安卓应用kill自身并启动

1.为了杀掉程序并重新启动,需要借助一个中间activity,并且该activity是另外一个进程,在该activity中调用killProcess杀掉原进程

				  
  

(2)启动到中间activity
Intent i = new Intent(this, EmptyActivity.class);//借助中间层自启
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra(EmptyActivity.INTENT_KILL, true);
i.putExtra(EmptyActivity.INTENT_PID, android.os.Process.myPid());
startActivity(i);
finish();
Application.getApplication().finishAllActivity();//不加入这个,当killProcess后,还会重启一次
//Application建立Stack activityStack 保存启动的activity,最后finishAllActivity	

  /** 
     * 添加Activity到堆栈 
     */  
    public void addActivity(Activity activity){  
        if(activityStack==null){  
            activityStack=new Stack();  
        }  
        activityStack.add(activity);  
    }  
    
    /** 
     * 结束所有Activity 
     */  
    public void finishAllActivity(){  
        for (int i = 0, size = activityStack.size(); i < size; i++){  
            if (null != activityStack.get(i)){  
                activityStack.get(i).finish();  
            }  
        }  
        activityStack.clear();  
    }  

(3)在中间Activity:EmptyActivity中杀掉进程并重启
protected void onCreate(android.os.Bundle savedInstanceState) {
		  super.onCreate(savedInstanceState);
		  setContentView(R.layout.empty);
		  try {
			  if(getIntent().getBooleanExtra(INTENT_KILL, false)){
				     //android.os.Process.killProcess(getIntent().getExtras().getInt(INTENT_PID));
	                Intent i = new Intent(EmptyActivity.this, WelcomeActivity.class);
	                startActivity(i);
	                EmptyActivity.this.finish();
	                android.os.Process.killProcess(getIntent().getExtras().getInt(INTENT_PID));
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
	  }



2.如果通过android.os.Process.killProcess(pid)杀掉程序后,并重启了WelcomeActivity,最后按back退出WelcomeActivity时,

若程序再重启了一次,那请先看看http://blog.csdn.net/liuyifirsttime/article/details/52130872

你可能感兴趣的:(学习笔记)