(三)高级篇____5、内容分享——从其他的App接收内容
原文链接:http://docs.eoeandroid.com/training/sharing/receive.html
作者:smilysas
完成时间:2012.09.05
从其他程序中接收内容
应用程序能够发送数据到其他程序,同样,也能够接收从其他程序发送过来的数据。需要考虑的是用户与应用程序如何进行交互,你想要从其他程序接收哪些数据类型。例如,一个社交网络程序会希望能够从其他程序接受文本数据,像一个有趣的网址链接。Google+ Android application客户端会接受文本数据与单张或者多张图片。通过这个程序,用户可以很方便地从Gallery程序选择一张图片来启动Google+进行发布。
更新Manifest文件
Intent filters通知Android系统一个程序会接受哪些数据。和Send Content to Other Apps Using Intents一课中用ACTION_SEND动作生成一个intent一样,可以通过在manifest文件中用 <intent-filter> 元素标签来定义intent filters以表明程序能够接收哪些intent。下面是个例子,定义的activity分别指定了可以接收文本、单张图片或者多张图片。
<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>
注意:更多关于intent和intent filter的信息,请参考Intents and Intent Filters
当另外一个程序通过创建intent并传给startActivity()以尝试分享一些东西时,你的程序会被呈现在一个列表里面让用户进行选择。如果用户选择了你的程序,相应的activity就应该被调用开启(上面例子中的.ui.MyActivity),这个时候就是你如何处理获取到的数据的问题了。
处理接收到的数据
为了处理从Intent传过来的数据,可以通过调用getIntent()方法来获取到Intent对象。一旦获取该对象,就可以对里面的数据进行判断,从而决定下一步应该做什么。请记住,如果一个activity可以被其他的程序启动,你需要在检查intent的时候考虑这种情况。
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 } }
敬告:因为你无法知道其他程序发送过来的数据内容是文本还是其他的数据,例如设置错误的MIME类型或者发送了过大的图片,因此你需要避免在UI线程里面而是在单独的线程里去处理那些获取到的二进制数据。
更新UI可以像更新EditText一样简单,也可以是比过滤出感兴趣的图片还复杂的操作。因此,接下来会发生什么事情最终要取决于你的程序。

浙公网安备 33010602011771号