Android中接受来自其他应用的内容

Mainfest 文件代码:

<activity android:name=”.IntentReceiver” >
<intent-filter>
<action android:name=”android.intent.action.SEND” />
<category android:name=”android.intent.category.DEFAULT” />
<data android:mimeType=”image/*” />
</intent-filter>
<intent-filter>
<action android:name=”android.intent.action.SEND” />
<category android:name=”android.intent.category.DEFAULT” />
<data android:mimeType=”text/plain” />
</intent-filter>
<intent-filter>
<action android:name=”android.intent.action.SEND_MULTIPLE” />
<category android:name=”android.intent.category.DEFAULT” />
<data android:mimeType=”image/*” />
</intent-filter>
</activity>

范例:

void onCreate (Bundle savedInstanceState) {
    ...
    // 获取 intent、 action 以及 MIME 类型,这些是一个意图的主要内容
    Intent intent = getIntent();
    String action = intent.getAction();
    String type = intent.getType();

    if (Intent.ACTION_SEND.equals(action) && type != null) {
        if ("text/plain".equals(type)) {
            handleSendText(intent); // 处理收到的文本
        } else if (type.startsWith("image/")) {
            handleSendImage(intent); // 处理收到的图像
        }
    } else if (Intent.ACTION_SEND_MULTIPLE.equals(action) && type != null) {
        if (type.startsWith("image/")) {
            handleSendMultipleImages(intent); // 处理收到的多个图像
        }
    } else {
        // 还可以添加其他类型意图的处理
    }
    ...
}

void handleSendText(Intent intent) {
    String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
    if (sharedText != null) {
        // 更新 UI 来反映收到的内容
    }
}

void handleSendImage(Intent intent) {
    Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
    if (imageUri != null) {
        // 更新 UI 来反映收到的内容
    }
}

void handleSendMultipleImages(Intent intent) {
    ArrayList imageUris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
    if (imageUris != null) {
        // 更新 UI 来反映收到的内容
    }
}

说明:通过在 Manifest 文件中声明相应的意图过滤器,就可以接收来自其他应用的数据以供在自己的应用中进行处理。

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注