天天看點

Android開發(25) 兩個App之間使用intent交換資料概述實作

概述

兩個App之間如何進行資料交換,像“使用intent調用系統自帶的拍照應用并獲得結果” 是一種很友善的形式。

它發送一個 Intent,這個Intent指明啟動了另外一個App,完成任務後指定傳回結果,原先的App接收傳回的結果。

先看頁面:

Android開發(25) 兩個App之間使用intent交換資料概述實作
Android開發(25) 兩個App之間使用intent交換資料概述實作

實作

第一個應用 DEMO1:

1.建立一個自定義的action, 使用intent發出

String action = "zyf.demo.customAction";
Intent n = new Intent(action);                 

複制

2.附件一些自定義的内容,使用putExtra

n.putExtra("key1", "hello,這是來自demo1的消息。");           

複制

3.可以先檢查是否有比對這個action的處理程式。

String action = "zyf.demo.customAction";
        Intent n = new Intent(action);

        PackageManager packageManager = getBaseContext().getPackageManager();
        final Intent intent = new Intent(action);
        List<ResolveInfo> resolveInfo = packageManager
                .queryIntentActivities(intent,
                        PackageManager.MATCH_DEFAULT_ONLY);
        if (resolveInfo.size() > 0) {
            Toast.makeText(getBaseContext(), "找到了比對的activity", 0).show();
        }
        else{
            Toast.makeText(getBaseContext(), "未找到比對的activity", 0).show();
        }           

複制

4.使用 startActivityForResult 方法 啟動Intent。

startActivityForResult(n, REQUEST_CODE_1);             

複制

5.獲得結果(來自DEMO2傳回的)

final int REQUEST_CODE_1 = 1;

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_CODE_1) {
        String res = data.getStringExtra("result");
        Toast.makeText(getBaseContext(), "收到:" + res, 0).show();
    } else
        super.onActivityResult(requestCode, resultCode, data);
}           

複制

第二個應用,DEMO2:

1.建立一個activity用于接收 “上面指定的action”,并在AndroidManifest.xml 檔案中注冊intent-filter。

<activity
        android:name="zyf.demo.demo2.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        <intent-filter>
             <action android:name="zyf.demo.customAction"/>
             <category android:name="android.intent.category.DEFAULT"/>
        </intent-filter>
    </activity>           

複制

2.在activity中可以顯示來自DEMO1的資料。

private void tryShowExtra() {
    try {
        Intent intent = getIntent();
        String extra1 = intent.getStringExtra("key1");
        txt1.setText(extra1);
    } catch (Exception e) {
        txt1.setText(e.getMessage());
    }

}           

複制

3.在activity中處理關閉目前應用時的傳回内容

public void onClick(View v){
    Intent resultIntent = new Intent();
    resultIntent.putExtra("result", "這是來自demo2的結果");
    setResult(Activity.RESULT_OK, resultIntent);
    this.finish();
}           

複制

示範代碼下載下傳