2025-02-09

Android中的桌面快捷方式和PC機上的快捷方式一樣,用於啟動某一應用程序。要在桌面添加一個快捷方式非常簡單,隻需長按桌面或者點擊"Menu"按鈕,然後在彈出的選項中選擇shortcut,然後選擇要添加的快捷方式即可。
下面主要介紹如何通過代碼將一個應用程序添加到桌面快捷方式。
首先在描述文件AndroidManifest.xml中註冊一個action為:<action android:name="android.intent.action.CREATE_SHORTCUT"/>
如下所示:
[java]
<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
      package="com.test.shortcut" 
      android:versionCode="1" 
      android:versionName="1.0"> 
 
 
    <application android:icon="@drawable/icon" android:label="@string/app_name"> 
        <activity android:name=".MainActivity" 
                  android:label="@string/app_name"> 
            <intent-filter> 
                <action android:name="android.intent.action.MAIN" /> 
                <category android:name="android.intent.category.LAUNCHER" /> 
                <action android:name="android.intent.action.CREATE_SHORTCUT"/> 
            </intent-filter> 
        </activity> 
    </application> 
</manifest> 

接下來是MainActivity:
[java]
public class MainActivity extends Activity { 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.main); 
         
        Intent intent; 
        //判斷是否要添加快捷方式 
        if (this.getIntent().getAction().equals(Intent.ACTION_CREATE_SHORTCUT)){ 
            intent = new Intent(); 
            //設置快捷方式名稱 
            intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "撥打電話"); 
             
            //設置快捷方式圖標 
            Parcelable icon = Intent.ShortcutIconResource.fromContext(this, android.R.drawable.stat_sys_phone_call); 
            intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon); 
             
            //設置快捷方式執行的intent 
            Uri uri = Uri.parse("tel:055555");   
            Intent it = new Intent(Intent.ACTION_DIAL, uri);   
            intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, it); 
             
            setResult(RESULT_OK,intent); 
        }else { 
            //取消 
            setResult(RESULT_CANCELED);; 
        } 
        this.finish(); 
    } 

 代碼非常簡單,運行程序,長按桌面,選擇shortcut後如圖所示:

選擇將ShortCut添加到桌面,效果如圖:

單擊“撥打電話”圖標,出現如圖所示結果:

 

摘自 fwwdn的專欄

發佈留言

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