一 Activity的啟動入口(基于安卓8.0)

1.1 從Launcher啟動
首先我們通過git命令獲取到Launcher的最新源碼
git clone -b master https://android.googlesource.com/platform/packages/apps/Launcher3

1.1.1進(jìn)入到Launcher.java 找到

public void onClick(View v) {
      .....
     .......
        Object tag = v.getTag();
        if (tag instanceof ShortcutInfo) {
          //點(diǎn)擊應(yīng)用圖標(biāo)
            onClickAppShortcut(v);
        } else if (tag instanceof FolderInfo) {
            if (v instanceof FolderIcon) {
                onClickFolderIcon(v);
            }
        } 
      ...
      ...
}

1.1.2 進(jìn)入OnClickAppShortcut(v)

/**
 * Event handler for an app shortcut click.
 *
 * @param v The view that was clicked. Must be a tagged with a {@link ShortcutInfo}.
 */
protected void onClickAppShortcut(final View v) {
    if (LOGD) Log.d(TAG, "onClickAppShortcut");
    Object tag = v.getTag();
    if (!(tag instanceof ShortcutInfo)) {
        throw new IllegalArgumentException("Input must be a Shortcut");
    }

    // Open shortcut
    final ShortcutInfo shortcut = (ShortcutInfo) tag;

    if (shortcut.isDisabled != 0) {
        if ((shortcut.isDisabled &
                ~ShortcutInfo.FLAG_DISABLED_SUSPENDED &
                ~ShortcutInfo.FLAG_DISABLED_QUIET_USER) == 0) {
            // If the app is only disabled because of the above flags, launch activity anyway.
            // Framework will tell the user why the app is suspended.
        } else {
            if (!TextUtils.isEmpty(shortcut.disabledMessage)) {
                // Use a message specific to this shortcut, if it has one.
                Toast.makeText(this, shortcut.disabledMessage, Toast.LENGTH_SHORT).show();
                return;
            }
            // Otherwise just use a generic error message.
            int error = R.string.activity_not_available;
            if ((shortcut.isDisabled & ShortcutInfo.FLAG_DISABLED_SAFEMODE) != 0) {
                error = R.string.safemode_shortcut_error;
            } else if ((shortcut.isDisabled & ShortcutInfo.FLAG_DISABLED_BY_PUBLISHER) != 0 ||
                    (shortcut.isDisabled & ShortcutInfo.FLAG_DISABLED_LOCKED_USER) != 0) {
                error = R.string.shortcut_not_available;
            }
            Toast.makeText(this, error, Toast.LENGTH_SHORT).show();
            return;
        }
    }

    // Check for abandoned promise
    if ((v instanceof BubbleTextView) && shortcut.hasPromiseIconUi()) {
        String packageName = shortcut.intent.getComponent() != null ?
                shortcut.intent.getComponent().getPackageName() : shortcut.intent.getPackage();
        if (!TextUtils.isEmpty(packageName)) {
            onClickPendingAppItem(v, packageName,
                    shortcut.hasStatusFlag(ShortcutInfo.FLAG_INSTALL_SESSION_ACTIVE));
            return;
        }
    }

    // Start activities
    startAppShortcutOrInfoActivity(v);
}

1.1.3進(jìn)入 startAppShortcutOrInfoActivity()

private void startAppShortcutOrInfoActivity(View v) {
    ItemInfo item = (ItemInfo) v.getTag();
    Intent intent;
    if (item instanceof PromiseAppInfo) {
        PromiseAppInfo promiseAppInfo = (PromiseAppInfo) item;
        intent = promiseAppInfo.getMarketIntent();
    } else {
        intent = item.getIntent();
    }
    if (intent == null) {
        throw new IllegalArgumentException("Input must have a valid intent");
    }
    boolean success = startActivitySafely(v, intent, item);
    getUserEventDispatcher().logAppLaunch(v, intent); // TODO for discovered apps b/35802115

    if (success && v instanceof BubbleTextView) {
        mWaitingForResume = (BubbleTextView) v;
        mWaitingForResume.setStayPressed(true);
    }
}

