如何将下载的图片扫描到系统相册?附带:微信转发多图

前言

之前项目中有个需求就是可以转发多图到微信朋友圈,自微信6.7.3发布后,微信不再支持多图分享。SO  经过漫长的岁月(用户的测试)出现了一下最终的解决方法。

思路:由于微信发送朋友圈时,能选择到系统相册中的图片,所以我们把下载下来的图片保存到系统相册中,这样微信发送朋友圈时就可以选择到我们下载到本地的图片了。

 

第一步:下载图片

import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.Target;
import com.fastframe.log.L;
import com.letu.sharehelper.App;

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

/**
 * 创建时间: 2016/12/1.
 * 创建者: letu01.
 * 描述:
 */
public class ImageDownloadManager {

    private static volatile ImageDownloadManager instance;

    private DownloadCallback callback;

    private String savePath;


    /*package*/
    public static ImageDownloadManager getInstance() {
        if (instance == null) {
            synchronized (ImageDownloadManager.class) {
                if (instance == null) {
                    instance = new ImageDownloadManager();
                }
            }
        }
        return instance;
    }

    private ImageDownloadManager() {
    }

    /**
     * 开始下载
     *
     * @param urls
     */
    public void downLoad(Context context, String[] urls,String savePath, DownloadCallback callback) {
        this.callback = callback;
        this.savePath = savePath;
        new DownLoadImageTask(context, urls).executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
    }


    private class DownLoadImageTask extends AsyncTask<Void, Void, List<File>> {
        private final Context context;

        private String[] mUrls;

        public DownLoadImageTask(Context context, String[] mUrls) {
            this.context = context;
            this.mUrls = mUrls;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }


        @Override
        protected List<File> doInBackground(Void... params) {
            List<File> fileList = new ArrayList<>();
            int length = mUrls.length;
            for (int i = 0; i < length; i++) {
                try {
                    Message msg = handler.obtainMessage();
                    msg.what = 1;
                    msg.arg1 = i + 1;
                    msg.arg2 = length;
                    msg.sendToTarget();
                    File file = Glide.with(context)
                            .load(mUrls[i])
                            .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                            .get();
                    String targetPath = savePath;
                    String targetFilePath = targetPath + String.format("%s.jpg", String.valueOf(System.currentTimeMillis()));
                    File newFile = new File(targetFilePath);
                    boolean b = file.renameTo(newFile);
                    if(b){
                        fileList.add(newFile);
                    }else {
                        fileList.add(file);
                    }

                } catch (Exception ex) {
                    ex.printStackTrace();
                    L.e(ex.getMessage());
                    Message msg = handler.obtainMessage();
                    msg.what = -1;
                    msg.obj = ex;
                    msg.sendToTarget();
                }
            }
            return fileList;

        }

        @Override
        protected void onPostExecute(List<File> result) {
            if (null != callback) {
                callback.onSuccess(result);
            }
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    int index = msg.arg1;
                    int total = msg.arg2;
                    if (null != callback) {
                        callback.onProgress(total, index);
                    }
                    break;
                case -1:
                    if (null != callback) {
                        callback.onError((Exception) msg.obj);
                    }
                    break;
            }
        }
    };

}

开始下载:

ImageDownloadManager.getInstance().downLoad(activity, urls, new DownloadCallback() {
            @Override
            public void onProgress(int totalNumbers, int progressIndex) {
                Log.e("",String.format("正在下载图片,第%d张", progressIndex))
            }

            @Override
            public void onSuccess(final List<File> files) {
                Log.e("","图片下载完成!")
                
            }

            @Override
            public void onError(final Exception e) {
            Log.e("","图片下载失败,请重试!")
            }
        });

第二步:将图片扫描到系统相册中

/**
*context   上下文
*fileList  待扫描文件列表
*/
new FileScanManager(context, fileList, new FileScanManager.ScanListener() {

                    @Override
                    public void onProgress(Uri uri) {
                        //扫描进度
                    }

                    @Override
                    public void onFinish() {
                      //TODO 做扫描完成后的操作;
                    }
                });

扫描类:

/**
 * createTime: 2018/11/28.13:50
 * updateTime: 2018/11/28.13:50
 * author: singleMan.
 * desc: 扫描文件到系统相册
 */

public class FileScanManager implements MediaScannerConnection.MediaScannerConnectionClient {

    public interface ScanListener {
        void onFinish();

        void onProgress(Uri uri);
    }

    private MediaScannerConnection connection;
    private List<File> fileList = new ArrayList<>();
    private ScanListener listener;

    private int scanIndex = 0;

    Context context;

    public FileScanManager(Context context, File file, ScanListener listener) {
        this.context = context;
        this.listener = listener;
        fileList.add(file);
        connection = new MediaScannerConnection(context, this);
        connection.connect();
    }

    public FileScanManager(Context context, List<File> files, ScanListener listener) {
        this.context = context;
        this.listener = listener ;
        if (null != files && !files.isEmpty())
            fileList.addAll(files);
        connection = new MediaScannerConnection(context, this);
        connection.connect();
    }

    @Override
    public void onMediaScannerConnected() {
        scanIndex = fileList.size();
        for (File file : fileList) {
            connection.scanFile(file.getAbsolutePath(), null);
        }

    }

    @Override
    public void onScanCompleted(String path, Uri uri) {
        listener.onProgress(uri);
        scanIndex--;
        if (scanIndex == 0) {
            handler.sendEmptyMessage(1);
            connection.disconnect();
        }

    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (null != listener)
                listener.onFinish();
        }
    };

}

到此微信就可以读取到我们下载的图片了。

最后一步:分享到微信

 /**
     * @param activity
     * @param content
     * @param uris
     */
    private static void shareToWeiXin(final Activity activity, String content, ArrayList<Uri> uris) {
        if (null == uris || uris.isEmpty()) return;
        try {
            ArrayList<Uri> imageUris = new ArrayList<>();
            Intent intent = new Intent();
            ComponentName comp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareToTimeLineUI");
            intent.setComponent(comp);
            intent.setAction(Intent.ACTION_SEND_MULTIPLE);
            intent.setType("image/*");
            intent.putExtra("Kdescription", content);
            /**
                667版本开始不支持文本内容的转发
                673版本开始不支持多图转发
             */
            intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris);
            activity.startActivityForResult(intent, 10);
        } catch (ActivityNotFoundException e) {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(activity, "您还未安装微信", Toast.LENGTH_SHORT).show();
                }
            });
        }

    }

要实现多图转发请关注: AccessibilityService(辅助服务)

源码下载地址:https://download.csdn.net/download/siyujiework/11109346

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值