提供两个主要类吧.
添加权限:
<uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES"/>
<uses-permission android:name="android.permission.RESTART_PACKAGES"/>
Exit
package net.driverclient.app.bean;
import java.io.Serializable;
import android.os.Handler;
import android.os.HandlerThread;
/**
* 退出
* @author Bert Guo
* 2013-3-3
*/
public class Exit implements Serializable {
private boolean isExit = false;
private Runnable task = new Runnable() {
public void run() {
isExit = false;
}
};
public void doExitInOneSecond() {
isExit = true;
HandlerThread thread = new HandlerThread("doTask");
thread.start();
new Handler(thread.getLooper()).postDelayed(task, 1000);
}
public boolean isExit() {
return isExit;
}
public void setExit(boolean isExit) {
this.isExit = isExit;
}
}
MainActivity
package net.driver.app.ui;
import net.driver.app.AppContext;
import net.driver.app.R;
import net.driver.app.base.BaseActivity;
import net.driver.app.bean.Exit;
import net.driver.app.common.UIHelper;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
/**
* 主界面
* @author Bert Guo
* 2013-4-2
*/
public class Main extends BaseActivity {
private Exit exit = new Exit(); // 退出
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@Override
public void onBackPressed() {
// TODO Auto-generated method stub
if (exit.isExit()) {
android.os.Process.killProcess(android.os.Process.myPid()); // 获取PID
System.exit(0);
} else {
Toast.makeText(getApplicationContext(), "再按一次退出程序",
Toast.LENGTH_SHORT).show();
exit.doExitInOneSecond();
}
}
}