让别人把内容分享到你的APP里,可能你很好奇这是什么意思,不过相信你也常用过这个功能,例如你在看Youtube,在用Facebook或者想要上传和传送文件的时候,都有一个分享的功能,这个时候如果可以把你的APP加上去,就可以把内容直接分享到你的APP里面啦!
看看上面的这张图就可以大致上了解我们要实作的效果啦,但是这是怎么做出来的呢?步骤其实很简单,我们来一步一步完成吧!
首先,要先更新Manifest檔案:
<activity android:name=".ui.MyActivity" >
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/*" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND_MULTIPLE" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/*" />
</intent-filter>
</activity>
|
加入好後就可以在別的App分享頁面的時候看到你的APP了,接下來我們要在自己的APP上面接收資訊,可以接收的資訊分別有文字和圖像。
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 if (type.startsWith("image/")) {
handleSendImage(intent); // Handle single image being sent
}
} else if (Intent.ACTION_SEND_MULTIPLE.equals(action) && type != null) {
if (type.startsWith("image/")) {
handleSendMultipleImages(intent); // Handle multiple images 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
}
}
void handleSendImage(Intent intent) {
Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
if (imageUri != null) {
// Update UI to reflect image being shared
}
}
void handleSendMultipleImages(Intent intent) {
ArrayList<Uri> imageUris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
if (imageUris != null) {
// Update UI to reflect multiple images being shared
}
}
|
要注意傳入的資訊有可能是病毒資訊,所以要小心注意!
如果想要從自身的App傳資訊給別的App,做法也是類似,可以參考這篇官方的文檔:https://developer.android.com/training/sharing/send
DATE: 2月 11, 2019
AUTHOR: yayapipi