Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
346 views
in Technique[技术] by (71.8m points)

sharing image with whatsapp in android

I have image in assets folder and need to share it with whatsapp application

I tried this code , it keeps give me sharing failed try again ! what's wrong ?!

         Intent share = new Intent(Intent.ACTION_SEND);
      share.setType("image/*");
      share.setPackage("com.whatsapp"); 
    //  share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File("file:///assets/epic/adv.png"))); 
      share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///assets/epic/adv.png"));
      this.startActivity(Intent.createChooser(share, "share_via"));
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This code for share image via whatsapp worked fine for me .

public void shareImageWhatsApp() {

    Bitmap adv = BitmapFactory.decodeResource(getResources(), R.drawable.adv);
    Intent share = new Intent(Intent.ACTION_SEND);
    share.setType("image/jpeg");
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    adv.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    File f = new File(Environment.getExternalStorageDirectory()
            + File.separator + "temporary_file.jpg");
    try {
        f.createNewFile();
        new FileOutputStream(f).write(bytes.toByteArray());
    } catch (IOException e) {
        e.printStackTrace();
    }
    share.putExtra(Intent.EXTRA_STREAM,
            Uri.parse( Environment.getExternalStorageDirectory()+ File.separator+"temporary_file.jpg"));
    if(isPackageInstalled("com.whatsapp",this)){
          share.setPackage("com.whatsapp"); 
          startActivity(Intent.createChooser(share, "Share Image"));

    }else{

        Toast.makeText(getApplicationContext(), "Please Install Whatsapp", Toast.LENGTH_LONG).show();
    }

}

private boolean isPackageInstalled(String packagename, Context context) {
    PackageManager pm = context.getPackageManager();
    try {
        pm.getPackageInfo(packagename, PackageManager.GET_ACTIVITIES);
        return true;
    } catch (NameNotFoundException e) {
        return false;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...