Android 调用系统分享网络图片到微信

2019-03-12  本文已影响0人  听风1413

最近项目上有这样一个需求,需要分享网络图片到微信,在网上查阅了相关资料,然后结合自己的思路,总结了一下实现的具体流程:

1、将网络图片下载下来,转换成Bitmap:
  /**
     * @param  path 网络图片地址
     */
    public Bitmap getBitmap(String path) {
        try {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestMethod("GET");
            if (conn.getResponseCode() == 200) {
                InputStream inputStream = conn.getInputStream();
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                return bitmap;
            }
        } catch (IOException e) {

            e.printStackTrace();
        }
        return null;
    }
2、将Bitmap格式的文件保存在本地:
  /**
     * 保存文件
     */
    public void saveFile(Bitmap bm) throws IOException {
        File sd = Environment.getExternalStorageDirectory();
        File dirFile = new File(sd.getPath() + "/Download/imgurl.jpg");
        FileOutputStream fos;
        fos = new FileOutputStream(dirFile);
        if (fos!=null ) {
            bm.compress(Bitmap.CompressFormat.JPEG, 50, fos);
            fos.flush();
            fos.close();
        }
    }
3、调用系统分享:
 private Uri U;
    private void shareCode() {
        File sd = Environment.getExternalStorageDirectory();
        String path = sd.getPath() + "/Download/imgurl.jpg";
        File file = new File(path);
        if (Build.VERSION.SDK_INT < 24) {
            U = Uri.fromFile(file);
        } else {
            //android 7.0及以上权限适配
            U= FileProvider.getUriForFile(this,
                    "cn.izis.whteachtest.provider",
                    file);
        }
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("image/*");
        intent.putExtra(Intent.EXTRA_SUBJECT, "分享");
        intent.putExtra(Intent.EXTRA_STREAM, U);
        startActivity(Intent.createChooser(intent, getTitle()));
    }
注意:android 6.0系统以上,需要申请相关的的权限,这里就不做具体的说明了。
上一篇下一篇

猜你喜欢

热点阅读