Android Receiving Content from Other Apps [从其他APP接收分享数据]

来源:互联网 发布:淘宝官方折扣 编辑:程序博客网 时间:2024/05/16 14:21

您的应用程序可以发送数据给其他应用程序,同样也很容易接收其他应用程序发送的数据。

1.Update Your Manifest  [更新你的AndroidManifest.xml文件]

Intent filters会通知系统一个程序控件会接受 哪些intents 。如下示例code:
<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>
此Activity会接收的数据:单张图片,文本,多张图片。
当另外一个程序通过startActivity()传送创建的Intent来 
尝试分享一些如上描述的东西的时候,你的程序就会被呈现在一个选择列表里供用户选择。如果用户选择了你的程序,相应的activity就会响应开启,这个时候就该你处理获取到的数据了。

2.Handle the Incoming Content [处理传入的数据]

通过调用getIntent()方法来获取到Intent对象,从而获取intent传递过来的数据。sample code:
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    }}

注意:接收的数据 有很大的不确定性,处理数据的操作不要放在UI线程里,最好单独创建一个线程进行数据的处理。

原创粉丝点击