歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android活動文件夾

Android活動文件夾

日期:2017/3/1 10:23:12   编辑:Linux編程

Android活動文件夾是SDK1.5引入的,支持開發人員在設備的桌面上公開ContentProvider,如聯系人、媒體數據等。Android中的活動文件夾對ContentProvider的作用就相當於RSS閱讀器對發布網站的作用。

活動文件夾的工作原理如下:

(1)首先在主頁上創建一個圖標,表示來自ContentProvider的一組行。通過為圖標指定一個URI來進行鏈接。

(2)當用戶單擊該圖標時,系統接受URI並用它掉用ContentProvider。ContentProvider通過游標返回一組行。

(3)只要此游標包含活動文件夾想要的列(比如名稱、描述和單擊時調用的程序)系統就會以ListView或GridView形式呈現這些行。

(4)因為在基礎存儲數據更改時,ListView或GridView能夠更新自己的數據,所以這些視圖被視為活的,活動文件夾因此而得名。

了解了活動文件夾概念後,接下來介紹如何構建活動文件夾。要構建活動文件夾需要兩個東西:一個活動和一個專門的ContentProvider。Android使用次活動標簽來填充可用活動文件夾列表。下面的例子中我們將使用Android內置的ContentProvider:Contacts聯系人,來實現一個聯系人的活動文件夾。

首先來看描述文件:AndroidManifest.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  3. package="com.test.livefolder"
  4. android:versionCode="1"
  5. android:versionName="1.0">
  6. <application android:icon="@drawable/icon" android:label="@string/app_name">
  7. <activity android:name=".MainActivity"
  8. android:label="@string/app_name">
  9. <intent-filter>
  10. <strong><category android:name="android.intent.category.DEFAULT" />
  11. <action android:name="android.intent.action.CREATE_LIVE_FOLDER"/></strong>
  12. </intent-filter>
  13. </activity>
  14. </application>
  15. </manifest>

接下來是主活動類:

  1. public class MainActivity extends Activity {
  2. /** Called when the activity is first created. */
  3. @Override
  4. public void onCreate(Bundle savedInstanceState) {
  5. super.onCreate(savedInstanceState);
  6. final Intent intent = getIntent();
  7. final String action = intent.getAction();
  8. //從聯系人取得數據
  9. final Uri uri = Uri.parse("content://contacts/live_folders/people");
  10. if (LiveFolders.ACTION_CREATE_LIVE_FOLDER.equals(action)){
  11. setResult(RESULT_OK, createLiveFolder(uri,"Contacts LF",R.drawable.icon));
  12. }
  13. else{
  14. setResult(RESULT_CANCELED);
  15. }
  16. this.finish();
  17. }
  18. //創建活動文件夾
  19. private Intent createLiveFolder(Uri uri,String name,int icon){
  20. final Intent intent = new Intent();
  21. //設置Intent
  22. intent.setData(uri);
  23. //活動文件夾名稱
  24. intent.putExtra(LiveFolders.EXTRA_LIVE_FOLDER_NAME, name);
  25. //活動文件夾圖標
  26. intent.putExtra(LiveFolders.EXTRA_LIVE_FOLDER_ICON, Intent.ShortcutIconResource.fromContext(this, icon));
  27. //顯示模式:列表
  28. intent.putExtra(LiveFolders.EXTRA_LIVE_FOLDER_DISPLAY_MODE, LiveFolders.DISPLAY_MODE_LIST);
  29. return intent;
  30. }
  31. }

運行程序,長按桌面,選擇文件夾,結果如圖所示:


然後選擇,Contact live folder在桌面出現一個活動文件夾,如圖:


單擊此活動文件夾,由於此時沒有聯系人記錄所以活動文件夾中列表為空如圖,


我們手動添加2個聯系人記錄後,在點擊Contact LF活動文件夾,結果如圖:


可見活動文件夾中的數據確實會實時更新。

更多Android相關信息見Android 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=11

Copyright © Linux教程網 All Rights Reserved