Android 系统跳转实现分享功能(如 微信 朋友圈 QQ QQ空间 微博)

     前者基本都是一个实现思路,  唯独微博实现比较特殊一点。

     我对两个类做了封装  只要配置没问题, 拿去直接用。

     先来一波配置

   清单文件下

<provider
    android:name="androidx.core.content.FileProvider"
    android:authorities="包名.fileprovider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths_public" />
</provider>

 

 然后就是res路径下 创建一个xml文件夹  (里面有三个xml布局文件)

  (1) file_paths

<?xml version="1.0" encoding="utf-8"?>
    <paths>
        <external-path
            name="camera_photos"
            path="."/>
        <external-path
            name="files_root"
            path="Android/data/com.ijuyin.prints.news/"/>
        <external-path
            name="external_storage_root"
            path="."/>
        <external-path name="my_images" path="."/>
    </paths>


<!--<path xmlns:android="http://schemas.android.com/apk/res/android">-->
<!--    <external-path name="my_images" path=""/>-->
<!--</path>-->

 

   (2) file_paths_public

 

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path
        name="external_storage_root"
        path="." />
    <files-path
    name="files-path"
    path="." />
    <cache-path
        name="cache-path"
        path="." />
    <!--/storage/emulated/0/Android/data/...-->
    <external-files-path
        name="external_file_path"
        path="." />
    <!--代表app 外部存储区域根目录下的文件 Context.getExternalCacheDir目录下的目录-->
    <external-cache-path
        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,华为没有
-->
    <root-path
        name="root-path"
        path="" />

    ...
