2013-06-01 80 views
18

當我開發Android應用程序時出現此問題。我想分享我在開發過程中收集的知識。如何在Android中以編程方式添加快捷方式到主屏幕

+0

到標記爲重複MODS的:請注意,您在重複的答案不能完全解決問題。因此,OP建議[請提出一個新問題](http://stackoverflow.com/questions/ask)。您會看到他的自我答案包含與複製件上接受的答案非常不同的信息。請考慮重新開放。 –

+0

這似乎是一種獲得聲譽的簡單方法,因爲他幾乎不用提供信用就可以複製較舊的文章:http://viralpatel.net/blogs/android-install-uninstall-shortcu t-example/ – igorsantos07

回答

62

的Android爲我們提供了一個意圖類com.android.launcher.action.INSTALL_SHORTCUT可用於快捷方式添加到主屏幕。在下面的代碼片段中,我們創建了名爲HelloWorldShortcut的活動MainActivity的快捷方式。

首先,我們需要將權限INSTALL_SHORTCUT添加到android清單xml中。

<uses-permission 
     android:name="com.android.launcher.permission.INSTALL_SHORTCUT" /> 

addShortcut()方法在主屏幕上創建一個新的快捷方式。

private void addShortcut() { 
    //Adding shortcut for MainActivity 
    //on Home screen 
    Intent shortcutIntent = new Intent(getApplicationContext(), 
      MainActivity.class); 

    shortcutIntent.setAction(Intent.ACTION_MAIN); 

    Intent addIntent = new Intent(); 
    addIntent 
      .putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); 
    addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "HelloWorldShortcut"); 
    addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, 
      Intent.ShortcutIconResource.fromContext(getApplicationContext(), 
        R.drawable.ic_launcher)); 

    addIntent 
      .setAction("com.android.launcher.action.INSTALL_SHORTCUT"); 
    addIntent.putExtra("duplicate", false); //may it's already there so don't duplicate 
    getApplicationContext().sendBroadcast(addIntent); 
} 

注意我們如何創建shortcutIntent對象來保存我們的目標活動。這個意圖對象作爲EXTRA_SHORTCUT_INTENT被添加到另一個意圖中。

最後我們播出了新的意圖。這增加了一個名爲 EXTRA_SHORTCUT_NAME的名稱和由EXTRA_SHORTCUT_ICON_RESOURCE定義的圖標。

乾杯! Chanaka

而且把這個代碼,以避免多個快捷鍵:

if(!getSharedPreferences(Utils.APP_PREFERENCE, Activity.MODE_PRIVATE).getBoolean(Utils.IS_ICON_CREATED, false)){ 
      addShortcut(); 
      getSharedPreferences(Utils.APP_PREFERENCE, Activity.MODE_PRIVATE).edit().putBoolean(Utils.IS_ICON_CREATED, true); 
     } 
+0

關於無證功能 –

+4

不要爲我工作 – David

+2

我認爲現在Play商店會自動爲用戶做這件事。 (可以在設置中進行更改),這樣只會在桌面上顯示2個圖標。 –

相關問題