欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Android——intent分享图片到微信好友、朋友圈、QQ

程序员文章站 2022-03-12 20:01:08
直接上代码,工具类import android.content.ComponentName;import android.content.ContentValues;import android.content.Context;import android.content.Intent;import android.content.pm.PackageInfo;import android.database.Cursor;import android.net.Uri;import and...

直接上代码,工具类

import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

public class WechatShareUtil {

    /**
     * 分享多图片到QQ
     */
    public static void sharePicToQQNoSDK(Context context, List<String> paths) {
        if (isInstallQQ(context)) {

            Intent shareIntent = new Intent();
            shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
            shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            shareIntent.setType("image/*");
            // 遍历所有支持发送图片的应用。找到需要的应用
            ComponentName componentName = new ComponentName("com.tencent.mobileqq", "com.tencent.mobileqq.activity.JumpActivity");
            shareIntent.setComponent(componentName);

            ArrayList<Uri> imageList = new ArrayList<>();

            for (String picPath : paths) {
                Log.e("backinfo", picPath);
                File file = new File(picPath);
                if (file.exists()){
                    Uri uri = null;
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        try {
                            uri = Uri.parse(MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), file.getName(), null));
                        } catch (FileNotFoundException e) {
                            Toast.makeText(context,"图片不存在", Toast.LENGTH_SHORT).show();
                            e.printStackTrace();
                        }
                    } else {
                        uri = Uri.fromFile(file);
                    }
                    imageList.add(uri);
                }
            }

            if(imageList.size() == 0){
                Toast.makeText(context,"图片不存在", Toast.LENGTH_SHORT).show();
                return;
            }

            shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageList);
            context.startActivity(Intent.createChooser(shareIntent, "Share"));
        }
    }

    /**
     * 分享单图片到朋友圈
     * @param context
     * @param imagePath
     */
    public static void sharePicsToWXFriendCircle(Context context, String imagePath) {
        if (!isInstallWeChart(context)) {
            Toast.makeText(context,"您没有安装微信", Toast.LENGTH_SHORT).show();
            return;
        }

        Intent intent = new Intent();
        intent.setComponent(new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareToTimeLineUI"));
        intent.setAction(Intent.ACTION_SEND);

        File f = new File(imagePath);
        Uri uri = null;
        if (f.exists()){
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                uri = getImageContentUri(context, f);
            } else {
                uri = Uri.fromFile(f);
            }
        }else {
            Toast.makeText(context,"图片不存在", Toast.LENGTH_SHORT).show();
            return;
        }

        intent.setType("image/*");
        intent.putExtra(Intent.EXTRA_STREAM, uri); //图片数据(支持本地图片的Uri形式)
        intent.putExtra("Kdescription", ""); //微信分享页面,图片上边的描述
        context.startActivity(intent);
    }

    /**
     * 唤醒微信
     * @param context
     */
    public static void startWechat(Context context){
        Intent intent = new Intent(Intent.ACTION_MAIN);
        ComponentName cmp = new ComponentName("com.tencent.mm","com.tencent.mm.ui.LauncherUI");
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setComponent(cmp);
        context.startActivity(intent);
    }

    /**
     * 分享图片给好友(多图片)
     * @param context
     * @param paths
     */
    public static void sharePicToWechatNoSDK(Context context, List<String> paths) {

        if(!isInstallWeChart(context)){
            Toast.makeText(context,"您没有安装微信", Toast.LENGTH_SHORT).show();
            return;
        }

        Intent intent = new Intent();
        ComponentName comp = new ComponentName("com.tencent.mm","com.tencent.mm.ui.tools.ShareImgUI");

        intent.setComponent(comp);
        intent.setAction(Intent.ACTION_SEND_MULTIPLE);
        intent.setType("image/*");

        ArrayList<Uri> imageList = new ArrayList<>();

        for (String picPath : paths) {
            File file = new File(picPath);
            if (file.exists()){
                Uri uri = null;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    try {
                        uri = Uri.parse(MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), file.getName(), null));
                    } catch (FileNotFoundException e) {
                        Toast.makeText(context,"图片不存在", Toast.LENGTH_SHORT).show();
                        e.printStackTrace();
                    }
                } else {
                    uri = Uri.fromFile(file);
                }
                imageList.add(uri);
            }
        }

        if(imageList.size() == 0){
            Toast.makeText(context,"图片不存在", Toast.LENGTH_SHORT).show();
            return;
        }
        intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageList); //图片数据(支持本地图片的Uri形式)

        context.startActivity(intent);
    }

    /**
     * 获取分享到微信朋友圈的uri格式
     * @param context
     * @param imageFile
     * @return
     */
    public static Uri getImageContentUri(Context context, File imageFile) {

        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Images.Media._ID}, MediaStore.Images.Media.DATA +"=? ",
                new String[]{filePath}, null);

        Uri uri =null;

        if (cursor !=null) {
            if (cursor.moveToFirst()) {
                int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
                Uri baseUri = Uri.parse("content://media/external/images/media");
                uri = Uri.withAppendedPath(baseUri, "" + id);
            }
            cursor.close();
        }

        if (uri ==null) {
            ContentValues values = new ContentValues();
            values.put(MediaStore.Images.Media.DATA, filePath);
            uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        }
        return uri;
    }

    /**检查是否安装微信
     * @param context
     * @return
     */
    private static boolean isInstallWeChart(Context context){

        PackageInfo packageInfo = null;

        try {
            packageInfo = context.getPackageManager().getPackageInfo("com.tencent.mm", 0);
        } catch (Exception e) {
            packageInfo = null;
            e.printStackTrace();
        }

        if (packageInfo == null) {
            return false;
        } else {
            return true;
        }
    }

    /**检查是否安装QQ
     * @param context
     * @return
     */
    private static boolean isInstallQQ(Context context){

        PackageInfo packageInfo = null;

        try {
            packageInfo = context.getPackageManager().getPackageInfo("com.tencent.mobileqq", 0);
        } catch (Exception e) {
            packageInfo = null;
            e.printStackTrace();
        }

        if (packageInfo == null) {
            return false;
        } else {
            return true;
        }
    }
}

