首页 > 解决方案 > 当我选择一些文本并单击共享时,它将显示我的应用程序

问题描述

我想构建一个android应用程序。它的方式是当我选择一些文本并单击共享时,它会显示我的应用程序。谁能帮助我我需要使用什么以及如何获得?

标签: android

解决方案


您需要告诉 Android 您的应用可以处理文本。您可以通过在 Android 清单文件中定义意图过滤器来做到这一点。

例如:

<activity android:name=".ui.MyActivity" >
    <intent-filter>
        <action android:name="android.intent.action.SEND" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:mimeType="text/plain" />
    </intent-filter>
</activity>

在这里,您是在告诉系统,每当有人共享“文本/纯文本”类型的内容时,都将显示我的应用程序作为选项。

如果用户选择您的应用程序,您将在 ui.MyActivity 类中获取数据,如下所述:

void onCreate (Bundle savedInstanceState) {
    ...
    // Get intent, action and MIME type
    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); // Handle text being sent
        }
    } else {
        // Handle other intents, such as being started from the home screen
    }
    ...
}

void handleSendText(Intent intent) {
    String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
    if (sharedText != null) {
        // Update UI to reflect text being shared
    }
}

推荐阅读