有人會說,快捷方式,不是安裝完應用程式後,長按應用程式的ICON然後将它拖到桌面上不就行了嗎?沒錯,這樣是一種方法,但這種方法有一個缺點,看圖吧:
如上圖,如果我們長按桌面點選快捷方式,将會跳到如下界面,如果單從這個界面選擇的話,我們就必須進入Applications 目錄,然後再在Applications 裡面選擇我們對應的應用程式,這樣的話使用者可能得麻煩的去找咯。但我們同時會發現,在Applications 的下面有很多另外的ICON比如 上圖的BookMark ,Contact 等,這些也是應用,那麼這些是怎麼做到不用進去Applications 而在第一頁就出現供使用者選擇呢?今天我們就針對這點來講講吧。
要做這一功能首先我們先來了解一下manifest 裡面的這一标簽:
<activity-alias>
syntax:文法:
activity的一個别名,用<code>targetActivity</code>屬性命名。目标activity必須與别名在同一應用程式的manifest裡,并且在别名之前聲明。
上面給出的解釋我們來配置一下manifest,配置為如下:
<activity android:name=".shortcut">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</intent-filter>
</activity>
<activity-alias android:name=".CreateShortcuts"
android:targetActivity=".shortcut" android:label="@string/shortcut">
<action android:name="android.intent.action.CREATE_SHORTCUT" />
<category android:name="android.intent.category.DEFAULT" />
</activity-alias>
Activity:
.shortcut 是我們快捷方式需要的Activity
activity-alias:
對應的targetActivity是指向應用建立快捷方式使用的Activity
android:label對應的建立快捷方式清單顯示的文字,而該應用對應的快捷方式的圖示則預設使用我們給定的application的圖示。如圖:
好了,這是第一步步驟,下面進入代碼階段,先看代碼:
package com.terry.attrs;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.widget.LinearLayout;
import android.widget.TextView;
public class shortcut extends Activity {
private static final String SHORT_CUT_EXTRAS = "com.terry.extra.short";
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
final Intent intent = getIntent();
final String action = intent.getAction();
if (Intent.ACTION_CREATE_SHORTCUT.equals(action)) {
createShortCut();
finish();
return;
}
String extra = intent.getStringExtra(SHORT_CUT_EXTRAS);
LinearLayout layout = new LinearLayout(getApplicationContext());
TextView tv = new TextView(getApplicationContext());
if (extra != null)
tv.setText(extra);
layout.addView(tv);
setContentView(layout);
}
void createShortCut() {
Intent shortcutIntent = new Intent(Intent.ACTION_MAIN);
shortcutIntent.setClass(this, this.getClass());
shortcutIntent.putExtra(SHORT_CUT_EXTRAS, "測試的快捷方式");
Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "這裡随便指定");
Parcelable shortIcon = Intent.ShortcutIconResource.fromContext(
this, com.terry.attrs.R.drawable.icon);
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, shortIcon);
setResult(RESULT_OK, intent);
}
代碼解釋:
onCreate方法,首先擷取intent 的action如果接收到的action為建立快捷方式的請求,則執行建立快捷方式的代碼,否則則通過得到的extra 為textView 指派。
createShortCut方法,首先設定快捷方式點選後要跳轉的intent 和要帶入的參數,然後設定桌面快捷方式的名稱,圖示和對應的intent(即上面帶入資料和跳轉的界面的 class的Intent)最後将結果傳入。
最近運作的結果:
跳擊後到達的界面:
TIP:這裡可以是任何ACTIVITY界面。
最後給大家分享下源碼吧:
就到這裡,希望我的一篇廢話能對你有所幫助。
<a href="http://down.51cto.com/data/2357073" target="_blank">附件:http://down.51cto.com/data/2357073</a>
本文轉自 terry_龍 51CTO部落格,原文連結:http://blog.51cto.com/terryblog/415396,如需轉載請自行聯系原作者