</paths>

  

   (3) network_security_config

 

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true" />
</network-security-config>

 

   因为是需要内容提供者 跳转三方应用的页面  所以必须要添加, 还有就是 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
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals(mType)) {
                    return true;
                }
            }
        }
        return false;
    }

    public static void deletePic(File file){

        if (file.isDirectory()){

            File[] files = file.listFiles();

            for (int j = 0; j < files.length; j++) {
                File f = 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 List<File> files = 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 < url.length; i++) {
                    File file = null;
                    if (url[i].contains("http")) {
                        file = Tools.saveImageToSdCard(context, url[i]);
                    } else {
                        file = new File(url[i]);
                    }
                    files.add(file);
                }
                ArrayList<Uri> imageUris = new ArrayList<Uri>();
                    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, ArrayList<Uri> uri) {
        Intent shareIntent = new Intent();
        shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        //2添加图片数组
        ArrayList<Uri> imageUris = new ArrayList<>();
        for (int i = 0; i < uri.size(); i++) {
            Uri url = null;
            try {
                url = Uri.parse(android.provider.MediaStore.Images.
                        Media.insertImage(context.getContentResolver(),
                        files.get(i).getAbsolutePath(), files.get(i).getName(), null));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            imageUris.add(url);
        }
        if (getVersionCode(context, PACKAGE_NAME_WEI_XIN) < VERSION_CODE_FOR_WEI_XIN_VER7) {
            // 微信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指定选择微信
        ComponentName componentName = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareToTimeLineUI");
        shareIntent.setComponent(componentName);
        //4开始分享
        context.startActivity(Intent.createChooser(shareIntent, "分享图片"));
    }

    /**
     * 拉起微信发送多张图片给好友
     */
    private void shareWXSomeImg(Context context, ArrayList<Uri> uri) {
        Intent shareIntent = new Intent();
        //1调用系统分析
        shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
        shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //2添加图片数组
        ArrayList<Uri> imageUris = new ArrayList<>();
        for (int i = 0; i < uri.size(); i++) {
            Uri url = null;
            try {
                url = Uri.parse(android.provider.MediaStore.Images.
                        Media.insertImage(context.getContentResolver(),
                        files.get(i).getAbsolutePath(), files.get(i).getName(), null));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            imageUris.add(url);
        }
        shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris);
        shareIntent.setType("image/*");
        //3指定选择微信
        ComponentName componentName = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareImgUI");
        shareIntent.setComponent(componentName);
        //4开始分享
        context.startActivity(Intent.createChooser(shareIntent, "分享图片"));
    }

    /**
     * 拉起QQ发送多张图片给好友
     */
    private void shareQQImg(Context context, ArrayList<Uri> uri) {
        Intent shareIntent = new Intent();
        //1调用系统分析
        shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
        shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //2添加图片数组
        ArrayList<Uri> imageUris = new ArrayList<>();
        for (int i = 0; i < files.size(); i++) {
            Uri url = null;
            try {
                url = Uri.parse(android.provider.MediaStore.Images.
                        Media.insertImage(context.getContentResolver(),
                        files.get(i).getAbsolutePath(), files.get(i).getName(), null));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            imageUris.add(url);
        }
        shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris);
        shareIntent.setType("image/*");
        //3指定选择微信
        ComponentName componentName = new ComponentName("com.tencent.mobileqq", "com.tencent.mobileqq.activity.JumpActivity");
        shareIntent.setComponent(componentName);
        //4开始分享
        context.startActivity(Intent.createChooser(shareIntent, "分享图片"));
    }

    /**
     * 拉起QQ发送多张图片给好友
     */
    private void shareQZoneImg(Context context, ArrayList<Uri> uri) {
        Intent shareIntent = new Intent();
        //1调用系统分析
        shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
        shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //2添加图片数组
        ArrayList<Uri> imageUris = new ArrayList<>();
        for (int i = 0; i < files.size(); i++) {
            Uri url = null;
            try {
                url = Uri.parse(android.provider.MediaStore.Images.
                        Media.insertImage(context.getContentResolver(),
                        files.get(i).getAbsolutePath(), files.get(i).getName(), null));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            imageUris.add(url);
        }
        shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris);
        shareIntent.setType("image/*");
        //3指定选择微信
        ComponentName componentName = new ComponentName("com.qzone", "com.qzonex.module.operation.ui.QZonePublishMoodActivity");
        shareIntent.setComponent(componentName);
        //4开始分享
        context.startActivity(Intent.createChooser(shareIntent, "分享图片"));
    }

    /**
     * 拉起微博发送多张图片给好友
     */
    private void shareWBImg(Context context, ArrayList<Uri> uri) {
        Intent shareIntent = new Intent();
        //1调用系统分析
        shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
        shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //2添加图片数组
        ArrayList<Uri> imageUris = new ArrayList<>();
        for (int i = 0; i < files.size(); i++) {
            Uri url = null;
            try {
                url = Uri.parse(android.provider.MediaStore.Images.
                        Media.insertImage(context.getContentResolver(),
                        files.get(i).getAbsolutePath(), files.get(i).getName(), null));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            imageUris.add(url);
        }
        shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris);
        shareIntent.setType("image/*");
        //3指定选择微信
//        ComponentName componentName = new ComponentName("com.sina.weibo", "com.sina.weibo.activity.JumpActivity");
//        shareIntent.setComponent(componentName);
        shareIntent.setPackage("com.sina.weibo");
        //4开始分享
        context.startActivity(Intent.createChooser(shareIntent, "分享图片"));
    }

    /**
     * 获取制定包名应用的版本的versionCode
     *
     * @param context
     * @param
     * @return
     */
    public 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;
        }
    }


}

 

   使用时候     (切记 切记 切记 图片必须是下载到本地的!!!)

 动态申请权限  

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) {

}

 

   完成!!!!!   

  

 

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
实现Android仿微信朋友圈图片查看功能,可以按照以下步骤进行: 1. 首先,需要使用一个RecyclerView来展示朋友圈的列表,每个朋友圈项包含了图片的缩略图、文字内容和评论等信息。 2. 当用户点击某个朋友圈项时,需要跳转到一个新的Activity或者Fragment来显示该朋友圈的详细内容。 3. 在新的界面中,可以使用ViewPager来展示朋友圈中的图片。ViewPager的每一页对应一张图片,并实现左右滑动切换图片功能。 4. 对于图片的加载,可以使用一个图片加载库如Glide或Picasso来加载图片,避免OOM(Out of Memory)的问题。 5. 为了更好的用户体验,可以在ViewPager上添加一个类似于微信图片预览效果,即当用户点击某张图片时,可以全屏显示,并支持缩放、双击放大、手势滑动等功能。 6. 为了保证性能和流畅度,可以使用一些优化技巧,如图片的压缩、缓存、异步加载等。 7. 如果需要支持多张图片的查看,可以使用PhotoView或类似的第三方库来实现,它可以显示多张图片,并支持手势操作。 8. 最后,为了提高用户体验,可以加入一些其他功能,如显示图片的点赞数和评论数、支持多种分享方式、图片保存等。 通过以上步骤的实现,就可以实现Android仿微信朋友圈图片查看的功能了。这样用户就可以在朋友圈列表中预览图片,点击后再进行详细查看和操作,提高了用户的交互体验。
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值