对Android近期任务列表(Recent Applications)的简单分析

简介:

http://www.cnblogs.com/coding-way/archive/2013/06/05/3118732.html

这里的近期任务列表就是长按Home键出来的那个Dialog,里面放着近期打开过的应用,当然3.0以上系统的多任务切换键也是。

这个Dialog的实现在Android源码的/frameworks/base/policy/src/com/android/internal/policy/impl/RecentApplicationsDialog.java中。

接下来就对这个源码分析一下。

public class RecentApplicationsDialog extends Dialog implements OnClickListener {
    // Elements for debugging support
//  private static final String LOG_TAG = "RecentApplicationsDialog";
    private static final boolean DBG_FORCE_EMPTY_LIST = false;

    static private StatusBarManager sStatusBar;

    private static final int NUM_BUTTONS = 8;
    private static final int MAX_RECENT_TASKS = NUM_BUTTONS * 2;    // allow for some discards

    final TextView[] mIcons = new TextView[NUM_BUTTONS];
    View mNoAppsText;
    IntentFilter mBroadcastIntentFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);

    class RecentTag {
        ActivityManager.RecentTaskInfo info;
        Intent intent;
    }

    Handler mHandler = new Handler();
    Runnable mCleanup = new Runnable() {
        public void run() {
            // dump extra memory we're hanging on to
            for (TextView icon: mIcons) {
                icon.setCompoundDrawables(null, null, null, null);
                icon.setTag(null);
            }
        }
    };

    public RecentApplicationsDialog(Context context) {
        super(context, com.android.internal.R.style.Theme_Dialog_RecentApplications);

    }

    /**
     * We create the recent applications dialog just once, and it stays around (hidden)
     * until activated by the user.
     *
     * @see PhoneWindowManager#showRecentAppsDialog
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Context context = getContext();

        if (sStatusBar == null) {
            sStatusBar = (StatusBarManager)context.getSystemService(Context.STATUS_BAR_SERVICE);
        }

        Window window = getWindow();
        window.requestFeature(Window.FEATURE_NO_TITLE);
        window.setType(WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
        window.setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
                WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        window.setTitle("Recents");

        setContentView(com.android.internal.R.layout.recent_apps_dialog);

        final WindowManager.LayoutParams params = window.getAttributes();
        params.width = WindowManager.LayoutParams.MATCH_PARENT;
        params.height = WindowManager.LayoutParams.MATCH_PARENT;
        window.setAttributes(params);
        window.setFlags(0, WindowManager.LayoutParams.FLAG_DIM_BEHIND);

        //默认显示8个
        mIcons[0] = (TextView)findViewById(com.android.internal.R.id.button0);
        mIcons[1] = (TextView)findViewById(com.android.internal.R.id.button1);
        mIcons[2] = (TextView)findViewById(com.android.internal.R.id.button2);
        mIcons[3] = (TextView)findViewById(com.android.internal.R.id.button3);
        mIcons[4] = (TextView)findViewById(com.android.internal.R.id.button4);
        mIcons[5] = (TextView)findViewById(com.android.internal.R.id.button5);
        mIcons[6] = (TextView)findViewById(com.android.internal.R.id.button6);
        mIcons[7] = (TextView)findViewById(com.android.internal.R.id.button7);
        mNoAppsText = findViewById(com.android.internal.R.id.no_applications_message);

        //关键在哪,你懂得...
        for (TextView b: mIcons) {
            b.setOnClickListener(this);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_TAB) {
            // Ignore all meta keys other than SHIFT.  The app switch key could be a
            // fallback action chorded with ALT, META or even CTRL depending on the key map.
            // DPad navigation is handled by the ViewRoot elsewhere.
            final boolean backward = event.isShiftPressed();
            final int numIcons = mIcons.length;
            int numButtons = 0;
            while (numButtons < numIcons && mIcons[numButtons].getVisibility() == View.VISIBLE) {
                numButtons += 1;
            }
            if (numButtons != 0) {
                int nextFocus = backward ? numButtons - 1 : 0;
                for (int i = 0; i < numButtons; i++) {
                    if (mIcons[i].hasFocus()) {
                        if (backward) {
                            nextFocus = (i + numButtons - 1) % numButtons;
                        } else {
                            nextFocus = (i + 1) % numButtons;
                        }
                        break;
                    }
                }
                final int direction = backward ? View.FOCUS_BACKWARD : View.FOCUS_FORWARD;
                if (mIcons[nextFocus].requestFocus(direction)) {
                    mIcons[nextFocus].playSoundEffect(
                            SoundEffectConstants.getContantForFocusDirection(direction));
                }
            }

            // The dialog always handles the key to prevent the ViewRoot from
            // performing the default navigation itself.
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    /**
     * Dismiss the dialog and switch to the selected application.
     */
    public void dismissAndSwitch() {
        final int numIcons = mIcons.length;
        RecentTag tag = null;
        for (int i = 0; i < numIcons; i++) {
            if (mIcons[i].getVisibility() != View.VISIBLE) {
                break;
            }
            if (i == 0 || mIcons[i].hasFocus()) {
                tag = (RecentTag) mIcons[i].getTag();
                if (mIcons[i].hasFocus()) {
                    break;
                }
            }
        }
        if (tag != null) {
            switchTo(tag);
        }
        dismiss();
    }

    /**
     * Handler for user clicks.  If a button was clicked, launch the corresponding activity.
     */
    public void onClick(View v) {
        for (TextView b: mIcons) {
            if (b == v) {
                RecentTag tag = (RecentTag)b.getTag();
                switchTo(tag);
                break;
            }
        }
        dismiss();
    }

    //
    private void switchTo(RecentTag tag) {
        if (tag.info.id >= 0) {
            // This is an active task; it should just go to the foreground.
            final ActivityManager am = (ActivityManager)
                    getContext().getSystemService(Context.ACTIVITY_SERVICE);
            am.moveTaskToFront(tag.info.id, ActivityManager.MOVE_TASK_WITH_HOME);
        } else if (tag.intent != null) {
            tag.intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY
                    | Intent.FLAG_ACTIVITY_TASK_ON_HOME);
            try {
                getContext().startActivity(tag.intent);
            } catch (ActivityNotFoundException e) {
                Log.w("Recent", "Unable to launch recent task", e);
            }
        }
    }

    /**
     * Set up and show the recent activities dialog.
     */
    @Override
    public void onStart() {
        super.onStart();
        reloadButtons();
        if (sStatusBar != null) {
            sStatusBar.disable(StatusBarManager.DISABLE_EXPAND);
        }

        // receive broadcasts
        getContext().registerReceiver(mBroadcastReceiver, mBroadcastIntentFilter);

        mHandler.removeCallbacks(mCleanup);
    }

    /**
     * Dismiss the recent activities dialog.
     */
    @Override
    public void onStop() {
        super.onStop();

        if (sStatusBar != null) {
            sStatusBar.disable(StatusBarManager.DISABLE_NONE);
        }

        // stop receiving broadcasts
        getContext().unregisterReceiver(mBroadcastReceiver);

        mHandler.postDelayed(mCleanup, 100);
     }

    /**
     * Reload the 6 buttons with recent activities
     */
    private void reloadButtons() {

        final Context context = getContext();
        final PackageManager pm = context.getPackageManager();
        final ActivityManager am = (ActivityManager)
                context.getSystemService(Context.ACTIVITY_SERVICE);
        final List<ActivityManager.RecentTaskInfo> recentTasks =
                am.getRecentTasks(MAX_RECENT_TASKS, ActivityManager.RECENT_IGNORE_UNAVAILABLE);

        ActivityInfo homeInfo = 
            new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME)
                    .resolveActivityInfo(pm, 0);

        IconUtilities iconUtilities = new IconUtilities(getContext());

        // Performance note:  Our android performance guide says to prefer Iterator when
        // using a List class, but because we know that getRecentTasks() always returns
        // an ArrayList<>, we'll use a simple index instead.
        int index = 0;
        int numTasks = recentTasks.size();
        for (int i = 0; i < numTasks && (index < NUM_BUTTONS); ++i) {
            final ActivityManager.RecentTaskInfo info = recentTasks.get(i);

            // for debug purposes only, disallow first result to create empty lists
            if (DBG_FORCE_EMPTY_LIST && (i == 0)) continue;

            Intent intent = new Intent(info.baseIntent);
            if (info.origActivity != null) {
                intent.setComponent(info.origActivity);
            }

            // Skip the current home activity.
            if (homeInfo != null) {
                if (homeInfo.packageName.equals(
                        intent.getComponent().getPackageName())
                        && homeInfo.name.equals(
                                intent.getComponent().getClassName())) {
                    continue;
                }
            }

            intent.setFlags((intent.getFlags()&~Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED)
                    | Intent.FLAG_ACTIVITY_NEW_TASK);
            final ResolveInfo resolveInfo = pm.resolveActivity(intent, 0);
            if (resolveInfo != null) {
                final ActivityInfo activityInfo = resolveInfo.activityInfo;
                final String title = activityInfo.loadLabel(pm).toString();
                Drawable icon = activityInfo.loadIcon(pm);

                if (title != null && title.length() > 0 && icon != null) {
                    final TextView tv = mIcons[index];
                    tv.setText(title);
                    icon = iconUtilities.createIconDrawable(icon);
                    tv.setCompoundDrawables(null, icon, null, null);
                    RecentTag tag = new RecentTag();
                    tag.info = info;
                    tag.intent = intent;
                    tv.setTag(tag);
                    tv.setVisibility(View.VISIBLE);
                    tv.setPressed(false);
                    tv.clearFocus();
                    ++index;
                }
            }
        }

        // handle the case of "no icons to show"
        mNoAppsText.setVisibility((index == 0) ? View.VISIBLE : View.GONE);

        // hide the rest
        for (; index < NUM_BUTTONS; ++index) {
            mIcons[index].setVisibility(View.GONE);
        }
    }

    /**
     * This is the listener for the ACTION_CLOSE_SYSTEM_DIALOGS intent.  It's an indication that
     * we should close ourselves immediately, in order to allow a higher-priority UI to take over
     * (e.g. phone call received).
     */
    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
                String reason = intent.getStringExtra(PhoneWindowManager.SYSTEM_DIALOG_REASON_KEY);
                if (! PhoneWindowManager.SYSTEM_DIALOG_REASON_RECENT_APPS.equals(reason)) {
                    dismiss();
                }
            }
        }
    };
}

