其实就是把应用加入分享列表里去,系统本身就有分享功能,只不过是分享文本和图片,如果系统把链接也可以分享,那开发者们就不用再接入第三方分享功能了。
1.首先如何拉起下面列表呢?
//分享文字
public void shareText(View view) {
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_TEXT, "This is my shareText");
shareIntent.setType("text/plain");
startActivity(Intent.createChooser(shareIntent, "分享到"));
}
//分享单张图片
public void shareImage(View view) {
String imagePath = Environment.getExternalStorageDirectory() + File.separator + "sharePic.jpg";
//由文件得到uri
Uri imageUri = Uri.fromFile(new File(imagePath));
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
shareIntent.setType("image/*");
startActivity(Intent.createChooser(shareIntent, "分享到"));
}
//分享多张图片
public void shareMultipleImage(View view) {
ArrayList<uri> uriList = new ArrayList<>();
String path = Environment.getExternalStorageDirectory() + File.separator;
uriList.add(Uri.fromFile(new File(path+"sharePic1.jpg")));
uriList.add(Uri.fromFile(new File(path+"sharePic2.jpg")));
uriList.add(Uri.fromFile(new File(path+"sharePic3.jpg")));
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uriList);
shareIntent.setType("image/*");
startActivity(Intent.createChooser(shareIntent, "分享到"));
}
}
2.首先如何加入列表呢?
<activity android:name=".ShareDemoActivity" android:label="分享到">
<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>
3,如何处理收到的数据:
Intent intent = getIntent();
String action = intent.getAction();
String type = intent.getType();
if (Intent.ACTION_SEND.equals(action) && type != null) {
if ("text/plain".equals(type)) {
String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
if (sharedText != null) {
text.setText(sharedText);
}
} else if (type.startsWith("image/")) {
Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
if (imageUri != null) {
image.setImageURI(imageUri);
}
}
} else if (Intent.ACTION_SEND_MULTIPLE.equals(action) && type != null) {
if (type.startsWith("image/")) {
ArrayList<Uri> imageUris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
if (imageUris != null) {
if (imageUris.size() > 1) {
image.setImageURI(imageUris.get(0));
}
}
}
}