| 要求權限 |
|---|
| Manifest(AndroidManifest.xml) 裡加上權限要求 |
| <uses-permission android:name= "com.android.launcher.permission.INSTALL_SHORTCUT" /> |
| import 會用到的物件類別 |
|---|
| import android.content.Intent; import android.content.pm.ShortcutInfo; import android.content.pm.ShortcutManager; import android.app.PendingIntent; |
| 程式內容 |
|---|
|
//可以當成參數傳入的設定 String id = "testID"; String labelShort = "testA";//直接出現在桌面時使用的標題名稱 int iconID = R.mipmap.ic_heart; Class targetClass = ActText.class; //設定要攜帶的參數 String paraTitle = "FILENAME"; String paraVal = _fileLog; |
|
//定義要開啟的 Activity Intent intentTask = new Intent(this, targetClass) .setAction(Intent.ACTION_VIEW); //攜帶參數 intentTask.putExtra(paraTitle, paraVal); task 說明 |
|
//如果裝置版本較舊, 可以執行舊版SDK if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.O) { android.content.Intent intent = new android.content.Intent(); intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT"); intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, labelShort); intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intentTask); intent.putExtra(Intent.EXTRA_SHORTCUT_ICON, android.graphics.drawable.Icon.createWithResource(this, iconID)); this.sendBroadcast(intent); return; } 版本問題應對 |
|
//建立捷徑的外觀 ShortcutInfo pinShortcutInfo = new ShortcutInfo.Builder(this, id) .setShortLabel(labelShort) .setIcon(android.graphics.drawable.Icon.createWithResource(this, iconID)) .setIntent(intentTask) .build(); |
|
//建立捷徑 ShortcutManager shortcutManager = this.getSystemService(ShortcutManager.class); Intent pinnedShortcutCallbackIntent = shortcutManager.createShortcutResultIntent(pinShortcutInfo); PendingIntent successCallback = PendingIntent.getBroadcast(this, 0, pinnedShortcutCallbackIntent, 0); shortcutManager.requestPinShortcut(pinShortcutInfo, successCallback.getIntentSender()); |
| 確保 目標 Activity 能直接被啟動 |
|---|
| activity 宣告要有這一段 |
|
<intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> |
| Activity 開啟後接收參數 |
|---|
| import android.os.Bundle; |
| Bundle bundle = this.getIntent().getExtras(); if (bundle != null) { _id = (String) bundle.get(PARA_ID); _filename = (String) bundle.get(PARA_FILE); } |
Intent-Task
意義在於桌面捷徑被點選後觸發的事件內容
定義要啟動的 activity
以及要帶進的參數
| 設定 Task 基本內容 |
|---|
|
Intent task = new Intent(this, [類別名稱].class) .setAction(Intent.ACTION_VIEW); |
| 必須要 setAction 為 ACTION_VIEW |
| 為 task 加上參數 |
|---|
| task.putExtra( [參數名稱] , [參數內容] ); |
|
設定參數名稱 必須要與接收的 Activity 端對應 |
| 啟免參數對應錯誤 |
|---|
| 可以將參數名稱寫成 final 字串共用 |
| 設定常數: public static final String PARA_FILE= "FILENAME"; |
|
task 設定參數內容: task.putExtra(PARA_FILE ,filename); |
|
Activity 接收參數內容: _filename = (String) bundle.get(PARA_FILE); |