RecentApplicationsDialog.java完整源码

从源码可以看出,关键部分有三处。

 

一个很关键的内部类:

// 每个任务都包含一个Tag,这个Tag保存着这个App的一些非常有用的信息
    class RecentTag {
        ActivityManager.RecentTaskInfo info;
        Intent intent;
    }

这个RecentTag保存在每个近期任务的图标里,并且保存着这个任务的原始信息。

 

刚启动Dialog时对每个任务的初始化:

private void reloadButtons() {

        final Context context = getContext();
        final PackageManager pm = context.getPackageManager();
        final ActivityManager am = (ActivityManager)
                context.getSystemService(Context.ACTIVITY_SERVICE);
                
        //拿到最近使用的应用的信息列表
        final List<ActivityManager.RecentTaskInfo> recentTasks =
                am.getRecentTasks(MAX_RECENT_TASKS, ActivityManager.RECENT_IGNORE_UNAVAILABLE);

        //自制一个home activity info,用来区分
        ActivityInfo homeInfo = 
            new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME)
                    .resolveActivityInfo(pm, 0);

        IconUtilities iconUtilities = new IconUtilities(getContext());

        int index = 0;
        int numTasks = recentTasks.size();
        //开始初始化每个任务的信息
        for (int i = 0; i < numTasks && (index < NUM_BUTTONS); ++i) {
            final ActivityManager.RecentTaskInfo info = recentTasks.get(i);

            //复制一个任务的原始Intent
            Intent intent = new Intent(info.baseIntent);
            if (info.origActivity != null) {
                intent.setComponent(info.origActivity);
            }

            //跳过home activity
            if (homeInfo != null) {
                if (homeInfo.packageName.equals(
                        intent.getComponent().getPackageName())
                        && homeInfo.name.equals(
                                intent.getComponent().getClassName())) {
                    continue;
                }
            }

            intent.setFlags((intent.getFlags()&~Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED)
                    | Intent.FLAG_ACTIVITY_NEW_TASK);
            final ResolveInfo resolveInfo = pm.resolveActivity(intent, 0);
            if (resolveInfo != null) {
                final ActivityInfo activityInfo = resolveInfo.activityInfo;
                final String title = activityInfo.loadLabel(pm).toString();
                Drawable icon = activityInfo.loadIcon(pm);

                if (title != null && title.length() > 0 && icon != null) {
                    final TextView tv = mIcons[index];
                    tv.setText(title);
                    icon = iconUtilities.createIconDrawable(icon);
                    tv.setCompoundDrawables(null, icon, null, null);
                    //new一个Tag,保存这个任务的RecentTaskInfo和Intent
                    RecentTag tag = new RecentTag();
                    tag.info = info;
                    tag.intent = intent;
                    tv.setTag(tag);
                    tv.setVisibility(View.VISIBLE);
                    tv.setPressed(false);
                    tv.clearFocus();
                    ++index;
                }
            }
        }

       ...//无关紧要的代码
    }

