2013-11-14 27 views
0

假設,我有一些可以幫助用戶安裝其他應用的Android應用。有什麼方法可以在主屏幕上創建這個應用程序的快捷方式嗎?我也可以指定這些快捷方式的位置嗎?如何以編程方式在Android中創建另一個應用的快捷方式?

+0

我不明白;你是什​​麼意思快捷鍵?所以你想爲已安裝的應用程序創建應用程序圖標/小部件? – LotusUNSW

+0

@LotusUNSW是的,我想爲已安裝的應用程序創建應用程序圖標 –

回答

1

試試這個:

public void createShortCut{ 
    Intent shortcutintent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT"); 
    shortcutintent.putExtra("duplicate", false); 
    shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.shortcutname)); 
    Parcelable icon = Intent.ShortcutIconResource.fromContext(getApplicationContext, R.drawable.icon); 
    shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon); 
    shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent("com.whatsapp")); 
    sendBroadcast(shortcutintent); 
} 
+0

thanx代碼,但是有沒有辦法在創建一個新的之前檢查是否已經存在類似的捷徑? –

+0

嘗試用shortcutintent.putExtra(「duplicate」,false); – Piero

+0

如何使用此代碼創建URL快捷方式? –

-1

Android上沒有這樣的API。

+1

我應該評論而不是回答。 – duggu

0

一種方法是創建一個小部件。但是,用戶必須再次將小部件放置在主屏幕上才能使用。

0
A bit improved version: we are checking if the shortcut has been already created 
and must not be created if user remove it from the screen 

final static private String PREF_KEY_SHORTCUT_ADDED = "PREF_KEY_SHORTCUT_ADDED"; 

@Override 
    public void onStart(){ 
     super.onStart(); 

// Checking if ShortCut was already added 
     sharedPreferences = getPreferences(MODE_PRIVATE); 
     boolean shortCutWasAlreadyAdded = sharedPreferences.getBoolean(PREF_KEY_SHORTCUT_ADDED, false); 
     if (!shortCutWasAlreadyAdded) createShortcutIcon(); 


    }// end onStart 


    // Creates shortcut on Android widget screen 
    private void createShortcutIcon(){ 

     Intent shortcutIntent = new Intent(getApplicationContext(), Splash.class); 
     shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
     shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 

     Intent addIntent = new Intent(); 
     addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); 
     addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name)); 

     addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE 
       , Intent.ShortcutIconResource.fromContext(getApplicationContext() 
         , R.drawable.ic_launcher)); 

     addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT"); 
     getApplicationContext().sendBroadcast(addIntent); 

     // Remembering that ShortCut was already added 
     SharedPreferences.Editor editor = sharedPreferences.edit(); 
     editor.putBoolean(PREF_KEY_SHORTCUT_ADDED, true); 
     editor.commit(); 

     objPublicDelegate.showToast(getString(R.string.app_name)+ " shortcut created on screen."); 

    }// end createShortcutIcon 
+0

謝謝。 shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);如果沒有這兩行代碼,有時應用程序崩潰,說「TransactionTooLargeException」。爲了避免這種例外,它必須添加這些行。 –

相關問題