AndroidはIntentを使って画像を共有したり、微信7.0版で「リソースの取得に失敗し、モーメンツに共有できない」という問題が発生したりして、共有に失敗した問題を処理しています.

23542 ワード

オリジナルワンタッチ共有(システムデフォルト)
Intent imageIntent = new Intent(Intent.ACTION_SEND);
imageIntent.setType("image/jpeg");
imageIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(path));
startActivity(Intent.createChooser(imageIntent, "  "));

カスタム共有機能ジャンプ1.指定されたappをインストールするかどうかを判断します
 public static boolean isInstallApp(Context context, String app_package) {
        final PackageManager packageManager = context.getPackageManager();
        List pInfo = packageManager.getInstalledPackages(0);
        if (pInfo != null) {
            for (int i = 0; i < pInfo.size(); i++) {
                String pn = pInfo.get(i).packageName;
                if (app_package.equals(pn)) {
                    return true;
                }
            }
        }
        return false;
    }

2.QQの友達に写真を共有する
  public static void shareImageToQQ(Context mContext, String bitmap) {
        if (isInstallApp(mContext, PlatformUtil.PACKAGE_MOBILE_QQ)) {
            try {
                //                Uri uriToImage = Uri.parse(MediaStore.Images.Media.insertImage(
                //                        mContext.getContentResolver(), bitmap, null, null));
                Uri uriToImage = Uri.parse(bitmap);
                Intent shareIntent = new Intent();
                shareIntent.setAction(Intent.ACTION_SEND);
                shareIntent.putExtra(Intent.EXTRA_STREAM, uriToImage);
                shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                shareIntent.setType("image/*");
                //              。       
                ComponentName componentName = new ComponentName(PACKAGE_MOBILE_QQ, "com.tencent.mobileqq.activity.JumpActivity");

                shareIntent.setComponent(componentName);
                // mContext.startActivity(shareIntent);
                mContext.startActivity(Intent.createChooser(shareIntent, "Share"));
            } catch (Exception e) {
                //            ContextUtil.getInstance().showToastMsg("     **  ");
            }
        } else {
            Toast.makeText(mContext, "     QQ   ", Toast.LENGTH_LONG).show();
        }
        /*
                QQ      ,    QQ          ,          QQ   ,               
              :
        mActivity.startActivity(intent);//      QQ        ,        ,    
            mActivity.startActivity(Intent.createChooser(intent, "Share"));
        */
    }

