Android程序真退出與假退出後臺運行詳解

public void onBackPressed() {
  AlertDialog.Builder builder = new Builder(LawdaquanActivity.this);
  builder.setIcon(R.drawable.imagebutton5);
  builder.setTitle("提示");
  builder.setMessage("你真的要退出法律信息軟件嗎?");
  builder.setPositiveButton("是",
    new android.content.DialogInterface.OnClickListener() {
     @Override
     public void onClick(DialogInterface dialog, int which) {
      Intent i = new Intent(Intent.ACTION_MAIN);

      i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

      i.addCategory(Intent.CATEGORY_HOME);

      startActivity(i);

     }
    });
  builder.setNegativeButton("否",
    new android.content.DialogInterface.OnClickListener() {
     @Override
     public void onClick(DialogInterface dialog, int which) {
      dialog.dismiss();
     }
    });
  builder.create().show();

 }

 

————-真退出
退出應用程序的實現:可以自己寫個方法,例如:

public void exitProgrames{

Intent startMain = new Intent(Intent.ACTION_MAIN);

startMain.addCategory(Intent.CATEGORY_HOME);

startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

startActivity(startMain);

android.os.Process.killProcess(android.os.Process.myPid());

 

————–重寫ONKEYDOWN
public boolean onKeyDown(int keyCode, KeyEvent event) {

  if (keyCode == KeyEvent.KEYCODE_BACK) {
   new AlertDialog.Builder(this)
     .setIcon(R.drawable.title)
     .setTitle("退出軟件")
     .setMessage("是否退出法律文書軟件")
     .setPositiveButton("否",
       new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog,
          int which) {
         // TODO Auto-generated method stub

        }
       }).setNegativeButton("退出", new OnClickListener() {

      @Override
      public void onClick(DialogInterface dialog, int which) {
       // TODO Auto-generated method stub
       finish();
      }
     }).create().show();
  }

  else {
   return super.onKeyDown(keyCode, event);

  }

  // TODO Auto-generated method stub
  return super.onKeyDown(keyCode, event);
 }

———–假退出
Intent i = new Intent(Intent.ACTION_MAIN);

      i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

      i.addCategory(Intent.CATEGORY_HOME);

      startActivity(i);
finish();

 

 

摘自 gongzibai的專欄

發佈留言