Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發 >> 關於android開發 >> Android,androiddeveloper

Android,androiddeveloper

編輯:關於android開發

Android,androiddeveloper


實現android雙擊後退鍵退出當前APP功能

實現該功能基本思路是,

1, 監聽後退鍵 , 比較兩次後退間隔 , 低於兩秒則出發退出

2, 退出當前APP 

我選擇在基類中BaseActivity 中設置監聽,代碼如下:

@Override
    public void onBackPressed() {

        //Preferences 中獲取是否雙擊退出
        boolean isDoubleClick = true;
        //BaseApplication.get("ifDoubleClickedBack", true);

        if (isDoubleClick) {
            long curTime = SystemClock.uptimeMillis();
            if ((curTime - mBackPressedTime) < (2 * 1000)) {
                finish();
                //activity棧管理
                AppManager.getAppManager().AppExit();
            } else {
                mBackPressedTime = curTime;
                Toast.makeText(this, "再次點擊退出", Toast.LENGTH_SHORT).show();
            }
        } else {
            finish();
        }

    }

 

在退出當前APP中,參考開源中國,封裝了activity棧

public class AppManager { private static Stack<Activity> activityStack; private static AppManager instance; private AppManager() { } /** * 單一實例 */ public static AppManager getAppManager() { if (instance == null) { instance = new AppManager(); } if (activityStack == null) { activityStack = new Stack<Activity>(); } return instance; } /** * 獲取指定的Activity * * @author kymjs */ public static Activity getActivity(Class<?> cls) { if (activityStack != null) for (Activity activity : activityStack) { if (activity.getClass().equals(cls)) { return activity; } } return null; } /** * 添加Activity到堆棧 */ public void addActivity(Activity activity) { activityStack.add(activity); } /** * 獲取當前Activity(堆棧中最後一個壓入的) */ public Activity currentActivity() { Activity activity = activityStack.lastElement(); return activity; } /** * 結束當前Activity(堆棧中最後一個壓入的) */ public void finishActivity() { Activity activity = activityStack.lastElement(); finishActivity(activity); } /** * 結束指定的Activity */ public void finishActivity(Activity activity) { if (activity != null && activityStack.contains(activity)) { activityStack.remove(activity); activity.finish(); } } /** * 結束指定的Activity */ public void removeActivity(Activity activity) { if (activity != null && activityStack.contains(activity)) { activityStack.remove(activity); } } /** * 結束指定類名的Activity */ public void finishActivity(Class<?> cls) { for (Activity activity : activityStack) { if (activity.getClass().equals(cls)) { finishActivity(activity); break; } } } /** * 結束所有Activity */ public void finishAllActivity() { for (int i = 0, size = activityStack.size(); i < size; i++) { if (null != activityStack.get(i)) { finishActivity(activityStack.get(i)); } } activityStack.clear(); } /** * 退出應用程序 */ public void AppExit() { try { finishAllActivity(); // System.exit(0); } catch (Exception e) { } } } View Code

思路就是在每次activity 壓入activity棧中管理

在退出時遍歷棧,挨個finish

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved