使用Intent共享文本、图片、视频等资源

来源:互联网 发布:淘宝助理批量改价格 编辑:程序博客网 时间:2024/05/09 05:08
Tweet

Very often, you might want to enable the ability for users to share some content (either text, link or an image) from your Android app. Users can share the content using email, twitter, Facebook, sms or through numerous other ways.

The users might already have installed some custom apps for each one of the above service. So instead of coding all these again, it would be really nice (for both your users as well as for you as a developer) if you can invoke any one of these apps, where users want to share content from your app.

Sharing text

Android provides a built-in Intent called ACTION_SEND for this purpose. Using it in your app is very easy. All you have to do is to use the following couple of lines.

Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/html");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, Html.fromHtml("<p>This is the text that will be shared.</p>"));
startActivity(Intent.createChooser(sharingIntent,"Share using"));
view rawSharingText.javaThis Gist brought to you by GitHub.

In my phone, it invokes the following dialog box listing the apps that have registered to get notification for this intent.

sharing-content-android

Sharing binary objects (Images, videos etc.)

In addition to supporting text, this intent also supports sharing images or any binary content. All you have to do is to set the appropriate mime type and then pass the binary data by calling the putExtra method.

Intent sharingIntent = new Intent(Intent.ACTION_SEND);
Uri screenshotUri = Uri.parse(path);

sharingIntent.setType("image/png");
sharingIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
startActivity(Intent.createChooser(sharingIntent, "Share image using"));
view rawSharingImage.javaThis Gist brought to you by GitHub.

Registering for the Intent

If you want your app to be listed when this Intent is called, then you have to add an intent filter in your manifest.xml file

<intent-filter>
   <action android:name="android.intent.action.SEND" />
   <category android:name="android.intent.category.DEFAULT" />
   <data android:mimeType="image/*" />
</intent-filter>
view rawmanifest.xmlThis Gist brought to you by GitHub.

android:mimeType specifies the mime type which you are interested in listening.

Happy sharing ;)

原创粉丝点击