Android 系统跳转实现分享功能(如 微信 朋友圈 QQ Q
CSDN地址: https://blog.csdn.net/shuai497331206
前者基本都是一个实现思路, 唯独微博实现比较特殊一点。
我对两个类做了封装 只要配置没问题, 拿去直接用。
先来一波配置
清单文件下
android:name="androidx.core.content.FileProvider"
android:authorities="包名.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths_public"/>
下的文件 Context.getExternalCacheDir目录下的目录-->
name="external_cache_path"
path="."/>
<!--配置root-path。这样子可以读取到sd卡和一些应用分身的目录,否则微信分身保存的图片,就会导致 java.lang.IllegalArgumentException: Failed to find configured root that contains /storage/emulated/999/tencent/MicroMsg/WeiXin/export1544062754693.jpg,在小米6的手机上微信分身有这个crash,华为没有
-->
name="root-path"
path=""/>
...
(3) network_security_config
<?xml version="1.0" encoding="utf-8"?>
因为是需要内容提供者 跳转三方应用的页面 所以必须要添加, 还有就是 android7.0以后的权限
保存图片下载到本地
package com.ggmall.ggb.personal.utils;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Calendar;
import java.util.List;
/**
* Created by ShinnyYang on 2020/2/26.
*/
public class Tools {
public static String IMAGE_NAME = "iv_share_";
public static int i = 0;
//根据网络图片url路径保存到本地
public static final File saveImageToSdCard(Context context, String image) {
boolean success = false;
File file = null;
try {
file = createStableImageFile(context);
Bitmap bitmap = null;
URL url = new URL(image);
HttpURLConnection conn = null;
conn = (HttpURLConnection) url.openConnection();
InputStream is = null;
is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
FileOutputStream outStream;
outStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
success = true;
} catch (Exception e) {
e.printStackTrace();
}
if (success) {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
context.sendBroadcast(mediaScanIntent);
return file;
} else {
return null;
}
}
//创建本地保存路径
public static File createStableImageFile(Context context) throws IOException {
i++;
String imageFileName =IMAGE_NAME + Calendar.getInstance().getTimeInMillis() + ".jpg";
File storageDir = new File(Environment.getExternalStorageDirectory(),
"DCIM");
// File storageDir = new File(context.getExternalCacheDir() + "shareImg");
// File storageDir = new File(Environment.getExternalStorageDirectory() + "/");
Log.i("info","=======保存路径====" + storageDir.getAbsolutePath());
if (!storageDir.exists()){
storageDir.mkdirs();
}
File image = new File(storageDir, imageFileName);
return image;
}
//判断是否安装了微信,QQ,QQ空间
public static boolean isAppAvilible(Context context,String mType) {
final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
Listpinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
if (pinfo != null) {
for (int i = 0; i
Stringpn=pinfo.get(i).packageName;
if(pn.equals(mType)) {
returntrue;
}
}
}
returnfalse;
}
publicstaticvoiddeletePic(Filefile){
if(file.isDirectory()){
File[]files=file.listFiles();
for(intj=0;j
Filef=files[j];
deletePic(f);
}
//file.delete();//如要保留文件夹,只删除文件,请注释这行
}else{
file.delete();
}
}
}
分享的主要部分,
package com.ggmall.ggb.personal.utils;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.widget.Toast;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by ShinnyYang on 2020/2/24.
*/
public class ShareUtils {
/**
* 微信7.0版本号,兼容处理微信7.0版本分享到朋友圈不支持多图片的问题
*/
private static final int VERSION_CODE_FOR_WEI_XIN_VER7 = 1380;
/**
* 微信包名
*/
public static final String PACKAGE_NAME_WEI_XIN = "com.tencent.mm";
public static ShareUtils shareUtils = null;
private Context context = null;
private Listfiles = new ArrayList<>();
public static ShareUtils Initialize() {
if (shareUtils == null) {
shareUtils = new ShareUtils();
}
return shareUtils;
}
public ShareUtils setContext(Context context) {
this.context = context;
files.clear();
return shareUtils;
}
public void shareQQ(String[] url) {
if (!Tools.isAppAvilible(context, "com.tencent.mobileqq")) {
Toast.makeText(context, "您还没有安装QQ", Toast.LENGTH_SHORT).show();
return;
}
ShareSave(url, 3);
}
public void shareWeiXin(final String[] url) {
if (!Tools.isAppAvilible(context, "com.tencent.mm")) {
Toast.makeText(context, "您还没有安装微信", Toast.LENGTH_SHORT).show();
return;
}
ShareSave(url, 0);
}
public void shareQZone(String[] url) {
if (!Tools.isAppAvilible(context, "com.tencent.mobileqq")) {
Toast.makeText(context, "您还没有安装QQ", Toast.LENGTH_SHORT).show();
return;
}
ShareSave(url, 2);
}
public void sharePYQ(String[] url) {
if (!Tools.isAppAvilible(context, "com.tencent.mm")) {
Toast.makeText(context, "您还没有安装微信", Toast.LENGTH_SHORT).show();
return;
}
ShareSave(url, 1);
}
public void shareWB(final String[] url) {
if (!Tools.isAppAvilible(context, "com.sina.weibo")) {
Toast.makeText(context, "您还没有安装微博", Toast.LENGTH_SHORT).show();
return;
}
ShareSave(url, 4);
}
public void ShareSave(final String[] url, final int type) {
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i
Filefile=null;
if(url[i].contains("http")) {
file=Tools.saveImageToSdCard(context,url[i]);
}else{
file=newFile(url[i]);
}
files.add(file);
}
ArrayListimageUris = new ArrayList();
for (File f : files) {
imageUris.add(Uri.fromFile(f));
}
if (type == 0) {
shareWXSomeImg(context, imageUris);
} else if (type == 1) {
shareweipyqSomeImg(context, imageUris);
} else if (type == 2) {
shareQZoneImg(context, imageUris);
} else if (type == 3) {
shareQQImg(context, imageUris);
} else {
shareWBImg(context, imageUris);
}
}
}).start();
}
private void shareweipyqSomeImg(final Context context, ArrayListuri) {
Intent shareIntent = new Intent();
shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//2添加图片数组
ArrayListimageUris = new ArrayList<>();
for (int i = 0; i
Uriurl=null;
try{
url=Uri.parse(android.provider.MediaStore.Images.
Media.insertImage(context.getContentResolver(),
files.get(i).getAbsolutePath(),files.get(i).getName(),null));
}catch(FileNotFoundExceptione) {
e.printStackTrace();
}
imageUris.add(url);
}
if(getVersionCode(context,PACKAGE_NAME_WEI_XIN)
// 微信7.0以下版本
shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM,imageUris);
}else{
// 微信7.0及以上版本,朋友圈只支持单张图片分享
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM,imageUris.get(0));
}
shareIntent.setType("image/*");
//3指定选择微信
ComponentNamecomponentName=newComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareToTimeLineUI");
shareIntent.setComponent(componentName);
//4开始分享
context.startActivity(Intent.createChooser(shareIntent, "分享图片"));
}
/**
* 拉起微信发送多张图片给好友
*/
privatevoidshareWXSomeImg(Contextcontext,ArrayListuri) {
Intent shareIntent = new Intent();
//1调用系统分析
shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//2添加图片数组
ArrayListimageUris = new ArrayList<>();
for (int i = 0; i
Uriurl=null;
try{
url=Uri.parse(android.provider.MediaStore.Images.
Media.insertImage(context.getContentResolver(),
files.get(i).getAbsolutePath(),files.get(i).getName(),null));
}catch(FileNotFoundExceptione) {
e.printStackTrace();
}
imageUris.add(url);
}
shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM,imageUris);
shareIntent.setType("image/*");
//3指定选择微信
ComponentNamecomponentName=newComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareImgUI");
shareIntent.setComponent(componentName);
//4开始分享
context.startActivity(Intent.createChooser(shareIntent, "分享图片"));
}
/**
* 拉起QQ发送多张图片给好友
*/
privatevoidshareQQImg(Contextcontext,ArrayListuri) {
Intent shareIntent = new Intent();
//1调用系统分析
shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//2添加图片数组
ArrayListimageUris = new ArrayList<>();
for (int i = 0; i
Uriurl=null;
try{
url=Uri.parse(android.provider.MediaStore.Images.
Media.insertImage(context.getContentResolver(),
files.get(i).getAbsolutePath(),files.get(i).getName(),null));
}catch(FileNotFoundExceptione) {
e.printStackTrace();
}
imageUris.add(url);
}
shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM,imageUris);
shareIntent.setType("image/*");
//3指定选择微信
ComponentNamecomponentName=newComponentName("com.tencent.mobileqq", "com.tencent.mobileqq.activity.JumpActivity");
shareIntent.setComponent(componentName);
//4开始分享
context.startActivity(Intent.createChooser(shareIntent, "分享图片"));
}
/**
* 拉起QQ发送多张图片给好友
*/
privatevoidshareQZoneImg(Contextcontext,ArrayListuri) {
Intent shareIntent = new Intent();
//1调用系统分析
shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//2添加图片数组
ArrayListimageUris = new ArrayList<>();
for (int i = 0; i
Uriurl=null;
try{
url=Uri.parse(android.provider.MediaStore.Images.
Media.insertImage(context.getContentResolver(),
files.get(i).getAbsolutePath(),files.get(i).getName(),null));
}catch(FileNotFoundExceptione) {
e.printStackTrace();
}
imageUris.add(url);
}
shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM,imageUris);
shareIntent.setType("image/*");
//3指定选择微信
ComponentNamecomponentName=newComponentName("com.qzone", "com.qzonex.module.operation.ui.QZonePublishMoodActivity");
shareIntent.setComponent(componentName);
//4开始分享
context.startActivity(Intent.createChooser(shareIntent, "分享图片"));
}
/**
* 拉起微博发送多张图片给好友
*/
privatevoidshareWBImg(Contextcontext,ArrayListuri) {
Intent shareIntent = new Intent();
//1调用系统分析
shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//2添加图片数组
ArrayListimageUris = new ArrayList<>();
for (int i = 0; i
Uriurl=null;
try{
url=Uri.parse(android.provider.MediaStore.Images.
Media.insertImage(context.getContentResolver(),
files.get(i).getAbsolutePath(),files.get(i).getName(),null));
}catch(FileNotFoundExceptione) {
e.printStackTrace();
}
imageUris.add(url);
}
shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM,imageUris);
shareIntent.setType("image/*");
//3指定选择微信
//ComponentNamecomponentName=newComponentName("com.sina.weibo", "com.sina.weibo.activity.JumpActivity");
//shareIntent.setComponent(componentName);
shareIntent.setPackage("com.sina.weibo");
//4开始分享
context.startActivity(Intent.createChooser(shareIntent, "分享图片"));
}
/**
* 获取制定包名应用的版本的versionCode
*
* @paramcontext
* @param
* @return
*/
publicstaticintgetVersionCode(Contextcontext,StringpackageName) {
try{
PackageManagermanager=context.getPackageManager();
PackageInfoinfo=manager.getPackageInfo(packageName,0);
intversion=info.versionCode;
returnversion;
}catch(Exceptione) {
e.printStackTrace();
return0;
}
}
}
使用时候 (切记 切记 切记 图片必须是下载到本地的!!!)
动态申请权限
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
//动态获取内存存储权限
public void verifyStoragePermissions(Activity activity) {
int permission = ActivityCompat.checkSelfPermission(activity,
Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
if (!ActivityCompat.shouldShowRequestPermissionRationale(ShareDemoActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
ActivityCompat.requestPermissions(ShareDemoActivity.this,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE);
}
ActivityCompat.requestPermissions(ShareDemoActivity.this,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE);
}
while ((ContextCompat.checkSelfPermission(ShareDemoActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE))!= PackageManager.PERMISSION_GRANTED) {
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
}
完成!!!!!
CSDN地址: https://blog.csdn.net/shuai497331206