原文地址:Receiving Simple Data from Other Apps
如同你的应用程序可以向别的应用发送数据一样,你也可以从其他应用获取数据。好好想想用户和你的APP交互的时候想从其他APP接收些什么东西,比如一个社交类APP可能会对其他应用传来的URL之类的文本信息感兴趣。比如有个叫Google+的东西可以接受文本和图片,可以很方便地把这些信息组装成一条待发送的新动态。
修改Manifest文件 //update your manifest
Intent filter告诉系统应用的组件愿意接收哪种信息,给这个intent-filter添加要响应的特定的Action,就像构建Intent的时候传递Action一样。
比如,一个接收文本、单张图片和多张图片的Activity,它在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>
有了这样的声明后,当别的程序尝试通过构建Intent的方式分享上面声明的数据类型的时候,你的APP就会出现在选择列表里。当然这跟该类型是否有default选项和发起分享的一方是否使用了Intent.createChooser()有关。
处理接收到内容 //handle the incoming intent
直接在Activity中使用getIntent()方法获取启动这个Activity的Intent。一旦获取到了这个Intent,你就可以决定下一步要做些啥了,通过获取这个Intent的Action和Type就可以愉快地搞事情了。
下面是从原文摘录的代码,当然上面那段代码也是,orz
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)) { // Handle text being sent } else if (type.startsWith("image/")) { // Handle single image being sent } } else if (Intent.ACTION_SEND_MULTIPLE.equals(action) && type != null) { if (type.startsWith("image/")) { // Handle multiple images being sent } } else { // Handle other intents, such as being started from the home screen } ... }
Caution:
检查接收到的数据的时候要格外注意,你永远无法猜到别人会给你传过来什么奇怪的东西。比如,错误的MIME信息,文件类型都不对就很不优雅了,或者可能传过来的文件特别大,可能会让你卡顿崩溃之类的。还有,处理二进制原始数据的时候记得放在一个新线程里,不然的话可能会阻塞UI线程。
Happy Coding @Boiler