2015-06-14 82 views
4

我想給我的用戶一個選項,以創建應用程序內特定頁面的快捷方式。 我在Whatsapp上看到類似的用法,當你長時間按下聊天,並且你能夠創建一個桌面快捷方式到這個特定的聊天。在主屏幕上創建特定活動的快捷方式

我試過找到一些關於這個functionality的文檔,但無法讓它工作。 這是我有:

活動這不是發射活動(包括意向過濾器)

<activity android:name="com.my.example.pages.Topics" 
    android:parentActivityName="com.my.example.pages.Apps"> 
     <intent-filter> 
      <action android:name="android.intent.action.CREATE_SHORTCUT"/> 
      <category android:name="android.intent.category.DEFAULT"/> 
     </intent-filter> 
    </activity> 

createShortcut功能

public void createShortcut(){ 
     Intent shortcutIntent = new Intent("com.my.example.pages.Topics"); 
     Intent.ShortcutIconResource iconResource = Intent.ShortcutIconResource.fromContext(getActivity(), R.drawable.app_logo); 

     // The result we are passing back from this activity 
     Intent intent = new Intent(); 
     intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); 
     intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "Shortcut Test"); 
     intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource); 
     getActivity().setResult(getActivity().RESULT_OK, intent); 
     getActivity().finish(); 

     Toast.makeText(getActivity(),"Shortcut created",Toast.LENGTH_SHORT).show(); 
    } 

清單

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

我可能因爲調用函數後得到Toasts,但沒有創建快捷方式,並且由於finish()方法而退出應用程序。

爲了更清晰 - 如何爲非啓動器活動創建快捷方式?

*我在其中一個viewpager片段中運行代碼。

+0

相關:http://stackoverflow.com/questions/6988511/how-to-add-apps-shortcut-to-the-home-screen – cygery

+0

與所有的答覆,WhatsApp應用程序非常敬重好,順利。作爲用戶,我覺得這個選項是非常有用的,甚至是必要的 – Juvi

+0

似乎這是行得通的,「主題」必須是啓動器活動 –

回答

4

使用此命令爲非啓動器活動創建快捷方式。

private void createShortcutOfApp() { 

     Intent shortcutIntent = new Intent(getApplicationContext(), 
      YourTargetActivity.class); 
     shortcutIntent.setAction(Intent.ACTION_MAIN); 

     Intent addIntent = new Intent(); 
     addIntent 
      .putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); 
     addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "App shortcut name"); 
     addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, 
     Intent.ShortcutIconResource.fromContext(getApplicationContext(), 
     R.mipmap.logo_of_your_app_shortcut)); 

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

不添加權限在menifest

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

現在定義

android:exported=」true」 

屬性在

<activity> tag 

<activity 
    android:name=".YourTargetActivity" 
    android:exported="true"></activity> 

這個工程就像whatsapp app chat shorcut。

+0

@juvi請檢查以上答案 –

相關問題