3.微信の友达に直接写真を共有する
    public static void shareWechatFriend(Context mContext, String picFile) {
        if (isInstallApp(mContext, PlatformUtil.PACKAGE_WECHAT)) {
            Intent intent = new Intent();
            ComponentName cop = new ComponentName(PACKAGE_WECHAT, "com.tencent.mm.ui.tools.ShareImgUI");
            intent.setComponent(cop);
            intent.setAction(Intent.ACTION_SEND);
            intent.setType("image/*");
            Uri uri = null;
            if (picFile != null) {
                //                    , android    7.0(  7.0  )
                //   APP            file        ,    FileProvider    。   7.0          crash。
                try {
                    ApplicationInfo applicationInfo = mContext.getApplicationInfo();
                    int targetSDK = applicationInfo.targetSdkVersion;
                    if (targetSDK >= Build.VERSION_CODES.N && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        uri = Uri.parse(MediaStore.Images.Media.insertImage(mContext.getContentResolver(), new File(picFile).getAbsolutePath(), "pangu", null));
                    } else {
                        uri = Uri.fromFile(new File(picFile));
                    }
                    intent.putExtra(Intent.EXTRA_STREAM, uri);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            if (getVersionCode(mContext, PACKAGE_WECHAT) > VERSION_CODE_FOR_WEI_XIN_VER7) {
                //   7.0     
                intent.setAction(Intent.ACTION_SEND);
                intent.putExtra(Intent.EXTRA_STREAM, uri);
            }
            // context.startActivity(intent);
            mContext.startActivity(Intent.createChooser(intent, "Share"));
        } else {
            Toast.makeText(mContext, "          ", Toast.LENGTH_LONG).show();
        }
    }

4.テキストと画像を直接微信のモーメンツに共有する
/**
     *                
     *                  ,                   
     *        /data/data/****       ,          “        ,.....”      。
     */
    public static void shareWechatMoment(Context context, String picFile) {
        if (isInstallApp(context, PlatformUtil.PACKAGE_WECHAT)) {
            Intent intent = new Intent();
            //          ,     ,          
            ComponentName comp = new ComponentName(PACKAGE_WECHAT, "com.tencent.mm.ui.tools.ShareToTimeLineUI");
            intent.setComponent(comp);
            intent.setAction(Intent.ACTION_SEND);
            intent.setType("image/*");
            //  Uri    
            Uri uri = null;
            if (picFile != null) {
                try {
                    ApplicationInfo applicationInfo = context.getApplicationInfo();
                    int targetSDK = applicationInfo.targetSdkVersion;
                    if (targetSDK >= Build.VERSION_CODES.N && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        uri = Uri.parse(MediaStore.Images.Media.insertImage(context.getContentResolver(), new File(picFile).getAbsolutePath(), "pangu", null));
                    } else {
                        uri = Uri.fromFile(new File(picFile));
                    }
                    intent.putExtra(Intent.EXTRA_STREAM, uri);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            if (getVersionCode(context, PACKAGE_WECHAT) > VERSION_CODE_FOR_WEI_XIN_VER7) {
                //   7.0     
                intent.setAction(Intent.ACTION_SEND);
                intent.putExtra(Intent.EXTRA_STREAM, uri);
            }
            context.startActivity(intent);
        } else {
            Toast.makeText(context, "          ", Toast.LENGTH_LONG).show();
        }
    }

5.複数の画像を微信のモーメンツに共有する
 /**
     *            
     *
     * @param bmp       Bitmap  
     */
    public void shareImageToWechat(Bitmap bmp, Context mContext) {
        File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsoluteFile();
        String fileName = "share";
        File appDir = new File(file, fileName);
        if (!appDir.exists()) {
            appDir.mkdirs();
        }
        fileName = System.currentTimeMillis() + ".jpg";
        File currentFile = new File(appDir, fileName);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(currentFile);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        ArrayList uris = new ArrayList<>();
        Uri uri = null;
        try {
            ApplicationInfo applicationInfo = mContext.getApplicationInfo();
            int targetSDK = applicationInfo.targetSdkVersion;
            if (targetSDK >= Build.VERSION_CODES.N && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                uri = Uri.parse(android.provider.MediaStore.Images.Media.insertImage(mContext.getContentResolver(), currentFile.getAbsolutePath(), fileName, null));
            } else {
                uri = Uri.fromFile(new File(currentFile.getPath()));
            }
            uris.add(uri);
        } catch (Exception ex) {

        }
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        ComponentName comp = new ComponentName(PACKAGE_WECHAT, "com.tencent.mm.ui.tools.ShareToTimeLineUI");
        intent.setComponent(comp);
        intent.setType("image/*");
        //        intent.putExtra("Kdescription", content);
        if (getVersionCode(mContext, PACKAGE_WECHAT) < VERSION_CODE_FOR_WEI_XIN_VER7) {
            //   7.0    
            intent.setAction(Intent.ACTION_SEND_MULTIPLE);
            intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
        } else {
            //   7.0     
            intent.setAction(Intent.ACTION_SEND);
            intent.putExtra(Intent.EXTRA_STREAM, uri);
        }
        mContext.startActivity(intent);
    }

6.新浪微博に分かち合う
  /**
     *        
     *
     * @param photoPath     
     */
    public static void shareToSinaFriends(Context context, String photoPath) {
        if (!isInstallApp(context, PlatformUtil.PACKAGE_SINA)) {
            Toast.makeText(context, "        !", Toast.LENGTH_SHORT).show();
            return;
        }
        File file = new File(photoPath);
        if (!file.exists()) {
            String tip = "     ";
            Toast.makeText(context, tip + " path = " + photoPath, Toast.LENGTH_LONG).show();
            return;
        }

        Intent intent = new Intent(Intent.ACTION_SEND);
        //       type      ,"text/plain"            ;"image/*"       ,       type             ,              。
        //        intent.setType("text/plain");
        intent.setType("image/*");//     |  +  |           
        PackageManager packageManager = context.getPackageManager();
        List matchs = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        ResolveInfo resolveInfo = null;
        for (ResolveInfo each : matchs) {
            String pkgName = each.activityInfo.applicationInfo.packageName;
            if ("com.sina.weibo".equals(pkgName)) {
                resolveInfo = each;
                break;
            }
        }
        intent.setClassName(PACKAGE_SINA, resolveInfo.activityInfo.name);//      resolveInfo            crash
        intent.putExtra(Intent.EXTRA_TEXT, "Test Text String !!");
        intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
        context.startActivity(intent);
    }

完全なツールクラス
/**
 * Created by zhangbowen on 2019/4/3.
 *        
 **/
public class PlatformUtil {
    public static final String PACKAGE_WECHAT = "com.tencent.mm";
    public static final String PACKAGE_MOBILE_QQ = "com.tencent.mobileqq";
    public static final String PACKAGE_QZONE = "com.qzone";
    public static final String PACKAGE_SINA = "com.sina.weibo";

    /**
     *   7.0   ,      7.0                 
     */
    private static final int VERSION_CODE_FOR_WEI_XIN_VER7 = 1380;

    //         app
    public static boolean isInstallApp(Context context, String app_package) {
        final PackageManager packageManager = context.getPackageManager();
        List pInfo = packageManager.getInstalledPackages(0);
        if (pInfo != null) {
            for (int i = 0; i < pInfo.size(); i++) {
                String pn = pInfo.get(i).packageName;
                if (app_package.equals(pn)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     *      QQ  
     *
     * @param bitmap     
     */
    public static void shareImageToQQ(Context mContext, String bitmap) {
        if (isInstallApp(mContext, PlatformUtil.PACKAGE_MOBILE_QQ)) {
            try {
                //                Uri uriToImage = Uri.parse(MediaStore.Images.Media.insertImage(
                //                        mContext.getContentResolver(), bitmap, null, null));
                Uri uriToImage = Uri.parse(bitmap);
                Intent shareIntent = new Intent();
                shareIntent.setAction(Intent.ACTION_SEND);
                shareIntent.putExtra(Intent.EXTRA_STREAM, uriToImage);
                shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                shareIntent.setType("image/*");
                //              。       
                ComponentName componentName = new ComponentName(PACKAGE_MOBILE_QQ, "com.tencent.mobileqq.activity.JumpActivity");

                shareIntent.setComponent(componentName);
                // mContext.startActivity(shareIntent);
                mContext.startActivity(Intent.createChooser(shareIntent, "Share"));
            } catch (Exception e) {
                //            ContextUtil.getInstance().showToastMsg("     **  ");
            }
        } else {
            Toast.makeText(mContext, "     QQ   ", Toast.LENGTH_LONG).show();
        }
        /*
                 QQ      ,    QQ          ,          QQ   ,               
              :
        mActivity.startActivity(intent);//      QQ        ,        ,    
            mActivity.startActivity(Intent.createChooser(intent, "Share"));
        */
    }

    /**
     *            
     *
     * @param picFile     
     */
    public static void shareWechatFriend(Context mContext, String picFile) {
        if (isInstallApp(mContext, PlatformUtil.PACKAGE_WECHAT)) {
            Intent intent = new Intent();
            ComponentName cop = new ComponentName(PACKAGE_WECHAT, "com.tencent.mm.ui.tools.ShareImgUI");
            intent.setComponent(cop);
            intent.setAction(Intent.ACTION_SEND);
            intent.setType("image/*");
            Uri uri = null;
            if (picFile != null) {
                //                    , android    7.0(  7.0  )
                //   APP            file        ,    FileProvider    。   7.0          crash。
                try {
                    ApplicationInfo applicationInfo = mContext.getApplicationInfo();
                    int targetSDK = applicationInfo.targetSdkVersion;
                    if (targetSDK >= Build.VERSION_CODES.N && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        uri = Uri.parse(MediaStore.Images.Media.insertImage(mContext.getContentResolver(), new File(picFile).getAbsolutePath(), "pangu", null));
                    } else {
                        uri = Uri.fromFile(new File(picFile));
                    }
                    intent.putExtra(Intent.EXTRA_STREAM, uri);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            if (getVersionCode(mContext, PACKAGE_WECHAT) > VERSION_CODE_FOR_WEI_XIN_VER7) {
                //   7.0     
                intent.setAction(Intent.ACTION_SEND);
                intent.putExtra(Intent.EXTRA_STREAM, uri);
            }
            // context.startActivity(intent);
            mContext.startActivity(Intent.createChooser(intent, "Share"));
        } else {
            Toast.makeText(mContext, "          ", Toast.LENGTH_LONG).show();
        }
    }

    /**
     *                
     *                  ,                   
     *        /data/data/****       ,          “        ,.....”      。
     */
    public static void shareWechatMoment(Context context, String picFile) {
        if (isInstallApp(context, PlatformUtil.PACKAGE_WECHAT)) {
            Intent intent = new Intent();
            //          ,     ,          
            ComponentName comp = new ComponentName(PACKAGE_WECHAT, "com.tencent.mm.ui.tools.ShareToTimeLineUI");
            intent.setComponent(comp);
            intent.setAction(Intent.ACTION_SEND);
            intent.setType("image/*");
            //  Uri    --        
            Uri uri = null;
            if (picFile != null) {
                try {
                    ApplicationInfo applicationInfo = context.getApplicationInfo();
                    int targetSDK = applicationInfo.targetSdkVersion;
                    if (targetSDK >= Build.VERSION_CODES.N && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        uri = Uri.parse(MediaStore.Images.Media.insertImage(context.getContentResolver(), new File(picFile).getAbsolutePath(), "pangu", null));
                    } else {
                        uri = Uri.fromFile(new File(picFile));
                    }
                    intent.putExtra(Intent.EXTRA_STREAM, uri);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            if (getVersionCode(context, PACKAGE_WECHAT) > VERSION_CODE_FOR_WEI_XIN_VER7) {
                //   7.0     
                intent.setAction(Intent.ACTION_SEND);
                intent.putExtra(Intent.EXTRA_STREAM, uri);
            }
            context.startActivity(intent);
        } else {
            Toast.makeText(context, "          ", Toast.LENGTH_LONG).show();
        }
    }

    /**
     *        
     *
     * @param photoPath     
     */
    public static void shareToSinaFriends(Context context, String photoPath) {
        if (!isInstallApp(context, PlatformUtil.PACKAGE_SINA)) {
            Toast.makeText(context, "        !", Toast.LENGTH_SHORT).show();
            return;
        }
        File file = new File(photoPath);
        if (!file.exists()) {
            String tip = "     ";
            Toast.makeText(context, tip + " path = " + photoPath, Toast.LENGTH_LONG).show();
            return;
        }

        Intent intent = new Intent(Intent.ACTION_SEND);
        //       type      ,"text/plain"            ;"image/*"       ,       type             ,              。
        //        intent.setType("text/plain");
        intent.setType("image/*");//     |  +  |           
        PackageManager packageManager = context.getPackageManager();
        List matchs = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        ResolveInfo resolveInfo = null;
        for (ResolveInfo each : matchs) {
            String pkgName = each.activityInfo.applicationInfo.packageName;
            if ("com.sina.weibo".equals(pkgName)) {
                resolveInfo = each;
                break;
            }
        }
        intent.setClassName(PACKAGE_SINA, resolveInfo.activityInfo.name);//      resolveInfo            crash
        intent.putExtra(Intent.EXTRA_TEXT, "Test Text String !!");
        intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
        context.startActivity(intent);
    }


    /**
     *            
     *
     * @param bmp       Bitmap  
     */
    public void shareImageToWechat(Bitmap bmp, Context mContext) {
        File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsoluteFile();
        String fileName = "share";
        File appDir = new File(file, fileName);
        if (!appDir.exists()) {
            appDir.mkdirs();
        }
        fileName = System.currentTimeMillis() + ".jpg";
        File currentFile = new File(appDir, fileName);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(currentFile);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        ArrayList uris = new ArrayList<>();
        Uri uri = null;
        try {
            ApplicationInfo applicationInfo = mContext.getApplicationInfo();
            int targetSDK = applicationInfo.targetSdkVersion;
            if (targetSDK >= Build.VERSION_CODES.N && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                uri = Uri.parse(android.provider.MediaStore.Images.Media.insertImage(mContext.getContentResolver(), currentFile.getAbsolutePath(), fileName, null));
            } else {
                uri = Uri.fromFile(new File(currentFile.getPath()));
            }
            uris.add(uri);
        } catch (Exception ex) {

        }
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        ComponentName comp = new ComponentName(PACKAGE_WECHAT, "com.tencent.mm.ui.tools.ShareToTimeLineUI");
        intent.setComponent(comp);
        intent.setType("image/*");
        //        intent.putExtra("Kdescription", content);
        if (getVersionCode(mContext, PACKAGE_WECHAT) < VERSION_CODE_FOR_WEI_XIN_VER7) {
            //   7.0    
            intent.setAction(Intent.ACTION_SEND_MULTIPLE);
            intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
        } else {
            //   7.0     
            intent.setAction(Intent.ACTION_SEND);
            intent.putExtra(Intent.EXTRA_STREAM, uri);
        }
        mContext.startActivity(intent);
    }

    /**
     *             versionCode
     *
     * @param context
     * @param
     * @return
     */
    private 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;
        }
    }
}

ポイントを引く!!!
以前、QQと微信を分かち合う时に出会って、QQあるいは微信が开いている场合、再び分かち合うことを呼び出すのはQQと微信を开いただけで、呼び出していないで连络先を分かち合うことを选ぶ场合の解决方法は以下の通りです:
        mActivity.startActivity(intent);//      QQ        ,        ,    
            mActivity.startActivity(Intent.createChooser(intent, "Share"));

微信7.0以下のバージョンでマルチピクチャを送信するのに問題があるので、この判断を追加する必要があります.
if (getVersionCode(mContext, PACKAGE_WECHAT) < VERSION_CODE_FOR_WEI_XIN_VER7) {
            //   7.0    
            intent.setAction(Intent.ACTION_SEND_MULTIPLE);
            intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
        } else {
            //   7.0     
            intent.setAction(Intent.ACTION_SEND);
            intent.putExtra(Intent.EXTRA_STREAM, uri);
        }

問題に直面した学生がみんなでもっと交流することを望んで、すべてここを見てどうしてあなたの注意心を残しませんか.