这里的过程是:先用ActivityManager获取RecentTasks并生成一个List,然后利用这个List为Dialog中的每个任务初始化,并生成对应的信息RecentTag。

需要注意的是,RecentTag中的Intent是从对应任务的原始Intent复制过来的,这意味着那个原始Intent的一些Extra参数将会一并复制过来,

我来举个例子:比如我的App支持从第三方启动,并且第三方要提供一个token,当然这个token就以Extra参数的形式放进Intent里,然后通过startActivity()启动我的App;然后我的App根据这个token来处理,注意这里,当我的App退出后,再从近期任务里启动这个App,之前的那个token还会传递给我的App,这里就会出现错误了,原因就是上面分析的。这就是为什么从第三方跳转的应用不会出现在近期任务的列表里(比如点击短信里的url启动一个浏览器,之后近期任务里只有短信app,不会出现浏览器app)。要想不出现在近期任务里,可以给Intent设置FLAG_ACTIVITY_NO_HISTORY标志。

 

响应每个任务的点击事件:

private void switchTo(RecentTag tag) {
        if (tag.info.id >= 0) {
            // 这个Task没有退出,直接移动到前台
            final ActivityManager am = (ActivityManager)
                    getContext().getSystemService(Context.ACTIVITY_SERVICE);
            am.moveTaskToFront(tag.info.id, ActivityManager.MOVE_TASK_WITH_HOME);
        } else if (tag.intent != null) {
            //task退出了的话,id为-1,则使用RecentTag中的Intent重新启动
            tag.intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY
                    | Intent.FLAG_ACTIVITY_TASK_ON_HOME);
            try {
                getContext().startActivity(tag.intent);
            } catch (ActivityNotFoundException e) {
                Log.w("Recent", "Unable to launch recent task", e);
            }
        }
    }

