Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 初階開發

Intent 呼叫程式碼整理(二)

編輯:初階開發

繼先前的 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);

在 Market 搜尋指定套件名稱

例如搜尋 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 的組合,就能靈活驅動系統的各種功能。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved