編輯:初階開發
繼先前的 Intent 呼叫程式碼整理之後,這裡再補充一批實用寫法。熟悉 Intent 機制的讀者可能會發現,它無非就是對 Action、Category 與 Type 加上附加資料,程式透過 UriMatch 或 Intent-filter 來判斷處理,原理並不複雜。以下提供一些新的範例。
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(People.CONTENT_URI);
startActivity(intent);
這裡同樣是 ACTION_VIEW;若要改為「選擇並返回」,可將 action 改為 ACTION_PICK,並以 startActivityForResult 處理返回結果:
Uri personUri = ContentUris.withAppendedId(People.CONTENT_URI, ID); // ID 為聯絡人 Provider 中的資料列 BaseID
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(personUri);
startActivity(intent);
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, 0);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment
.getExternalStorageDirectory().getAbsolutePath() + "/cwj", "android123.jpg"))); // 存放於 sdcard 的 cwj 資料夾
startActivityForResult(intent, 0);
例如搜尋 com.android123.cwj:
Uri uri = Uri.parse("market://search?q=pname:com.android123.cwj");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
這些片段涵蓋了瀏覽聯絡人、挑選圖片、拍照與跳轉市集等常見情境,善用 Action 與 Uri 的組合,就能靈活驅動系統的各種功能。
Android 快捷方式(二):讓自己的 Activity 出現在 Launcher 選單裡
在桌面空白處長按,會跳出「加到主畫面」的對話框,接著選擇「捷徑」,系統便会列出所有可建立捷徑的 Activity——每個項目顯示對應應用的圖示與名稱。 問題是:怎麼讓自
Android 特色開發:帳戶管理(AccountManager)實作解析
本文節選自機械工業出版社《Android 應用開發揭秘》,作者楊豐盛。該書涵蓋 Android 框架、組件、使用者介面、遊戲開發、資料儲存、多媒體與網路開發等基礎,並深入
Google 發表 Android 2.3.3 SDK:NFC 全面開放
Google 於去年 12 月底正式推出 Android 2.3(Gingerbread)系統,其中 NFC 近場通訊是最受矚目的亮點之一。今日 Google 正式發布
Android ApiDemo 圖形與視圖(三):從 LinearLayout 到 TableLayout 的布局實戰
本篇延續 ApiDemo 中「Graphics and Views」的閱讀筆記,涵蓋第 37 到第 57 號範例。這一段的重心很明確:把布局從「寫死在 XML 裡」變成「