[Android] Make your app appear in the system share list
Translated by AI from 中文 · View original
This post was recovered from Internet Archive snapshots; some images may be lost.
First, in AndroidManifest, you need to add a filter<intent-filter> for the Activity in your app that needs to receive shares,
<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>
Next is the Java code control in the Activity,
//写一个初始化函数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);
}
}
Official detailed documentation
Google Developer – Detailed explanation of Intent and intent-filter
Google Developer – Receiving Simple Data from Other Apps