2025-05-23

和IOS開發和Windows Phone開發相比,Android是開放的,Android上的開發也相對更加靈活,能夠做很多事情。有的朋友會發現,在某些Android應用安裝以後,第一次運行,就會在桌面創建快捷方式。這是如何做到的呢?
要不怎麼說Android特別開放呢,在Android開發中,隻要發送一個廣播,就可以實現這種需求瞭。
廢話不多說,以下是封裝好的一段代碼。
public class ShortcutUtil { 
 
    public static void createShortCut(Activity act, int iconResId, 
            int appnameResId) { 
 
        // com.android.launcher.permission.INSTALL_SHORTCUT 
 
        Intent shortcutintent = new Intent( 
                "com.android.launcher.action.INSTALL_SHORTCUT"); 
        // 不允許重復創建 
        shortcutintent.putExtra("duplicate", false); 
        // 需要現實的名稱 
        shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_NAME, 
                act.getString(appnameResId)); 
        // 快捷圖片 
        Parcelable icon = Intent.ShortcutIconResource.fromContext( 
                act.getApplicationContext(), iconResId); 
        shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon); 
        // 點擊快捷圖片,運行的程序主入口 
        shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, 
                new Intent(act.getApplicationContext(), act.getClass())); 
        // 發送廣播 
        act.sendBroadcast(shortcutintent); 
    } 

 
代碼比較簡單,不做更詳細的解釋。
 
別忘記增加以下權限,否則看不到任何效果。
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT"/>
 
另外,這樣做可能並不友好。更好的做法是,第一次運行程序的時候,提示用戶是否創建桌面快捷方式,讓用戶選擇。以後再次運行就不再進行提示瞭。
 
—————————————————————————
GL(arui319)
http://blog.csdn.net/arui319
 

摘自   執著的程序員 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *