原生一鍵分享(系統(tǒng)默認(rèn))
Intent imageIntent = new Intent(Intent.ACTION_SEND);
imageIntent.setType("image/jpeg");
imageIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(path));
startActivity(Intent.createChooser(imageIntent, "分享"));
自定義分享功能跳轉(zhuǎn)
1.判斷是否安裝指定app
public static boolean isInstallApp(Context context, String app_package) {
final PackageManager packageManager = context.getPackageManager();
List<PackageInfo> pInfo = packageManager.getInstalledPackages(0);
if (pInfo != null) {
for (int i = 0; i < pInfo.size(); i++) {
String pn = pInfo.get(i).packageName;
if (app_package.equals(pn)) {
return true;
}
}
}
return false;
}
2.分享圖片給QQ好友
public static void shareImageToQQ(Context mContext, String bitmap) {
if (isInstallApp(mContext, PlatformUtil.PACKAGE_MOBILE_QQ)) {
try {
// Uri uriToImage = Uri.parse(MediaStore.Images.Media.insertImage(
// mContext.getContentResolver(), bitmap, null, null));
Uri uriToImage = Uri.parse(bitmap);
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, uriToImage);
shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
shareIntent.setType("image/*");
// 遍歷所有支持發(fā)送圖片的應(yīng)用穿剖。找到需要的應(yīng)用
ComponentName componentName = new ComponentName(PACKAGE_MOBILE_QQ, "com.tencent.mobileqq.activity.JumpActivity");
shareIntent.setComponent(componentName);
// mContext.startActivity(shareIntent);
mContext.startActivity(Intent.createChooser(shareIntent, "Share"));
} catch (Exception e) {
// ContextUtil.getInstance().showToastMsg("分享圖片到**失敗");
}
} else {
Toast.makeText(mContext, "您需要安裝QQ客戶端", Toast.LENGTH_LONG).show();
}
/*
之前有遇到在分享QQ和微信的時(shí)候蚤蔓,發(fā)現(xiàn)只要QQ或微信在打開的情況下,再調(diào)用分享只是打開了QQ和微信糊余,卻沒有調(diào)用選擇分享聯(lián)系人的情況
解決辦法如下:
mActivity.startActivity(intent);//如果微信或者QQ已經(jīng)喚醒或者打開秀又,這樣只能喚醒微信单寂,不能分享
請(qǐng)使用 mActivity.startActivity(Intent.createChooser(intent, "Share"));
*/
}
3.直接分享圖片到微信好友
public static void shareWechatFriend(Context mContext, String picFile) {
if (isInstallApp(mContext, PlatformUtil.PACKAGE_WECHAT)) {
Intent intent = new Intent();
ComponentName cop = new ComponentName(PACKAGE_WECHAT, "com.tencent.mm.ui.tools.ShareImgUI");
intent.setComponent(cop);
intent.setAction(Intent.ACTION_SEND);
intent.setType("image/*");
Uri uri = null;
if (picFile != null) {
//這部分代碼主要功能是判斷了下文件是否存在,在android版本高過7.0(包括7.0版本)
// 當(dāng)前APP是不能直接向外部應(yīng)用提供file開頭的的文件路徑吐辙,需要通過FileProvider轉(zhuǎn)換一下宣决。否則在7.0及以上版本手機(jī)將直接crash。
try {
ApplicationInfo applicationInfo = mContext.getApplicationInfo();
int targetSDK = applicationInfo.targetSdkVersion;
if (targetSDK >= Build.VERSION_CODES.N && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
uri = Uri.parse(MediaStore.Images.Media.insertImage(mContext.getContentResolver(), new File(picFile).getAbsolutePath(), "pangu", null));
} else {
uri = Uri.fromFile(new File(picFile));
}
intent.putExtra(Intent.EXTRA_STREAM, uri);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (getVersionCode(mContext, PACKAGE_WECHAT) > VERSION_CODE_FOR_WEI_XIN_VER7) {
// 微信7.0及以上版本
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, uri);
}
// context.startActivity(intent);
mContext.startActivity(Intent.createChooser(intent, "Share"));
} else {
Toast.makeText(mContext, "您需要安裝微信客戶端", Toast.LENGTH_LONG).show();
}
}
4.直接分享文本和圖片到微信朋友圈
/**
* 直接分享文本和圖片到微信朋友圈
* 在分享微信朋友圈的時(shí)候需要注意一點(diǎn)昏苏,分享的圖片要保存在微信可獲取到的目錄下
* 一定不能保存在/data/data/****這個(gè)內(nèi)置目錄中尊沸,否則將獲取不到圖片報(bào)“獲取不到圖片資源,.....”導(dǎo)致分享失敗捷雕。
*/
public static void shareWechatMoment(Context context, String picFile) {
if (isInstallApp(context, PlatformUtil.PACKAGE_WECHAT)) {
Intent intent = new Intent();
//分享精確到微信的頁(yè)面椒丧,朋友圈頁(yè)面壹甥,或者選擇好友分享頁(yè)面
ComponentName comp = new ComponentName(PACKAGE_WECHAT, "com.tencent.mm.ui.tools.ShareToTimeLineUI");
intent.setComponent(comp);
intent.setAction(Intent.ACTION_SEND);
intent.setType("image/*");
//添加Uri圖片地址
Uri uri = null;
if (picFile != null) {
try {
ApplicationInfo applicationInfo = context.getApplicationInfo();
int targetSDK = applicationInfo.targetSdkVersion;
if (targetSDK >= Build.VERSION_CODES.N && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
uri = Uri.parse(MediaStore.Images.Media.insertImage(context.getContentResolver(), new File(picFile).getAbsolutePath(), "pangu", null));
} else {
uri = Uri.fromFile(new File(picFile));
}
intent.putExtra(Intent.EXTRA_STREAM, uri);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (getVersionCode(context, PACKAGE_WECHAT) > VERSION_CODE_FOR_WEI_XIN_VER7) {
// 微信7.0及以上版本
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, uri);
}
context.startActivity(intent);
} else {
Toast.makeText(context, "您需要安裝微信客戶端", Toast.LENGTH_LONG).show();
}
}
5.分享多圖片到微信朋友圈
/**
* 分享多圖片到微信朋友圈
*
* @param bmp 分享的圖片的Bitmap對(duì)象
*/
public void shareImageToWechat(Bitmap bmp, Context mContext) {
File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsoluteFile();
String fileName = "share";
File appDir = new File(file, fileName);
if (!appDir.exists()) {
appDir.mkdirs();
}
fileName = System.currentTimeMillis() + ".jpg";
File currentFile = new File(appDir, fileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(currentFile);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
ArrayList<Uri> uris = new ArrayList<>();
Uri uri = null;
try {
ApplicationInfo applicationInfo = mContext.getApplicationInfo();
int targetSDK = applicationInfo.targetSdkVersion;
if (targetSDK >= Build.VERSION_CODES.N && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
uri = Uri.parse(android.provider.MediaStore.Images.Media.insertImage(mContext.getContentResolver(), currentFile.getAbsolutePath(), fileName, null));
} else {
uri = Uri.fromFile(new File(currentFile.getPath()));
}
uris.add(uri);
} catch (Exception ex) {
}
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
ComponentName comp = new ComponentName(PACKAGE_WECHAT, "com.tencent.mm.ui.tools.ShareToTimeLineUI");
intent.setComponent(comp);
intent.setType("image/*");
// intent.putExtra("Kdescription", content);
if (getVersionCode(mContext, PACKAGE_WECHAT) < VERSION_CODE_FOR_WEI_XIN_VER7) {
// 微信7.0以下版本
intent.setAction(Intent.ACTION_SEND_MULTIPLE);
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
} else {
// 微信7.0及以上版本
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, uri);
}
mContext.startActivity(intent);
}
6.分享到新浪微博
/**
* 分享到新浪微博
*
* @param photoPath 文件路徑
*/
public static void shareToSinaFriends(Context context, String photoPath) {
if (!isInstallApp(context, PlatformUtil.PACKAGE_SINA)) {
Toast.makeText(context, "新浪微博沒有安裝救巷!", Toast.LENGTH_SHORT).show();
return;
}
File file = new File(photoPath);
if (!file.exists()) {
String tip = "文件不存在";
Toast.makeText(context, tip + " path = " + photoPath, Toast.LENGTH_LONG).show();
return;
}
Intent intent = new Intent(Intent.ACTION_SEND);
// 使用以下兩種type有一定的區(qū)別,"text/plain"分享給指定的粉絲或好友 句柠;"image/*"分享到微博內(nèi)容,下面這兩個(gè)設(shè)置type的代碼必須寫在查詢語(yǔ)句前面浦译,否則找不到帶有分享功能的應(yīng)用。
// intent.setType("text/plain");
intent.setType("image/*");// 分享文本|文本+圖片|圖片 到微博內(nèi)容時(shí)使用
PackageManager packageManager = context.getPackageManager();
List<ResolveInfo> matchs = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
ResolveInfo resolveInfo = null;
for (ResolveInfo each : matchs) {
String pkgName = each.activityInfo.applicationInfo.packageName;
if ("com.sina.weibo".equals(pkgName)) {
resolveInfo = each;
break;
}
}
intent.setClassName(PACKAGE_SINA, resolveInfo.activityInfo.name);// 這里在使用resolveInfo的時(shí)候需要做判空處理防止crash
intent.putExtra(Intent.EXTRA_TEXT, "Test Text String !!");
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
context.startActivity(intent);
}
完整工具類
/**
* Created by zhangbowen on 2019/4/3.
* 分享功能工具類
**/
public class PlatformUtil {
public static final String PACKAGE_WECHAT = "com.tencent.mm";
public static final String PACKAGE_MOBILE_QQ = "com.tencent.mobileqq";
public static final String PACKAGE_QZONE = "com.qzone";
public static final String PACKAGE_SINA = "com.sina.weibo";
/**
* 微信7.0版本號(hào)溯职,兼容處理微信7.0版本分享到朋友圈不支持多圖片的問題
*/
private static final int VERSION_CODE_FOR_WEI_XIN_VER7 = 1380;
// 判斷是否安裝指定app
public static boolean isInstallApp(Context context, String app_package) {
final PackageManager packageManager = context.getPackageManager();
List<PackageInfo> pInfo = packageManager.getInstalledPackages(0);
if (pInfo != null) {
for (int i = 0; i < pInfo.size(); i++) {
String pn = pInfo.get(i).packageName;
if (app_package.equals(pn)) {
return true;
}
}
}
return false;
}
/**
* 分享圖片給QQ好友
*
* @param bitmap 文件路徑
*/
public static void shareImageToQQ(Context mContext, String bitmap) {
if (isInstallApp(mContext, PlatformUtil.PACKAGE_MOBILE_QQ)) {
try {
// Uri uriToImage = Uri.parse(MediaStore.Images.Media.insertImage(
// mContext.getContentResolver(), bitmap, null, null));
Uri uriToImage = Uri.parse(bitmap);
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, uriToImage);
shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
shareIntent.setType("image/*");
// 遍歷所有支持發(fā)送圖片的應(yīng)用精盅。找到需要的應(yīng)用
ComponentName componentName = new ComponentName(PACKAGE_MOBILE_QQ, "com.tencent.mobileqq.activity.JumpActivity");
shareIntent.setComponent(componentName);
// mContext.startActivity(shareIntent);
mContext.startActivity(Intent.createChooser(shareIntent, "Share"));
} catch (Exception e) {
// ContextUtil.getInstance().showToastMsg("分享圖片到**失敗");
}
} else {
Toast.makeText(mContext, "您需要安裝QQ客戶端", Toast.LENGTH_LONG).show();
}
/*
之前有同學(xué)說在分享QQ和微信的時(shí)候,發(fā)現(xiàn)只要QQ或微信在打開的情況下谜酒,再調(diào)用分享只是打開了QQ和微信叹俏,卻沒有調(diào)用選擇分享聯(lián)系人的情況
解決辦法如下:
mActivity.startActivity(intent);//如果微信或者QQ已經(jīng)喚醒或者打開,這樣只能喚醒微信僻族,不能分享
請(qǐng)使用 mActivity.startActivity(Intent.createChooser(intent, "Share"));
*/
}
/**
* 直接分享圖片到微信好友
*
* @param picFile 文件路徑
*/
public static void shareWechatFriend(Context mContext, String picFile) {
if (isInstallApp(mContext, PlatformUtil.PACKAGE_WECHAT)) {
Intent intent = new Intent();
ComponentName cop = new ComponentName(PACKAGE_WECHAT, "com.tencent.mm.ui.tools.ShareImgUI");
intent.setComponent(cop);
intent.setAction(Intent.ACTION_SEND);
intent.setType("image/*");
Uri uri = null;
if (picFile != null) {
//這部分代碼主要功能是判斷了下文件是否存在粘驰,在android版本高過7.0(包括7.0版本)
// 當(dāng)前APP是不能直接向外部應(yīng)用提供file開頭的的文件路徑,需要通過FileProvider轉(zhuǎn)換一下述么。否則在7.0及以上版本手機(jī)將直接crash蝌数。
try {
ApplicationInfo applicationInfo = mContext.getApplicationInfo();
int targetSDK = applicationInfo.targetSdkVersion;
if (targetSDK >= Build.VERSION_CODES.N && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
uri = Uri.parse(MediaStore.Images.Media.insertImage(mContext.getContentResolver(), new File(picFile).getAbsolutePath(), "pangu", null));
} else {
uri = Uri.fromFile(new File(picFile));
}
intent.putExtra(Intent.EXTRA_STREAM, uri);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (getVersionCode(mContext, PACKAGE_WECHAT) > VERSION_CODE_FOR_WEI_XIN_VER7) {
// 微信7.0及以上版本
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, uri);
}
// context.startActivity(intent);
mContext.startActivity(Intent.createChooser(intent, "Share"));
} else {
Toast.makeText(mContext, "您需要安裝微信客戶端", Toast.LENGTH_LONG).show();
}
}
/**
* 直接分享文本和圖片到微信朋友圈
* 在分享微信朋友圈的時(shí)候需要注意一點(diǎn),分享的圖片要保存在微信可獲取到的目錄下
* 一定不能保存在/data/data/****這個(gè)內(nèi)置目錄中度秘,否則將獲取不到圖片報(bào)“獲取不到圖片資源顶伞,.....”導(dǎo)致分享失敗。
*/
public static void shareWechatMoment(Context context, String picFile) {
if (isInstallApp(context, PlatformUtil.PACKAGE_WECHAT)) {
Intent intent = new Intent();
//分享精確到微信的頁(yè)面剑梳,朋友圈頁(yè)面唆貌,或者選擇好友分享頁(yè)面
ComponentName comp = new ComponentName(PACKAGE_WECHAT, "com.tencent.mm.ui.tools.ShareToTimeLineUI");
intent.setComponent(comp);
intent.setAction(Intent.ACTION_SEND);
intent.setType("image/*");
//添加Uri圖片地址--用于添加多張圖片
Uri uri = null;
if (picFile != null) {
try {
ApplicationInfo applicationInfo = context.getApplicationInfo();
int targetSDK = applicationInfo.targetSdkVersion;
if (targetSDK >= Build.VERSION_CODES.N && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
uri = Uri.parse(MediaStore.Images.Media.insertImage(context.getContentResolver(), new File(picFile).getAbsolutePath(), "pangu", null));
} else {
uri = Uri.fromFile(new File(picFile));
}
intent.putExtra(Intent.EXTRA_STREAM, uri);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (getVersionCode(context, PACKAGE_WECHAT) > VERSION_CODE_FOR_WEI_XIN_VER7) {
// 微信7.0及以上版本
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, uri);
}
context.startActivity(intent);
} else {
Toast.makeText(context, "您需要安裝微信客戶端", Toast.LENGTH_LONG).show();
}
}
/**
* 分享到新浪微博
*
* @param photoPath 文件路徑
*/
public static void shareToSinaFriends(Context context, String photoPath) {
if (!isInstallApp(context, PlatformUtil.PACKAGE_SINA)) {
Toast.makeText(context, "新浪微博沒有安裝!", Toast.LENGTH_SHORT).show();
return;
}
File file = new File(photoPath);
if (!file.exists()) {
String tip = "文件不存在";
Toast.makeText(context, tip + " path = " + photoPath, Toast.LENGTH_LONG).show();
return;
}
Intent intent = new Intent(Intent.ACTION_SEND);
// 使用以下兩種type有一定的區(qū)別垢乙,"text/plain"分享給指定的粉絲或好友 挠锥;"image/*"分享到微博內(nèi)容,下面這兩個(gè)設(shè)置type的代碼必須寫在查詢語(yǔ)句前面,否則找不到帶有分享功能的應(yīng)用侨赡。
// intent.setType("text/plain");
intent.setType("image/*");// 分享文本|文本+圖片|圖片 到微博內(nèi)容時(shí)使用
PackageManager packageManager = context.getPackageManager();
List<ResolveInfo> matchs = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
ResolveInfo resolveInfo = null;
for (ResolveInfo each : matchs) {
String pkgName = each.activityInfo.applicationInfo.packageName;
if ("com.sina.weibo".equals(pkgName)) {
resolveInfo = each;
break;
}
}
intent.setClassName(PACKAGE_SINA, resolveInfo.activityInfo.name);// 這里在使用resolveInfo的時(shí)候需要做判空處理防止crash
intent.putExtra(Intent.EXTRA_TEXT, "Test Text String !!");
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
context.startActivity(intent);
}
/**
* 分享多圖片到微信朋友圈
*
* @param bmp 分享的圖片的Bitmap對(duì)象
*/
public void shareImageToWechat(Bitmap bmp, Context mContext) {
File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsoluteFile();
String fileName = "share";
File appDir = new File(file, fileName);
if (!appDir.exists()) {
appDir.mkdirs();
}
fileName = System.currentTimeMillis() + ".jpg";
File currentFile = new File(appDir, fileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(currentFile);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
ArrayList<Uri> uris = new ArrayList<>();
Uri uri = null;
try {
ApplicationInfo applicationInfo = mContext.getApplicationInfo();
int targetSDK = applicationInfo.targetSdkVersion;
if (targetSDK >= Build.VERSION_CODES.N && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
uri = Uri.parse(android.provider.MediaStore.Images.Media.insertImage(mContext.getContentResolver(), currentFile.getAbsolutePath(), fileName, null));
} else {
uri = Uri.fromFile(new File(currentFile.getPath()));
}
uris.add(uri);
} catch (Exception ex) {
}
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
ComponentName comp = new ComponentName(PACKAGE_WECHAT, "com.tencent.mm.ui.tools.ShareToTimeLineUI");
intent.setComponent(comp);
intent.setType("image/*");
// intent.putExtra("Kdescription", content);
if (getVersionCode(mContext, PACKAGE_WECHAT) < VERSION_CODE_FOR_WEI_XIN_VER7) {
// 微信7.0以下版本
intent.setAction(Intent.ACTION_SEND_MULTIPLE);
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
} else {
// 微信7.0及以上版本
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, uri);
}
mContext.startActivity(intent);
}
/**
* 獲取制定包名應(yīng)用的版本的versionCode
*
* @param context
* @param
* @return
*/
private static int getVersionCode(Context context, String packageName) {
try {
PackageManager manager = context.getPackageManager();
PackageInfo info = manager.getPackageInfo(packageName, 0);
int version = info.versionCode;
return version;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
}
劃重點(diǎn)1妥狻A宦隆!
之前有遇到在分享QQ和微信的時(shí)候蓖宦,發(fā)現(xiàn)只要QQ或微信在打開的情況下齐婴,再調(diào)用分享只是打開了QQ和微信,卻沒有調(diào)用選擇分享聯(lián)系人的情況
解決辦法如下:
mActivity.startActivity(intent);//如果微信或者QQ已經(jīng)喚醒或者打開稠茂,這樣只能喚醒微信柠偶,不能分享
請(qǐng)使用 mActivity.startActivity(Intent.createChooser(intent, "Share"));
在 微信7.0以下版本發(fā)送多圖片有問題需要添加這個(gè)判斷
if (getVersionCode(mContext, PACKAGE_WECHAT) < VERSION_CODE_FOR_WEI_XIN_VER7) {
// 微信7.0以下版本
intent.setAction(Intent.ACTION_SEND_MULTIPLE);
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
} else {
// 微信7.0及以上版本
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, uri);
}
希望有遇到問題的同學(xué)大家一起多多交流,都看到這里了何不留下你的小心心呢睬关。