2013-06-03 26 views
2

我已經使用以下方法通過提示alertbox退出應用程序的用戶。
但我的申請是要求2次離開。應用程序詢問兩次退出與onBackPressed()

代碼:

@Override 
    public void onBackPressed() 
    { 
     new AlertDialog.Builder(this) 
     .setTitle("Closing Activity") 
     .setMessage("Are you sure you want to close this activity?") 
     .setPositiveButton("Yes", new DialogInterface.OnClickListener() 
      { 
       @Override 
       public void onClick(DialogInterface dialog, int which) { 
        finish();  
       } 
      }) 
     .setNegativeButton("No", null) 
     .show(); 
    } 
+2

你'覆蓋'finish()'方法?此外,我會說這是一個壞主意,恕我直言,除非絕對必要如保存數據 – codeMagic

+0

你也覆蓋onkeydown嗎? – stinepike

+0

給你的整個活動或顯示,如果你重寫destroy()或finish()方法 – anddevmanu

回答

5

這可能是幾件事情的結果:

  1. 您還覆蓋void onKeyDown(...)void dispatchKeyEvent(...) ,並在那裏

  2. 已覆蓋調用onBackPressed();void finish()
    有你所說的第二個對話框

  3. 你的應用實例化2次
    (以任何理由 - 看你的代碼)

  4. 打開,意圖您的活動特意兩次,然後我有一個固定在這裏:)
    更換您的代碼與這片打開它:

    Intent intent = new Intent(this, yourSubActivityClass.class); 
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
    startActivity(intent); 
    

    從文檔:

    如果已設置,並且正在啓動的活動已在當前任務中運行,則不會啓動該活動的新實例,而是關閉其上的所有其他活動,並將此Intent交付給(現在名列前茅)作爲新意圖的舊活動。

  5. 如果一些那些幫助過你,請你告訴我在評論
    否則張貼更多的代碼,我會盡力幫助你更多;)

+0

謝謝你@ Schnizel1337它的工作原理我刪除了從OnBackPressed方法覆蓋並清除頂部。它現在正常工作..非常感謝你... !!!! –

+0

沒問題,那麼你可以用左邊的按鈕接受我的回答,所以其他人可以看到它是正確的:) – bricklore

0
//I use this : 

public class MyActivity extends Activity 
    { 
    private int BackPressedCount=0; //press count 

    private void StartTimer() 
     { 
     TimerTask TT=new TimerTask() 
      { 
      @Override 
      public void run() 
       { 
       try 
        { 
        //if second press not detect in 1 second,reset and stop timer 
        BackPressedCount=0; 
        this.cancel(); 
        } 
       catch(Exception E) 
        { 
        } 
       } 
      }; 
     new Timer().scheduleAtFixedRate(TT, 1000, 1000);// init timer for 1 second period 
     } 

    @Override 
    public void onBackPressed() 
     { 
     //super.onBackPressed(); 

     BackPressedCount++; //every press 

     if(BackPressedCount==1) // if first press detect run Timer (wait for second press) 
      StartTimer(); 

     if(BackPressedCount==2) // if second press detect then finish 
      finish(); 

     Toast.makeText(getBaseContext(),"Press again to exit" ,Toast.LENGTH_SHORT).show(); 
     } 

    } 
+0

你可以添加一些解釋或評論,以幫助澄清你的答案? – skrrgwasme

+0

是的,我可以! ,我試圖添加評論 – Kourosh