Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 系統層面實用技巧整理:快捷方式、寄信與指定瀏覽器

編輯:關於 Android 程式設計

開發過程中難免會碰到一些「不是核心功能,但客戶一定要」的需求,例如幫 App 建立桌面捷徑、一鍵寄信給客服、強制用 Chrome 開啟網頁。這些功能都不難,但 API 細節零散,寫過一次之後往往又要翻半天文件。這篇把它們整理在一起,當成速查表使用。

一、建立與移除桌面捷徑

Android 的桌面捷徑本質上是一則廣播。App 只要送出帶有指定 action 的 Intent,並把名稱、圖示、啟動目標塞進 extras,Launcher 就會代為建立圖示。

private void addShortcut() {
    Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");

    // 捷徑名稱
    shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name));
    // 不允許重複建立
    shortcut.putExtra("duplicate", false);

    // 指定點擊捷徑後要啟動的 Activity
    ComponentName comp = new ComponentName(this.getPackageName(), getClass().getName());
    shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT,
            new Intent(Intent.ACTION_MAIN).setComponent(comp));

    // 捷徑圖示
    ShortcutIconResource iconRes = Intent.ShortcutIconResource.fromContext(this, R.drawable.icon);
    shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes);

    sendBroadcast(shortcut);
}

/**
 * 移除本程式的桌面捷徑
 */
private void deleteShortcuts() {
    Intent shortcut = new Intent("com.android.launcher.action.UNINSTALL_SHORTCUT");

    shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name));

    ComponentName comp = new ComponentName(this.getPackageName(), getClass().getName());
    shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT,
            new Intent(Intent.ACTION_MAIN).setComponent(comp));

    sendBroadcast(shortcut);
}

兩個方法的差別只在 action 字串,其餘參數結構完全一致。要注意的是,部分客製化 Launcher 對這類廣播的支援程度不一,正式上線前最好在幾個主流桌面上實測。

二、調起系統寄信流程

自己實作郵件客戶端是件吃力不討好的事,比較務實的做法是發送 ACTION_SEND Intent,把收件者、標題、內文甚至附件交給系統處理,讓使用者自行挑選偏好的郵件 App。

public boolean sendEmail(String to[], String subject, String body,
                         String attachementFilePath) {
    final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
    emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, to);
    emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
    emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, body);

    if (attachementFilePath != null) {
        Uri attachmentUri = null;
        try {
            File file = new File(attachementFilePath);
            if (file == null) {
                Log.d("[RC] Mail", "File error: " + attachementFilePath);
            } else if (!file.exists()) {
                Log.d("[RC] Mail", "File does not exist: " + attachementFilePath);
            } else if (!file.canRead()) {
                Log.d("[RC] Mail", "File can't be read: " + attachementFilePath);
            } else if (!file.isFile()) {
                Log.d("[RC] Mail", "Invalid file: " + attachementFilePath);
            } else {
                attachmentUri = Uri.fromFile(file);
                Log.d("[RC] Mail", "Attachement path[size=" + file.length() + "]: " + attachementFilePath);
                Log.d("[RC] Mail", "Attachement URI: " + attachmentUri.toString());
            }
        } catch (java.lang.Throwable ex) {
            Log.e("[RC] Mail", "Error: " + ex.toString());
        }
        if (attachmentUri != null) {
            emailIntent.putExtra(Intent.EXTRA_STREAM, attachmentUri);
        }
    }

    emailIntent.setType("text/plain");

    // 先確認有沒有可處理的 App,避免直接 START 時 ANR 或崩潰
    List<ResolveInfo> availableSoft = (List<ResolveInfo>) mContext
            .getPackageManager().queryIntentActivities(emailIntent, PackageManager.MATCH_DEFAULT_ONLY);
    if (availableSoft.size() <= 0) {
        return false;
    }

    mContext.startActivity(Intent.createChooser(emailIntent,
            mContext.getResources().getString(R.string.menu_sendEmail)));
    return true;
}

這裡有兩個值得學的習慣。第一,附加檔案之前逐項檢查存在性、可讀性與型別,並把失敗原因寫進 Log,日後排查問題會輕鬆很多。第二,啟動之前先用 queryIntentActivities 確認有沒有 App 能承接這個 Intent,這能有效避免 ActivityNotFoundException。

三、優先以 Chrome 開啟網頁

WebView 之外,很多時候我們希望把外部連結交給真正的瀏覽器。若想確保用的是 Chrome(例如需要它對 HTML5 的支援),可以在啟動前遍歷候選 App,挑出套件名為 com.android.chrome 的那一個。

// 用法:new Intent(Intent.ACTION_VIEW, uri)
public void startActiviyByChromeIfExists(Context context, Intent intent) {
    try {
        Log.d("startActiviyByChromeIfExists", "Intent Scheme: " + intent.getScheme());
    } catch (Exception e) {
        // 忽略取 scheme 失敗的情況
    }

    if (context != null && intent != null) {
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        List<ResolveInfo> availableSoft = (List<ResolveInfo>) context
                .getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);

        for (ResolveInfo info : availableSoft) {
            if ("com.android.chrome".equals(info.activityInfo.packageName)) {
                intent.setComponent(new ComponentName(
                        info.activityInfo.packageName, info.activityInfo.name));
                context.startActivity(intent);
                return;
            }
        }

        if (availableSoft.size() == 0) {
            try {
                Toast.makeText(mContext, R.string.setting_no_browser_installed,
                        Toast.LENGTH_LONG).show();
            } catch (Exception e) {
                Log.e("startActiviyByChromeIfExists", e.getMessage());
            }
        } else {
            // 沒有 Chrome,就交給系統預設處理
            context.startActivity(intent);
        }
    }
}

這個寫法的彈性很好:有 Chrome 就用 Chrome,沒有就退回系統預設,一句提示文案告知使用者沒裝瀏覽器,整條路徑都不會中斷。

小結

這三段程式背後其實是同一套思路——把.Intent 當成系統能力的呼叫介面。無論是建捷徑、寄信還是開網頁,App 都只是提出請求,真正做事的是系統或其他 App。理解這層關係之後,共用、撥號、開啟地圖導航、分享圖片這些需求,都能用同樣的模式快速搞定。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved