在前一篇相關主題的博文中我們瞭解了如何使用Action來啟動當前應用之外的Activity處理我們的商務邏輯,在本篇筆記中我在簡單介紹一下使用ComponentName來與當前應用之外的應用進行互動。
在介紹Component之前,我們首先來瞭解ComponentName這個類;ComponentName與Intent同位於android.content包下,我們從Android官方文檔中可以看到,這個類主要用來定義可見一個應用程式組件,例如:Activity,Service,BroadcastReceiver或者ContentProvider。
那麼,如何用ComponentName來定義一個組件呢。
這是ComponentName的建構函式:ComponentName(String pkg,String cls)
我們知道在Android應用程式中如果要詳細描述一個組件我們需要知道該組件所在的應用程式套件名,也就是在AndroidManifest.xml檔案中manifest根結點下的package=“XXX.XXXXX.XXXXX",還有組件在應用程式中的完整路徑名,拿Activity來說,也就是activity節點中name屬性的值。因此到這裡我們也就明白了可以使用ComponentName來封裝一個組件的應用程式套件名和組件的名字。
我們已經知道,在Android中組件之間的交流往往使用意圖(Intent)來完成的,那麼在Intent中有一個方法可以封裝一個ComponentName,最後我們在使用意圖去完成我們需要實現的功能。
下面我們用具體的代碼來描述如何使用ComponentName來協助我們與其他應用程式互動:
首先我們要建立兩個Android應用程式,appsend和appreceiver。
appreceiver的AndroidMainfest.xml
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" <span style="color:#cc0000;"> <strong>package="com.example.appreceiver"</strong></span> android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="11" android:targetSdkVersion="18" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity <strong><span style="color:#ff0000;"> android:name="com.example.appreceiver.MainActivity"</span></strong> android:label="@string/app_name" > <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) {<strong><span style="color:#ff0000;">ComponentName cn=new ComponentName("com.example.appreceiver", "com.example.appreceiver.MainActivity");</span></strong>Intent intent = new Intent();<strong><span style="color:#ff0000;">intent.setComponent(cn);</span></strong>startActivityForResult(intent, 2);}
完整案例,已經打包上傳至csdn了,如有需要可以下載來看,點擊開啟連結