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

深入解析 Android 應用互動(二):使用 ComponentName 跨應用通訊

編輯:關於 Android 程式設計

在前一篇文章中,我們探討了如何透過 Action 啟動本應用之外的 Activity 來完成業務邏輯。本篇筆記則要介紹另一種方式——透過 ComponentName 與其他應用進行互動。

認識 ComponentName

ComponentName 與 Intent 同屬 android.content 套件。根據 Android 官方文件,這個類別主要用來描述應用程式中的某個元件,例如 Activity、Service、BroadcastReceiver 或 ContentProvider。

那麼,該如何以 ComponentName 定義一個元件呢?先來看它的建構子:

ComponentName(String pkg, String cls)

我們知道,在 Android 應用程式中,若要精確描述一個元件,必須掌握兩項資訊:一是元件所在的應用包名,也就是 AndroidManifest.xml 中 manifest 根節點下的 package="XXX.XXXXX.XXXXX";二是元件在應用中的完整類別路徑名稱,以 Activity 而言即為 activity 節點中 name 屬性的值。因此,ComponentName 的作用就是把「應用包名」與「元件名稱」這兩項資訊封裝在一起。

由於 Android 中元件之間的溝通主要透過 Intent 完成,而 Intent 提供了一個方法可以設定 ComponentName,於是搭配起來便能精準地導向目標元件。

實作步驟

我們建立兩個 Android 專案:appsend(發送方)與 appreceiver(接收方)。

首先,接收方 appreceiver 的 AndroidManifest.xml 必須明確宣告其元件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.appreceiver"
    android:versionCode="1"
    android:versionName="1.0">

    <uses-sdk android:minSdkVersion="11" android:targetSdkVersion="18" />

    <application android:label="@string/app_name">
        <activity android:name="com.example.appreceiver.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

接著,在發送方 appsend 中撰寫啟動目標 Activity 的程式片段:

public void button(View view) {
    ComponentName cn = new ComponentName("com.example.appreceiver", "com.example.appreceiver.MainActivity");
    Intent intent = new Intent();
    intent.setComponent(cn);
    startActivityForResult(intent, 2);
}

透過 new ComponentName(包名, 類別名稱) 精準定位元件,再以 intent.setComponent(cn) 設定目標,最後呼叫 startActivityForResult() 即可跨應用啟動對方的 Activity,並能接收回傳結果。這種做法比單純依賴 Action 更為精確,特別適合在明確知道目標元件身分的場合使用。

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