Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 系統功能呼叫:用 Intent 打電話、開相機與瀏覽器

編輯:關於 Android 程式設計

Android 的 Intent 不只是頁面之間的傳遞工具,它同時是「向系統描述你想做什麼」的標準方式。想撥電話、想看圖片、想開網頁、想拍照——這些都不用自己實作,只要宣告一個 Intent 並交給 startActivity(),系統就會找出適合的應用程式接手。

版面配置

先放四顆按鈕,各自對應一種系統功能:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center_horizontal">

    <Button
        android:id="@+id/callTelephoneButton"
        android:layout_width="150dip"
        android:layout_height="40dip"
        android:layout_marginTop="50dip"
        android:gravity="center"
        android:text="撥打電話"
        android:textSize="20sp" />

    <Button
        android:id="@+id/browsephotosButton"
        android:layout_width="150dip"
        android:layout_height="40dip"
        android:layout_marginTop="50dip"
        android:gravity="center"
        android:text="瀏覽圖片"
        android:textSize="20sp" />

    <Button
        android:id="@+id/openBrowserButton"
        android:layout_width="150dip"
        android:layout_height="40dip"
        android:layout_marginTop="50dip"
        android:gravity="center"
        android:text="開啟瀏覽器"
        android:textSize="20sp" />

    <Button
        android:id="@+id/openCameraButton"
        android:layout_width="150dip"
        android:layout_height="40dip"
        android:layout_marginTop="50dip"
        android:gravity="center"
        android:text="開啟相機"
        android:textSize="20sp" />
</LinearLayout>

Activity 程式碼

package cn.com.bravesoft.testintent;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

    private Button mTelephoneButton;
    private Button mPhotosButton;
    private Button mBrowserButton;
    private Button mCameraButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mTelephoneButton = (Button) findViewById(R.id.callTelephoneButton);
        mPhotosButton    = (Button) findViewById(R.id.browsephotosButton);
        mBrowserButton   = (Button) findViewById(R.id.openBrowserButton);
        mCameraButton    = (Button) findViewById(R.id.openCameraButton);

        OnClickListener listener = new ButtonOnClickListenerImpl();
        mTelephoneButton.setOnClickListener(listener);
        mPhotosButton.setOnClickListener(listener);
        mBrowserButton.setOnClickListener(listener);
        mCameraButton.setOnClickListener(listener);
    }

    private class ButtonOnClickListenerImpl implements OnClickListener {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {

                case R.id.callTelephoneButton:
                    // 直接撥打電話
                    Intent telephoneIntent = new Intent(Intent.ACTION_CALL);
                    telephoneIntent.setData(Uri.parse("tel:150028068"));
                    startActivity(telephoneIntent);
                    break;

                case R.id.browsephotosButton:
                    // 瀏覽圖片:由系統挑選合適的圖庫應用程式
                    Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
                    galleryIntent.setType("image/*");
                    galleryIntent.addCategory(Intent.CATEGORY_OPENABLE);
                    startActivity(galleryIntent);
                    break;

                case R.id.openBrowserButton:
                    // 開啟瀏覽器
                    Intent browserIntent = new Intent(Intent.ACTION_VIEW);
                    browserIntent.setData(Uri.parse("https://www.example.com"));
                    startActivity(browserIntent);
                    break;

                case R.id.openCameraButton:
                    // 開啟相機拍照
                    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivity(cameraIntent);
                    break;

                default:
                    break;
            }
        }
    }
}

四個 Intent 的共同點是:都只描述「意圖」,不指定要由哪個 App 執行。系統會比對已安裝程式的 intent-filter,挑出能處理的元件——這正是 Android 元件模型鬆耦合的體現。

四個功能各自的重點

撥打電話

Uri.parse("tel:號碼") 搭配 ACTION_CALL 會直接撥出,因此必須在 AndroidManifest 中宣告 <uses-permission android:name="android.permission.CALL_PHONE" />,且執行期還要向使用者動態索取授權。若不想處理權限,改用 Intent.ACTION_DIAL,系統會帶使用者到撥號鍵盤並自動填號,由使用者自行按下撥號——大多數 App 都採這個折衷方案。

另外,別把 action 寫成字串 "android.intent.action.CALL",直接用 Intent.ACTION_CALL 常數才能享有編譯期檢查。

瀏覽圖片

ACTION_GET_CONTENT 搭配 type="image/*" 表示「我要一個圖片內容的 Uri」。加上 CATEGORY_OPENABLE 可過濾出真正能開啟的項目。若想同時支援多選與雲端來源,可改用 ACTION_OPEN_DOCUMENT,並記得把取得的 Uri 權限持久化(takePersistableUriPermission)。

開啟瀏覽器

ACTION_VIEW 是最通用的 action,只要給它 http/https 的 Uri,系統就會交給瀏覽器;給 geo: 會開地圖,給 mailto: 會開郵件。同一個 action 因 Uri 配置不同而導向不同程式,是 Intent 設計上最優雅的一點。

開啟相機

MediaStore.ACTION_IMAGE_CAPTURE 會啟動相機。範例中並未接收結果,拍照後相片由相機 App 自行保存。若需要拿到照片,有兩種常見做法:一是用 startActivityForResult() 並在 onActivityResult() 中從 extras 的 data 取出縮圖(解析度低,僅適合頭像等小圖);二是事先建立一個空檔案並以 putExtra(MediaStore.EXTRA_OUTPUT, uri) 指定輸出路徑,讓相機把原始大小的照片寫入該位置。

實務提醒

  • 先確認有人接:用 intent.resolveActivity(getPackageManager()) 檢查是否有程式能處理,避免丟出 ActivityNotFoundException 造成閃退。部分無 GMS 的裝置或平板也可能沒有相機、撥號程式。
  • 拍照要處理 FileProvider:Android 7.0(API 24)起,把 file:// 形式的 Uri 傳給其他 App 會觸發 FileUriExposedException。正確做法是在 manifest 宣告 FileProvider 與檔案路徑設定檔,用 getUriForFile() 取得 content:// Uri,並加上 FLAG_GRANT_READ_URI_PERMISSION。
  • 返回結果要驗證:onActivityResult() 中除了比對 requestCode,還應檢查 resultCode == RESULT_OK 與 data != null,使用者按返回鍵取消是常見路徑。
  • 設定檔要補齊:若使用 ACTION_CALL,除了權限宣告,targetSdk 在 API 23 以上還需 checkSelfPermission 與 requestPermissions 的執行期流程,缺一段就會在撥號時被系統攔下。
  • 善用共用選單:想讓使用者自行挑選分享/開啟方式,可用 Intent.createChooser() 包一層,語意比直接 startActivity 更清楚。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved