1. 程式人生 > >Android中通過其他APP啟動Activity的四種方式

Android中通過其他APP啟動Activity的四種方式

提示:在啟動一個Activity前進行必要的存在檢測很有必要,以免程式意外崩潰。

第一種:通過applicationId與package+activityPath

applicationId告訴系統活動在那個App內,進入App內就需要類路徑找具體的Activity。

//applicationId:com.example.student0.caller CallerActivity.java

private final static int REQ_CODE = 0X2233;
private final static String TARGET_APP_ID = "com.example.student0.recipient";
private final static String TARGET_ACTIVITY_DIR = "com.student0.demo.RecipientActivity";

ComponentName component = new ComponentName(TARGET_APP_ID, TARGET_ACTIVITY_DIR);
Intent intent = new Intent();
intent.setComponent(component);
startActivityForResult(CallerActivity.this, intent);



//applicationId:com.example.student0.recipient Manifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.student0.demo">
...
<activity android:name=".RecipientActivity.java" android:exported="true"/>
...

第二種:通過自定義Action啟動。

//applicationId:com.example.student0.recipient Manifest.xml
<intent-filter>
    <action android:name="com.example.student0.helloWord"/>
    <category android:name="android.intent.category.DEFAULT"/>
</intent-filter>



//applicationId:com.example.student0.caller CallerActivity.java
String targetActivityAction = "com.example.student0.helloWord";//與被呼叫的Activity的Action一致
Intent intent = new Intent();
intent.setAction(targetActivityAction);
CallerActivity.this.startActivity(intent);

第三種:通過packageManager獲取擁有對應軟體包名(ApplicationId)的App的Launch活動。

//applicationId:com.example.student0.caller CallerActivity.java
Intent intent = getPackageManager().getLaunchIntentForPackage("com.example.student0.recipient");
this.startActivity(intent);

第四種:通過<data/>設定可以響應的指定資料型別。

//applicationId:com.example.student0.recipient Mainfest.xml
<intent-filter>
    <category android:name="android.intent.category.DEFAULT"/>
    <data android:scheme="gugu"/>
</intent-filter>

//applicationId:com.example.student0.caller CallerActivity.java

Uri uri = Uri.parse("gugu://...");
Intent intent = new Intent();
intent.setData(uri);

android:scheme。指定資料的協議部分。

android:host。指定資料的主機部分。

android:port。指定資料的埠部分。

android:path。指定主機名和埠後的部分,即相對路徑。

android:mimeType。指定可以處理的資料型別,允許使用萬用字元的方式進行指定。

一個activity可以響應多個android:scheme,當一條<data/>中同時存在host、port、path時,資料的格式需要滿足該條<data/>中指定的所有協定。<data/>屬性指定的響應資料型別,在網頁中也能得到響應例如:

<a href="gugu://...">