如果该Task没有退出,只是切到后台,则切换到前台;如果已经退出,就要重新启动了。

这里的Intent就是之前说的,重复使用的旧Intent了,这里注意,系统添加了FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY和FLAG_ACTIVITY_TASK_ON_HOME标志,所以我们可以在App中通过判断Intent的flag是否包含这两个来判断是否是从近期任务里启动的。注意FLAG_ACTIVITY_TASK_ON_HOME标志是Api 11添加的,所以11一下的之判断FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY就行了。


相关文章
|
2月前
|
开发框架 前端开发 Android开发
Flutter 与原生模块(Android 和 iOS)之间的通信机制,包括方法调用、事件传递等,分析了通信的必要性、主要方式、数据传递、性能优化及错误处理,并通过实际案例展示了其应用效果,展望了未来的发展趋势
本文深入探讨了 Flutter 与原生模块(Android 和 iOS)之间的通信机制,包括方法调用、事件传递等,分析了通信的必要性、主要方式、数据传递、性能优化及错误处理,并通过实际案例展示了其应用效果,展望了未来的发展趋势。这对于实现高效的跨平台移动应用开发具有重要指导意义。
272 4
|
2月前
|
安全 Android开发 数据安全/隐私保护
深入探讨iOS与Android系统安全性对比分析
在移动操作系统领域,iOS和Android无疑是两大巨头。本文从技术角度出发,对这两个系统的架构、安全机制以及用户隐私保护等方面进行了详细的比较分析。通过深入探讨,我们旨在揭示两个系统在安全性方面的差异,并为用户提供一些实用的安全建议。
|
4月前
|
开发工具 Android开发 Swift
安卓与iOS开发环境对比分析
在移动应用开发的广阔舞台上,安卓和iOS这两大操作系统无疑是主角。它们各自拥有独特的特点和优势,为开发者提供了不同的开发环境和工具。本文将深入浅出地探讨安卓和iOS开发环境的主要差异,包括开发工具、编程语言、用户界面设计、性能优化以及市场覆盖等方面,旨在帮助初学者更好地理解两大平台的开发特点,并为他们选择合适的开发路径提供参考。通过比较分析,我们将揭示不同环境下的开发实践,以及如何根据项目需求和目标受众来选择最合适的开发平台。
59 2
|
25天前
|
存储 监控 API
app开发之安卓Android+苹果ios打包所有权限对应解释列表【长期更新】-以及默认打包自动添加权限列表和简化后的基本打包权限列表以uniapp为例-优雅草央千澈
app开发之安卓Android+苹果ios打包所有权限对应解释列表【长期更新】-以及默认打包自动添加权限列表和简化后的基本打包权限列表以uniapp为例-优雅草央千澈
|
2月前
|
安全 Android开发 数据安全/隐私保护
深入探索Android与iOS系统安全性的对比分析
在当今数字化时代,移动操作系统的安全已成为用户和开发者共同关注的重点。本文旨在通过比较Android与iOS两大主流操作系统在安全性方面的差异,揭示两者在设计理念、权限管理、应用审核机制等方面的不同之处。我们将探讨这些差异如何影响用户的安全体验以及可能带来的风险。
91 21
|
1月前
|
Java 开发工具 Android开发
安卓与iOS开发环境对比分析
在移动应用开发的广阔天地中,安卓和iOS两大平台各自占据半壁江山。本文深入探讨了这两个平台的开发环境,从编程语言、开发工具到用户界面设计等多个角度进行比较。通过实际案例分析和代码示例,我们旨在为开发者提供一个清晰的指南,帮助他们根据项目需求和个人偏好做出明智的选择。无论你是初涉移动开发领域的新手,还是寻求跨平台解决方案的资深开发者,这篇文章都将为你提供宝贵的信息和启示。
36 8
|
3月前
|
缓存 Java Shell
Android 系统缓存扫描与清理方法分析
Android 系统缓存从原理探索到实现。
107 15
Android 系统缓存扫描与清理方法分析
|
2月前
|
Linux Android开发 iOS开发
深入探索Android与iOS的多任务处理机制
在移动操作系统领域,Android和iOS各有千秋,尤其在多任务处理上展现出不同的设计理念和技术实现。本文将深入剖析两大平台在后台管理、资源分配及用户体验方面的策略差异,揭示它们如何平衡性能与电池寿命,为用户带来流畅而高效的操作体验。通过对比分析,我们不仅能够更好地理解各自系统的工作机制,还能为开发者优化应用提供参考。
|
2月前
|
算法 Linux 调度
深入探索安卓系统的多任务处理机制
【10月更文挑战第21天】 本文旨在为读者提供一个关于Android系统多任务处理机制的全面解析。我们将从Android操作系统的核心架构出发,探讨其如何管理多个应用程序的同时运行,包括进程调度、内存管理和电量优化等方面。通过深入分析,本文揭示了Android在处理多任务时所面临的挑战以及它如何通过创新的解决方案来提高用户体验和设备性能。
75 1
|
3月前
|
Android开发
Android gradle task任务检查各个module之间资源文件冲突.md
Android gradle task任务检查各个module之间资源文件冲突.md
Android gradle task任务检查各个module之间资源文件冲突.md

热门文章

最新文章