You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React Native(Expo)安卓应用中获取其他应用的选中文本?

解决方案

要获取通过PROCESS_TEXT Intent传递的选中文本,你可以借助Expo的expo-intent-launcher模块读取Intent的额外数据(extras),具体步骤如下:

1. 安装依赖

首先安装expo-intent-launcher,它能帮助我们获取完整的Intent信息:

npx expo install expo-intent-launcher

2. 在应用中读取选中的文本

在根组件(比如App.js)中,同时处理应用首次启动和后台唤起两种场景下的Intent数据,获取选中的文本:

import React, { useEffect, useState } from 'react';
import { View, Text } from 'react-native';
import { Linking } from 'react-native';
import { getIntentAsync } from 'expo-intent-launcher';

export default function App() {
  const [selectedText, setSelectedText] = useState(null);

  useEffect(() => {
    // 处理Intent并提取文本的通用逻辑
    const processIntent = (intent) => {
      if (intent.action === 'android.intent.action.PROCESS_TEXT') {
        const text = intent.extras['android.intent.extra.PROCESS_TEXT'];
        if (text) {
          setSelectedText(text);
          // 这里可以添加你的业务逻辑,比如用选中的文本执行后续操作
        }
      }
    };

    // 获取应用启动时的初始Intent
    const fetchInitialText = async () => {
      const intent = await getIntentAsync();
      processIntent(intent);
    };

    // 监听应用从后台唤起时的Intent
    const handleIntent = async () => {
      const intent = await getIntentAsync();
      processIntent(intent);
    };

    fetchInitialText();
    const subscription = Linking.addEventListener('url', handleIntent);

    return () => subscription.remove();
  }, []);

  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <Text>选中的文本:{selectedText || '暂无'}</Text>
    </View>
  );
}

3. 关键说明

  • PROCESS_TEXT Intent传递的选中文本固定存储在Intent的extras中,键名为android.intent.extra.PROCESS_TEXT
  • 必须同时处理应用首次启动和后台唤起两种场景,确保无论哪种方式打开应用都能获取到文本
  • 你已在app.json中配置的Intent Filter无需修改,保持现有配置即可

内容的提问来源于stack exchange,提问作者Nauman Zafar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 15:45:43