Android調用系統分享,資源未找到問題

Android調用系統的分享來分享網絡圖片,是不能直接分享網絡圖片的,需要把圖片保存到本地:

// 保存圖片
public static void saveBitmap(Bitmap bitmap, String filePath, String fileName) {
        File headDir = new File(filePath);
        if (!headDir.exists()) {
            headDir.mkdirs();
        }
        FileOutputStream headFos = null;
        File headFile = null;
        try {
            //重命名並保存
            headFile = new File(filePath, fileName);
            headFile.createNewFile();
            headFos = new FileOutputStream(headFile);
            bitmap.compress(CompressFormat.JPEG, 100, headFos);
            headFos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (headFos != null) {
                try {
                    headFos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

// 網絡圖片轉成bigmap對象
public static Bitmap getBitMBitmap(String urlpath) {
        Bitmap map = null;
        try {
            URL url = new URL(urlpath);
            URLConnection conn = url.openConnection();
            conn.connect();
            InputStream in;
            in = conn.getInputStream();
            map = BitmapFactory.decodeStream(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }
// 調用系統分享
public void share(String imgUrl) {
	String imgPath = "自已定義路徑";
	String imgName = "share.jpg";
	saveBitmap(getBitMBitmap(imgUrl), imgPath, imgName);
	Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setType("image/*");
    intent.putExtra(Intent.EXTRA_STREAM, Uri.parse(imgPath  + "/" + imgPath ));
    startActivity(Intent.createChooser(intent, "圖片描述,隨便寫"));
}

但是這時候我們去分享是不行的,我開始這樣去分享只有QQ好友成功了,其他的都沒成功,因爲你只是把圖片存到本地了,而你調系統的分享,系統不知道你給它保存了這個圖片,所以它去分享的時候它會說我不知道有這張圖片,可不就是資源未找到,所以我們要告訴系統 我給你保存了一張圖片:

/**
 * 這個參數是你保存到本地圖片的絕對路徑(包括文件名.jpg的)
 */
public static String insertImageToSystem(Context context, String imagePath) {
        String url = "";
        try {
            url = MediaStore.Images.Media.insertImage(context.getContentResolver(), imagePath, imgName , "分享");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return url;
    }

最終調用系統分享:

// 調用系統分享
public void share(String imgUrl) {
	String imgPath = "自已定義路徑";
	String imgName = "share.jpg";
	saveBitmap(getBitMBitmap(imgUrl), imgPath, imgName);
	insertImageToSystem(context, imgAbsPath);// imgAbsPath:圖片絕對路徑
	Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setType("image/*");
    intent.putExtra(Intent.EXTRA_STREAM, Uri.parse(imgPath  + "/" + imgPath ));
    startActivity(Intent.createChooser(intent, "圖片描述,隨便寫"));
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章