1. 程式人生 > >android7.1新特性 App Shortcuts 圖示快捷啟動

android7.1新特性 App Shortcuts 圖示快捷啟動

前幾天看了下谷歌的釋出會,在介紹7.1的適合展示了圖示快捷啟動的功能,類似於蘋果的3d touch ,好酷炫,於是決定自己動手研究一波

在動手開發之前呢先將AS升級到最新版,SDK更新到API25,因為只有API25才能使用這個功能。

首先介紹一下核心的幾個類,

ShortcutManager 該類是圖示資訊管理者,主要負責新增,更新或去除圖示上的某個條目

2 Shortcutinfo 該類是圖示條目資訊類,整個類代表一個條目,該類可以設定條目資訊,包括圖示,標題,主體內容,隱藏內容

Shortcutinfo.Binder 該類用來建立一個Shortcut條目,返回Shortcutinfo物件

我們再來看看幾個XML屬性:

android:shortcutId   條目資訊的ID

android:enabled     條目資訊是否顯示,預設是顯示的

android:icon           條目資訊的圖示

android:shortcutShortLabel  條目資訊的標題(有正文的時候不會顯示)

android:shortcutLongLabel  條目資訊的正文

android:shortcutDisabledMessage 當android:enabled  為false的時候顯示的內容

intent 使用者點選後跳轉的intent物件,強制要求有android:action 屬性

OK,瞭解完上面的屬性以後,我們開始動手實現下吧,

1,在AndroidMainfest.xml檔案下,在主程式入口的<activity>標籤線新加入一個<meta-data>標籤,用來設定圖示條目的資訊,其內容如下:

<meta-data android:name="android.app.shortcuts"
android:resource="@xml/shortcuts" />
2 在res目錄下新建一個xml資料夾,在資料夾下新建一個shortcuts的xml檔案,該檔案用來靜態設定條目的資訊
內容如下:
<?xml version="1.0" 
encoding="utf-8"?> <shortcuts xmlns:android="http://schemas.android.com/apk/res/android"> <shortcut android:shortcutId="compose" android:enabled="true" android:icon="@mipmap/ic_launcher" android:shortcutShortLabel="@string/compose_shortcut_short_label1" android:shortcutLongLabel="@string/compose_shortcut_long_label1" android:shortcutDisabledMessage="@string/compose_disabled_message1"> <intent android:action="android.intent.action.VIEW" android:targetPackage="com.example.wenxi.myapplication" android:targetClass="com.example.wenxi.myapplication.MainActivity" /> <!-- If your shortcut is associated with multiple intents, include them here. The last intent in the list is what the user sees when they launch this shortcut. --> <categories android:name="android.shortcut.conversation" /> </shortcut> <!-- Specify more shortcuts here. --> </shortcuts>

OK,簡單兩步,就完成了最簡單的demo,當然這還不夠,前面我說過,這是靜態的,要是需求裡面要動態更新條目資訊呢,這樣我們就不能夠用xml去做了,我們需要用程式碼實現上面的功能
首先,初始化ShortcutManager
ShortcutManager shortcutManager = getSystemService(ShortcutManager.class);
//返回shortcutManager 物件
其次,我們需要通過Shortcutinfo.Binder去建立 Shortcutinfo 物件
ShortcutInfo shortcut = new ShortcutInfo.Builder(this, "id1")
該方法中傳入的引數是當前Activity的上下文和條目的ID
拿到 shortcut,物件以後,我們就可以設定條目資訊了
.setShortLabel("Web site")//設定標題
.setLongLabel("Open"+String.valueOf(index)+"")//設定
.setIcon(Icon.createWithResource(context, R.mipmap.ic_launcher))
//.setActivity(new ComponentName("com.example.wenxi.myapplication","com.example.wenxi.myapplication.MainActivity"))
.setIntent(new Intent(Intent.ACTION_VIEW,
        Uri.parse("https://www.baidu.com/")))//設定點選跳轉的intent物件
.build();//建立
這裡需要注意的是,動態設定必須要設定intent物件,否則會報空指標異常,還有就是不知道是不是因為bug,
setActivity並不起作用
定義一個list,將shortcut新增到list裡面
private List<ShortcutInfo> list=new ArrayList();
list.add(shortcut);

最後,通過ShortcutManager新增資訊條目或者刪除條目:主要有下面三個方法:
注:可以有多個list資訊集合
本文采用shortcutManager.setDynamicShortcuts(list);
執行結果如圖:
原始碼下載地址:http://download.csdn.net/detail/qq_25817651/9673658