深入分析:Android中app之間的互動(二,使用ComponentName)

來源:互聯網
上載者:User

        在前一篇相關主題的博文中我們瞭解了如何使用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了,如有需要可以下載來看,點擊開啟連結











聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.