首先, 需要在AndroidManifest里为你的应用中需要接收分享的Activity添加一个过滤器<intent-filter>,
<activity
android:name="com.xxx.MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar"
android:screenOrientation="portrait">
<!-- 默认的过滤器 -->
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<!-- 添加接受分享指令的过滤器 -->
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<!-- 指定分享类型(mimetype)为纯文本 -->
<data android:mimeType="text/plain" />
</intent-filter>
</activity>
接下来是Activity中的Java代码控制,
//写一个初始化函数init()放在onCreate()里
//init()里写一个try catch接收分享的intent
//使用try catch 防止intent传入为空时崩溃
try {
Intent intent = getIntent();
if (intent.getType().equals("text/plain")) {
handleSendText(intent); // Handle text being sent
}
} catch (Exception e) {
e.printStackTrace();
Log.d("Error", "noIntent");
}
//处理接收的分享数据
public void handleSendText(Intent intent) {
String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
if (sharedText != null) {
String id = sharedText.substring(sharedText.indexOf("xx"), sharedText.indexOf("xx"));
//从字符串里取出id
editText.setText(id);
}
}
官方详细文档
Google Developer – Intent与intent-filter详解
Google Developer – Receiving Simple Data from Other Apps