Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

用程式碼在 Android 桌面建立應用程式捷徑

Android 桌面的捷徑和 PC 上的捷徑概念相同,都是為了快速啟動某個應用程式。手動建立很簡單:長按桌面或點 Menu,選擇 shortcut,再挑選要新增的項目即可。本文示範如何用程式碼讓使用者從你的 App 中直接建立捷徑。

步驟一:在 AndroidManifest.xml 註冊 action

關鍵是加入 android.intent.action.CREATE_SHORTCUT 這個 action:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.test.shortcut"
    android:versionCode="1"
    android:versionName="1.0">

    <application android:icon="@drawable/icon"
                 android:label="@string/app_name">
        <activity android:name=".MainActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
                <action android:name="android.intent.action.CREATE_SHORTCUT" />
            </intent-filter>
        </activity>
    </application>
</manifest>

步驟二:在 Activity 中組出捷徑內容

程式在 onCreate 中判斷是哪一種 action:如果是建立捷徑,就把名稱、圖示與要執行的 Intent 塞進結果 Intent 並 setResult(RESULT_OK, ...);否則回傳 RESULT_CANCELED。

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Intent intent;
        // 判斷是否要建立捷徑
        if (this.getIntent().getAction().equals(Intent.ACTION_CREATE_SHORTCUT)) {
            intent = new Intent();

            // 捷徑名稱
            intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "撥打電話");

            // 捷徑圖示
            Parcelable icon = Intent.ShortcutIconResource.fromContext(
                    this, android.R.drawable.stat_sys_phone_call);
            intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);

            // 捷徑被點擊時要執行的 Intent
            Uri uri = Uri.parse("tel:055555");
            Intent it = new Intent(Intent.ACTION_DIAL, uri);
            intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, it);

            setResult(RESULT_OK, intent);
        } else {
            // 取消
            setResult(RESULT_CANCELED);
        }
        this.finish();
    }
}

程式碼相當短。執行後長按桌面選擇 shortcut,清單中就會出現你的 App;選它並確認,桌面上便會產生名為「撥打電話」的圖示,點一下即會開啟撥號程式並帶入號碼。

幾個實務提醒

  • 三個 extra 缺一不可:EXTRA_SHORTCUT_NAME(名稱)、EXTRA_SHORTCUT_ICON_RESOURCE(圖示)、EXTRA_SHORTCUT_INTENT(點擊後的行為)。少一個就會建立失敗。
  • 不同桌面啟動器(Launcher)對捷徑的支援程度不一,部分客製 ROM 會限制或需要額外權限,實機測試是必要的。
  • 這個 Activity 通常不需要顯示 UI,因此設定完就 finish();若想更乾淨,可以改用 Theme.NoDisplay 主題。
  • 若想反過來「移除捷徑」,可發送 Intent.ACTION_DELETE_SHORTCUT 的廣播。
Copyright © Linux教程網 All Rights Reserved