FileDownloader 递归多文件下载

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;

import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadSampleListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.weipai.dialog.LoadingDialog;
import com.weipai.main.contact.Contact;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class DownloadFileUtil {

    private Context context;
    private String path;
    private boolean isShowLoading = true;
    private List<String> pathList;
    private List<String> netUrlList;
    private OnFilesDownloadListener listener;
    //private LoadingDialog dialog;

    public static DownloadFileUtil init(Context context, String path) {
        return new DownloadFileUtil(context, path);
    }

    private DownloadFileUtil(Context context, String path) {
        this.context = context;
        this.path = path;
        pathList = new ArrayList<>();
        netUrlList = new ArrayList<>();
    }

    public DownloadFileUtil setOnFilesDownloadListener(OnFilesDownloadListener listener){
        this.listener = listener;
        return this;
    }

    private int fileCount = 0;
    private OnSingleFileDownloadListener l = new OnSingleFileDownloadListener() {
        @Override
        public void onCompleted(String path) {
            ++fileCount;
            pathList.add(path);
            if (fileCount == netUrlList.size()){
                //dialog.dismiss();
                if (listener != null) listener.onCompleted(pathList);
            }else {
                downloadFile(netUrlList.get(fileCount), l);
            }
        }
    };

    /**
     * 递归下载多文件
     * @param urls
     */
    public void downloadFiles(final List<String> urls){
        netUrlList.clear();
        netUrlList.addAll(urls);
        if (netUrlList.size() > 0) {
            //dialog = new LoadingDialog(context);
            //dialog.show();
            downloadFile(urls.get(0), l);
        }
    }

    /**
     * 单文件下载
     * @param url
     * @param listener
     */
    public void downloadFile(String url, final OnSingleFileDownloadListener listener) {
        Log.e("backinfo", "downloadFile " + fileCount);
        Log.e("backinfo", "downloadFile url" + url);
        Log.e("backinfo", "downloadFile path" + path);
        String fileName = new Date().getTime() + ".jpg";
        /*if (fileName.isEmpty()) {
            if (fileCount == netUrlList.size() - 1) dialog.dismiss();
            return;
        }*/
        FileDownloader.getImpl().create(url)
                .setPath(path + fileName, false)
                .setCallbackProgressTimes(300)
                .setMinIntervalUpdateSpeed(400)
                .setAutoRetryTimes(3)
                .setListener(new FileDownloadSampleListener() {
                    @Override
                    protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        Log.e("backinfo", ",soFarBytes:" + soFarBytes + ",totalBytes:" + totalBytes + ",percent:" + soFarBytes * 1.0 / totalBytes + ",speed:" + task.getSpeed());
                    }

                    @Override
                    protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        Log.e("backinfo", ",soFarBytes:" + soFarBytes + ",totalBytes:" + totalBytes + ",percent:" + soFarBytes * 1.0 / totalBytes + ",speed:" + task.getSpeed());
                    }

                    @Override
                    protected void blockComplete(BaseDownloadTask task) {
                        Log.e("backinfo", "blockComplete ");
                    }

                    @Override
                    protected void completed(BaseDownloadTask task) {
                        //  VideoPlayerManager.instance().resumeVideoPlayer();
                        File file = new File(task.getTargetFilePath());
                        Log.e("backinfo",  "completed " + task.getTargetFilePath());
                        if (file.exists()) {
                            Uri localUri = Uri.fromFile(file);
                            Intent localIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, localUri);
                            context.sendBroadcast(localIntent);
                            listener.onCompleted(file.getAbsolutePath());
                        }
                    }

                    @Override
                    protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        Log.e("backinfo", "paused ");
                    }

                    @Override
                    protected void error(BaseDownloadTask task, Throwable e) {
                        Log.e("backinfo", "error " + e.getLocalizedMessage());
                    }

                    @Override
                    protected void warn(BaseDownloadTask task) {
                        Log.e("backinfo", "warn ");
                    }
                }).start();
    }



    private interface OnSingleFileDownloadListener{
        void onCompleted(String path);
    }

    public interface OnFilesDownloadListener{
        void onCompleted(List<String> pathList);
    }

    /** 获取文件后缀 */
    public String getFileExtension(String url) {
        int i = url.lastIndexOf('.');
        if (i > 0 && i < url.length() - 1) {
            return url.substring(i + 1).toLowerCase();
        }
        return "";
    }
}

使用例:

DownloadFileUtil.init(context,  "/sdcard/DCIM/Camera/")
               .setOnFilesDownloadListener(new DownloadFileUtil.OnFilesDownloadListener() {
                @Override
                    public void onCompleted(List<String> pathList) {
                        WechatShareUtil.sharePicToQQNoSDK(context, pathList);
                    }
                }).downloadFiles(urls);

 

本文地址:https://blog.csdn.net/qq_15710245/article/details/107185841