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

React Native中Android端向JS传递Intent获取的图文数据

Got it, let's walk through how to pass the Intent data (text and images) from your Android MainActivity to React Native and display it. Here's a step-by-step solution that covers both text and image sharing, plus edge cases like cold starts:

Step 1: Complete Intent Handling & Send Data to React Native in MainActivity.java

First, let's finish your existing code and add logic to send the shared data to React Native using React Native's event emitter. We'll handle both text and image types, and make sure we account for when the React context isn't fully initialized yet.

import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactContext;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;

public class MainActivity extends ReactActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Handle incoming Intent data on app launch
        handleIntent(getIntent());
    }

    // Handle new Intents when the app is already running (hot start)
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        handleIntent(intent);
    }

    // Core logic to process the Intent
    private void handleIntent(Intent intent) {
        String action = intent.getAction();
        String type = intent.getType();

        if (Intent.ACTION_SEND.equals(action) && type != null) {
            if ("text/plain".equals(type)) {
                String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
                if (sharedText != null) {
                    sendDataToReactNative("sharedText", sharedText);
                }
            } else if (type.startsWith("image/")) {
                Uri imageUri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
                if (imageUri != null) {
                    // Convert Uri to string for easy passing to JS
                    sendDataToReactNative("sharedImage", imageUri.toString());
                }
            }
        }
    }

    // Helper method to send data to React Native via event emitter
    private void sendDataToReactNative(String key, String value) {
        ReactInstanceManager reactInstanceManager = getReactInstanceManager();
        if (reactInstanceManager == null) return;

        // If React context is ready, send immediately
        if (reactInstanceManager.getCurrentReactContext() != null) {
            sendEvent(reactInstanceManager.getCurrentReactContext(), "SharedDataReceived", key, value);
        } else {
            // Wait for React context to initialize, then send
            reactInstanceManager.addReactInstanceEventListener(new ReactInstanceManager.ReactInstanceEventListener() {
                @Override
                public void onReactContextInitialized(ReactContext context) {
                    sendEvent(context, "SharedDataReceived", key, value);
                    // Remove listener to avoid duplicate events
                    reactInstanceManager.removeReactInstanceEventListener(this);
                }
            });
        }
    }

    // Wrapper to create and send the event
    private void sendEvent(ReactContext reactContext, String eventName, String key, String value) {
        WritableMap params = Arguments.createMap();
        params.putString(key, value);
        reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                .emit(eventName, params);
    }

    // ... rest of your MainActivity code (like getMainComponentName())
}
Step 2: Receive & Display Data in React Native JavaScript

Now, let's create a component that listens for the event we sent from Android, stores the data in state, and renders it to the user.

import React, { useState, useEffect } from 'react';
import { View, Text, Image, StyleSheet, DeviceEventEmitter } from 'react-native';

const SharedContentScreen = () => {
    const [sharedText, setSharedText] = useState(null);
    const [sharedImageUri, setSharedImageUri] = useState(null);

    useEffect(() => {
        // Listen for the event sent from Android
        const contentListener = DeviceEventEmitter.addListener(
            'SharedDataReceived',
            (data) => {
                // Update state based on the data received
                if (data.sharedText) {
                    setSharedText(data.sharedText);
                }
                if (data.sharedImage) {
                    setSharedImageUri(data.sharedImage);
                }
            }
        );

        // Clean up the listener when the component unmounts
        return () => {
            contentListener.remove();
        };
    }, []);

    return (
        <View style={styles.container}>
            <Text style={styles.header}>Shared Content</Text>
            
            {/* Render shared text if available */}
            {sharedText && (
                <View style={styles.contentCard}>
                    <Text style={styles.label}>Shared Text:</Text>
                    <Text style={styles.textContent}>{sharedText}</Text>
                </View>
            )}

            {/* Render shared image if available */}
            {sharedImageUri && (
                <View style={styles.contentCard}>
                    <Text style={styles.label}>Shared Image:</Text>
                    <Image 
                        source={{ uri: sharedImageUri }} 
                        style={styles.sharedImage}
                        resizeMode="cover"
                    />
                </View>
            )}

            {/* Fallback if no content was shared */}
            {!sharedText && !sharedImageUri && (
                <Text style={styles.emptyState}>No shared content received</Text>
            )}
        </View>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        padding: 20,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#f5f5f5',
    },
    header: {
        fontSize: 26,
        fontWeight: 'bold',
        marginBottom: 30,
        color: '#333',
    },
    contentCard: {
        width: '100%',
        marginBottom: 20,
        padding: 15,
        backgroundColor: 'white',
        borderRadius: 8,
        shadowColor: '#000',
        shadowOffset: { width: 0, height: 2 },
        shadowOpacity: 0.1,
        shadowRadius: 4,
        elevation: 3,
    },
    label: {
        fontSize: 16,
        fontWeight: '600',
        marginBottom: 8,
        color: '#555',
    },
    textContent: {
        fontSize: 14,
        lineHeight: 20,
        color: '#333',
    },
    sharedImage: {
        width: '100%',
        height: 250,
        borderRadius: 6,
    },
    emptyState: {
        fontSize: 16,
        color: '#888',
        textAlign: 'center',
    },
});

export default SharedContentScreen;
Step 3: Important Notes & Edge Cases
  • Image Permissions: For Android 10 and above, you'll need to handle image access properly. Add this permission to your AndroidManifest.xml if you haven't already:
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    
    For Android 13+, you can use READ_MEDIA_IMAGES instead.
  • Multiple Images: If you need to handle multiple shared images (using Intent.ACTION_SEND_MULTIPLE), modify the handleIntent method to get a list of Uris with intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM), then send an array to React Native instead of a single string.
  • Cold Start Handling: The code above handles both cold starts (app launched via share) and hot starts (app already running when share is triggered) by using onCreate and onNewIntent.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 04:14:36