Android之產生案頭捷徑(一)
產生捷徑有兩種情況,一種是直接在案頭直接產生;一種是長按案頭,在彈出的捷徑功能表中產生。
談談在案頭上直接產生。個人覺得這個比較爽快,既然都是捷徑了幹嘛還要再隱藏一層呢?當然喜歡案頭乾淨的就比較喜歡第二個了。
第一個是通過廣播(Broadcast)的形式向Luncher發送請求產生捷徑的。
在網上找到關於這方面的註冊資訊。
InstallShortcutReceiver的註冊資訊:
<!--設定wallpapaer的activity --> <!-- Intent received used to install shortcuts from other applications --> <receiver android:name="com.android.launcher2.InstallShortcutReceiver" android:permission="com.android.launcher.permission.INSTALL_SHORTCUT"> <intent-filter> <action android:name="com.android.launcher.action.INSTALL_SHORTCUT" /> </intent-filter> </receiver>
可以看出,要在案頭上建立捷徑就需要許可權了:
android:permission="com.android.launcher.permission.INSTALL_SHORTCUT。
所以在我們的manifest.xml檔案中,我們需要加入下面這段話:
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT"/>
下面就是代碼層的實現:
假如我在一個activity中建立一個建立捷徑的方法:createShortCut();
public void createShortCut(){//建立捷徑的Intent 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(getApplicationContext() , EnterActivity.class)); //發送廣播。OK sendBroadcast(shortcutintent);}
Android之產生案頭捷徑(二)
之前有談過直接在案頭產生捷徑,現在說說如何在添加到一個SHORTCUTS列表中,就是你長按案頭彈出來的那個東東。
首先在註冊activity時,需要添加一個action為android.intent.action.CREATE_SHOERTCUT的intentFilter.如下所示:
<activity android:name="ShortCutTest"> <intent-filter> <action android:name="android.intent.action.CREATE_SHORTCUT"/> </intent-filter> </activity>
接下來就是就是設定捷徑的表徵圖、名稱、事件等屬性。這裡圖表的產生,android裡提供了專門的方法來產生。
public class ShortCutTest extends Activity{ @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); } public void createShortCut(){ Intent addShortCut; //判斷是否需要添加捷徑 if(getIntent().getAction().equals(Intent.ACTION_CREATE_SHORTCUT)){ addShortCut = new Intent(); //捷徑的名稱 addShortCut.putExtra(Intent.EXTRA_SHORTCUT_NAME , "我的捷徑"); //顯示的圖片 Parcelable icon = ShortcutIconResource.fromContext(this, R.drawable.icon); addShortCut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon); //捷徑啟用的activity,需要執行的intent,自己定義 addShortCut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent()); //OK,產生 setResult(RESULT_OK, addShortCut); }else{ //取消 setResult(RESULT_CANCELED); } }}
ok.