Android 桌面的捷徑和 PC 上的捷徑概念相同,都是為了快速啟動某個應用程式。手動建立很簡單:長按桌面或點 Menu,選擇 shortcut,再挑選要新增的項目即可。本文示範如何用程式碼讓使用者從你的 App 中直接建立捷徑。
關鍵是加入 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>
程式在 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_SHORTCUT_NAME(名稱)、EXTRA_SHORTCUT_ICON_RESOURCE(圖示)、EXTRA_SHORTCUT_INTENT(點擊後的行為)。少一個就會建立失敗。finish();若想更乾淨,可以改用 Theme.NoDisplay 主題。Intent.ACTION_DELETE_SHORTCUT 的廣播。