2014-07-21 43 views
-6

我需要功能從完整應用程序中退出,同時按下後退按鈕。 目前我有一個腳本,要求按兩次退出應用程序,使用確認退出應用程序

因爲它完成當前的活動,但不退出應用程序舊訪問的活動保持不變。 這是我使用的代碼。

int i = 1; 
@Override 
public void onBackPressed() {  
    if (i == 1) { 
     Toast.makeText(getApplicationContext(), "Press back once more to exit.", Toast.LENGTH_SHORT).show(); 
    } else if(i>1) { 
     finish(); 
    } 
    i++; 
} 
+3

可能重複的[Android - 確認應用程序退出與吐司](http://stackoverflow.com/questions/14006461/android-confirm-app-exit-with-toast) – 0101100101

+0

據我所知,你可以清除只有你的應用程序堆棧不是其他人。只有Android OS任務管理器可以訪問。 – VVB

+0

@deepak Sharma您在應用程序中使用了像FLAG_ACTIVITY_REORDER_TO_FRONT這樣的標誌。 –

回答

-2

只有在第二次按下時才能返回新聞稿,並通知用戶再次按下退出。

private static long back_pressed; 

@Override 
public void onBackPressed() 
{ 
     /** If you want to take confirmation then display Alert here...**/ 
     if (back_pressed + 2000 > System.currentTimeMillis()) 
      finish(); /** otherwise directly exit from here...**/ 
     else 
      Toast.makeText(getBaseContext(), "Press once again to exit!", Toast.LENGTH_SHORT).show(); 

     back_pressed = System.currentTimeMillis(); 
} 

Ref。 Android Snippet

+0

不錯的答案,什麼邏輯。 –

+0

這不回答「問題」。 – 323go

+0

@ 323go什麼是回答問題? –

0

請嘗試下面的代碼。

第1步:創建恆類

public class Constant 
{ 
    public static int ACT_COUNT=0; 
} 

第2步:創建BaseActivity類

public class BaseActivity extends Activity 
{ 
private static long back_pressed; 
    @Override 
    protected void onCreate(Bundle arg0) 
    { 
    super.onCreate(arg0); 
    Constant.ACT_COUNT++; 
    } 


    @Override 
    public void onBackPressed() 
    { 
    /** If you want to take confirmation then display Alert here...**/ 
     if(Constant.ACT_COUNT<=1) 
     { 
      if (back_pressed + 2000 > System.currentTimeMillis()) 
       finish(); /** otherwise directly exit from here...**/ 
      else 
       Toast.makeText(getBaseContext(), "Press once again to exit!", Toast.LENGTH_SHORT).show(); 

      back_pressed = System.currentTimeMillis(); 
     } 
     else 
      super.onBackPressed(); 
    } 

    @Override 
    protected void onDestroy() 
    { 
     super.onDestroy(); 
     Constant.ACT_COUNT--; 
    } 

} 

注意:您的應用程序中使用BaseActivity而不是活動除外登錄活動和註冊活動(如果它在您的應用程序中)。