1.1.4 進(jìn)入startActivitySafely

    public boolean startActivitySafely(View v, Intent intent, ItemInfo item) {
        if (mIsSafeModeEnabled && !Utilities.isSystemApp(this, intent)) {
            Toast.makeText(this, R.string.safemode_shortcut_error, Toast.LENGTH_SHORT).show();
            return false;
        }
        // Only launch using the new animation if the shortcut has not opted out (this is a
        // private contract between launcher and may be ignored in the future).
        boolean useLaunchAnimation = (v != null) &&
                !intent.hasExtra(INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION);
        Bundle optsBundle = useLaunchAnimation ? getActivityLaunchOptions(v) : null;

        UserHandle user = item == null ? null : item.user;

        // Prepare intent
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (v != null) {
            intent.setSourceBounds(getViewBounds(v));
        }
        try {
            if (Utilities.ATLEAST_MARSHMALLOW
                    && (item instanceof ShortcutInfo)
                    && (item.itemType == Favorites.ITEM_TYPE_SHORTCUT
                     || item.itemType == Favorites.ITEM_TYPE_DEEP_SHORTCUT)
                    && !((ShortcutInfo) item).isPromise()) { //注釋1
                // Shortcuts need some special checks due to legacy reasons.
                startShortcutIntentSafely(intent, optsBundle, item);
            } else if (user == null || user.equals(Process.myUserHandle())) {//注釋2
                // Could be launching some bookkeeping activity
                startActivity(intent, optsBundle);
            } else { //注釋3
                LauncherAppsCompat.getInstance(this).startActivityForProfile(
                        intent.getComponent(), user, intent.getSourceBounds(), optsBundle);
            }
            return true;
        } catch (ActivityNotFoundException|SecurityException e) {
            Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
            Log.e(TAG, "Unable to launch. tag=" + item + " intent=" + intent, e);
        }
        return false;
    }

分析
方法中有三個(gè)if else的判斷
注釋1
6.0以上的系統(tǒng),快捷方式啟動,需要做一些校驗(yàn)。所謂的快捷方式,是google提供的新特性,用于啟動應(yīng)用內(nèi)的快捷操作,譬如是 發(fā)信息給某一個(gè)用戶。
注釋2
如果user為空 或就是launcher所在用戶
startActivity() //啟動Activity的地方
注釋3 (哪種情況會走這里的邏輯,待確認(rèn))

1.2 APP內(nèi)部啟動
1.2.1 顯式啟動
直接指定我們要啟動的class名字

    private void ExplicitStartActivity(){

        Intent intent = new Intent(this,ExplicitIntentActivity.class);
        startActivity(intent);

    }

1.2.2 隱式啟動
設(shè)定intent的action,讓系統(tǒng)去匹配查找

    private void ImplicitStartActivity(){

        Intent intent = new Intent("com.shine.activitystudy.ImplicitIntentActivity");

        startActivity(intent);

    }

1.3 從startActivity開始

可以看到 無論是從launcher啟動還是app內(nèi)部啟動,最后都會調(diào)用到Activity.java的startActivity()方法。

1.3.1 startActivity分析

    public void startActivity(Intent intent, @Nullable Bundle options) {
        if (options != null) {
            startActivityForResult(intent, -1, options);
        } else {
            // Note we want to go through this call for compatibility with
            // applications that may have overridden the method.
            startActivityForResult(intent, -1); //注釋1
        }
    }

以options是否為null來調(diào)用startActivityForResult()
來看注釋1的實(shí)現(xiàn)

    public void startActivityForResult(@RequiresPermission Intent intent, int requestCode) {
        startActivityForResult(intent, requestCode, null);
    }

也是調(diào)用到了這個(gè)方法。

 public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
            @Nullable Bundle options) 

下一節(jié),我們就以

public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
  @Nullable Bundle options) 

作為開始來進(jìn)一步分析Activity是如何啟動的。

參考文章
http://www.lovemingnuo.com/2018/03/16/App的啟動流程(Android8.0)%20第一篇/
http://www.voidcn.com/article/p-krltxsbq-qh.html

快捷方式啟動 參考
https://blog.csdn.net/qibin0506/article/details/52878690

android 8.0創(chuàng)建快捷方式
https://blog.csdn.net/rentee/article/details/77005547

google官方Intent介紹
https://developer.android.com/guide/components/intents-filters?hl=zh-cn

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容