天天看點

建立桌面快捷方式

添加桌面快捷方式,非常簡單,隻需三步:

1、建立一個添加快捷方式的Intent,該Intent的Action為com.android.launcher.action.INSTALL_SHORTCUT。

2、通過為該Intent添加Extra屬性來設定快捷方式的标題、圖示及快捷方式對應啟動的程式。

3、調用sendBroadcast()方法發送廣播即可添加快捷方式。

下面用一個簡單示例來示範,在該應用程式中,隻給出了添加桌面快捷方式的内容,程式的具體應用無須給出,第一次安裝該程式後,會在桌面建立快捷方式,以後不會再建立快捷方式。代碼如下:

Activity:

package com.home.activity;

import com.example.testshortcut.R;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Parcelable;
import android.widget.Toast;

public class TestShortcutActivity extends Activity {
	private SharedPreferences sp;
	private Editor editor;
	private int count = 1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		// 擷取SharedPreferences對象
		sp = this.getSharedPreferences("testshortcut", MODE_PRIVATE);
		// 得到Editor對象
		editor = sp.edit();
		// 讀取SharedPreferences對象中鍵為count的值
		int readCount = sp.getInt("count", 0);
		if (readCount > 0) {
			Toast.makeText(this, "快捷方式已存在,不必再建立", Toast.LENGTH_LONG).show();
			return;
		}
		// 建立添加快捷方式的Intent
		Intent addIntent = new Intent(
				"com.android.launcher.action.INSTALL_SHORTCUT");
		// 快捷方式的标題
		String title = "我的應用";
		// 加載快捷方式圖示
		Parcelable icon = Intent.ShortcutIconResource.fromContext(this,
				R.drawable.ic_launcher);
		// 建立點選快捷方式後再次啟動的程式,這裡啟動自己
		Intent myIntent = new Intent(this, TestShortcutActivity.class);
		// 設定快捷方式的标題
		addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, title);
		// 設定快捷方式的圖示
		addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
		// 設定快捷方式對應的Intent
		addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, myIntent);
		// 發送廣播添加快捷方式
		sendBroadcast(addIntent);
		// 把計數寫入檔案
		editor.putInt("count", count);
		// 送出修改
		editor.commit();
	}

}
      

權限:

<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT"/>      
<activity
            android:name="com.home.activity.TestShortcutActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <!-- 定義添加到桌面Launcher中 -->
            <intent-filter>
                <action android:name="android.intent.action.CREATE_SHORTCUT" />
            </intent-filter>
        </activity>