Android 原生(和微信)分享

原生分享内容

public class ShareUtils {

    /**
     * 分享文字
     *
     * @param a             上下文
     * @param activityTitle Activity的名字
     * @param msgTitle      消息标题
     * @param msgText       消息内容
     */
    public static void shareTxt(Activity a, String activityTitle, String msgTitle, String msgText) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain"); // 纯文本
        intent.putExtra(Intent.EXTRA_SUBJECT, msgTitle);
        intent.putExtra(Intent.EXTRA_TEXT, msgText);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        a.startActivity(Intent.createChooser(intent, activityTitle));
    }

    /**
     * 原生分享图片
     *
     * @param file	本地图片文件
     * @param activity
     */
    public static void shareImage(File file, Activity activity) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        Uri fileUri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            fileUri = FileProvider.getUriForFile(activity, getAppPackageName(App.context) + ".fileprovider", file);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            fileUri = Uri.fromFile(file);
        }
        intent.putExtra(Intent.EXTRA_STREAM, fileUri);
        intent.setType("image/*");
        Intent chooser = Intent.createChooser(intent, "");
        if (intent.resolveActivity(activity.getPackageManager()) != null) {
            activity.startActivityForResult(chooser,101);
        }
    }

    /**
     * 原生分享视频
     *
     * @param file	本地视频文件
     * @param activity
     */
    public static void shareVideo(File file, Activity activity) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        Uri fileUri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            fileUri = FileProvider.getUriForFile(activity, getAppPackageName(App.context) + ".fileprovider", file);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            fileUri = Uri.fromFile(file);
        }
        intent.putExtra(Intent.EXTRA_STREAM, fileUri);
        intent.setType("video/*");
        Intent chooser = Intent.createChooser(intent, "");
        if (intent.resolveActivity(activity.getPackageManager()) != null) {
            activity.startActivityForResult(chooser,101);
        }
    }


    public static String getAppPackageName(Context context) {
        String packageName = "";
        try {
            packageName = context.getPackageName();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return packageName;
    }

}

微信分享内容

public class WXUtil {

    /**
     * 检查是否安装微信
     *
     * @param context
     * @return
     */
    public static boolean isWeixinAvilible(Context context) {
        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("com.tencent.mm")) {
                    return true;
                }
            }
        }
        return false;
    }

    private static final int IMAGE_SIZE = 32768;//微信分享图片大小限制

    /**
     * 用户分享链接
     */
    public static volatile String shareUrl = "";

    /**
     * 微信分享
     *
     * @param friendsCircle true:朋友圈
     * @param title         分享标题
     * @param desc          分享描述
     */
    public static void share(final IWXAPI iwxapi, final Activity activity, final boolean friendsCircle, final String title, final String desc, final String bookUrl) {
        if (!isWeixinAvilible(App.context)) {
            ToastUtil.showShortToast(activity, "请先安装微信");
            return;
        }
        if (shareUrl == null) {
            ToastUtil.showShortToast(activity, "分享失败");
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                final Bitmap bitmap = returnBitMap(bookUrl);
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        WXWebpageObject webPage = new WXWebpageObject();
                        webPage.webpageUrl = shareUrl;//分享url
                        WXMediaMessage msg = new WXMediaMessage(webPage);
                        msg.title = title;
                        msg.description = desc;
                        msg.thumbData = getThumbData(bitmap);//封面图片byte数组
                        SendMessageToWX.Req req = new SendMessageToWX.Req();
                        req.transaction = String.valueOf(System.currentTimeMillis());
                        req.message = msg;
                        req.scene = friendsCircle ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession;
                        iwxapi.sendReq(req);
                    }
                });
            }
        }).start();
    }

    private static Bitmap returnBitMap(final String url) {
        URL imageurl = null;
        try {
            imageurl = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        Bitmap bitmap = null;
        try {
            HttpURLConnection conn = (HttpURLConnection) imageurl.openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    /**
     * 获取分享封面byte数组 我们这边取的是软件启动icon
     *
     * @return
     */
    private static byte[] getThumbData(Bitmap bitmap) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 2;
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, output);
        int quality = 100;
        while (output.toByteArray().length > IMAGE_SIZE && quality != 10) {
            output.reset(); // 清空baos
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, output);// 这里压缩options%,把压缩后的数据存放到baos中
            quality -= 10;
        }
        bitmap.recycle();
        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}

你可能感兴趣的:(Android)