【问题标题】:How to share image URL to WhatsApp in Android?如何在 Android 中将图像 URL 共享到 WhatsApp?
【发布时间】:2015-11-20 01:56:22
【问题描述】:

我需要在我的应用程序中将图像分享给 WhatsApp。我有图片网址。为了分享到 WhatsApp,我使用以下代码。

String image_url = "http://images.cartradeexchange.com//img//800//vehicle//Honda_Brio_562672_5995_6_1438153637072.jpg";

URI uri = null;
try {
    uri = new URI(image_url.toString());
} catch (URISyntaxException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
Log.e("uri=", "" + uri);
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
shareIntent.setType("image/jpg");

// Target whatsapp:
shareIntent.setPackage("com.whatsapp");
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

try {
    startActivity(shareIntent);
} catch (android.content.ActivityNotFoundException ex) {
    Toast.makeText(InventoryManageOnlineActivity.this,
            "Whatsapp have not been installed.",
            Toast.LENGTH_SHORT).show();
}

但它没有用。我收到以下错误。

08-26 11:57:34.674: W/Bundle(19447): Key android.intent.extra.STREAM expected Parcelable but value was a java.net.URI.  The default value <null> was returned.
08-26 11:57:34.738: W/Bundle(19447): Attempt to cast generated internal exception:
08-26 11:57:34.738: W/Bundle(19447): java.lang.ClassCastException: java.net.URI cannot be cast to android.os.Parcelable
08-26 11:57:34.738: W/Bundle(19447):    at android.os.Bundle.getParcelable(Bundle.java:810)
08-26 11:57:34.738: W/Bundle(19447):    at android.content.Intent.getParcelableExtra(Intent.java:4850)
08-26 11:57:34.738: W/Bundle(19447):    at android.content.Intent.migrateExtraStreamToClipData(Intent.java:7548)
08-26 11:57:34.738: W/Bundle(19447):    at android.app.Instrumentation.execStartActivity(Instrumentation.java:1545)
08-26 11:57:34.738: W/Bundle(19447):    at android.app.Activity.startActivityForResult(Activity.java:3746)
08-26 11:57:34.738: W/Bundle(19447):    at android.app.Activity.startActivityForResult(Activity.java:3707)
08-26 11:57:34.738: W/Bundle(19447):    at android.app.Activity.startActivity(Activity.java:4027)
08-26 11:57:34.738: W/Bundle(19447):    at android.app.Activity.startActivity(Activity.java:3989)
08-26 11:57:34.738: W/Bundle(19447):    at com.cartradrexchange.inventory.InventoryManageOnlineActivity$ManageOnlineAdapter.onClick(InventoryManageOnlineActivity.java:441)
08-26 11:57:34.738: W/Bundle(19447):    at android.view.View.performClick(View.java:4761)
08-26 11:57:34.738: W/Bundle(19447):    at android.view.View$PerformClick.run(View.java:19767)
08-26 11:57:34.738: W/Bundle(19447):    at android.os.Handler.handleCallback(Handler.java:739)
08-26 11:57:34.738: W/Bundle(19447):    at android.os.Handler.dispatchMessage(Handler.java:95)
08-26 11:57:34.738: W/Bundle(19447):    at android.os.Looper.loop(Looper.java:135)
08-26 11:57:34.738: W/Bundle(19447):    at android.app.ActivityThread.main(ActivityThread.java:5312)
08-26 11:57:34.738: W/Bundle(19447):    at java.lang.reflect.Method.invoke(Native Method)
08-26 11:57:34.738: W/Bundle(19447):    at java.lang.reflect.Method.invoke(Method.java:372)
08-26 11:57:34.738: W/Bundle(19447):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
08-26 11:57:34.738: W/Bundle(19447):    at com.android.internal.os.ZygoteInit.main(Zygote

为此,我在 Google 上进行了很多搜索,并按照以下 URL 进行操作

Android sharing image doesn't work.

但这对我没有用。请教我如何分享图片网址。

【问题讨论】:

    标签: android image sharing whatsapp


    【解决方案1】:

    尝试改变这一行

    sharingIntent.putExtra(android.content.Intent.EXTRA_STREAM, url);
    

    这个

    sharingIntent.putExtra(android.content.Intent.EXTRA_STREAM, Uri.fromFile(image_url )); 
    // Use direct image url instead of uri
    

    让我知道它是否适合您。

    【讨论】:

    • 嗨 lavekush,在那一行 Uri.fromFile() 方法获取文件而不是图像 url
    • 我不是从你那里复制的 ..am 参考这个stackoverflow.com/questions/19306417/… ....但是你发布得更快...无论如何我都删除了我的答案
    【解决方案2】:

    查看这个答案

    How to share an image on whats app which is set on an ImageView in android.

    顺便说一句,我不明白你为什么要这样做image_url.toString()?它已经在字符串中了吗?

    也试试这段代码。

    String image_url = "http://images.cartradeexchange.com//img//800//vehicle//Honda_Brio_562672_5995_6_1438153637072.jpg";
    
            Intent shareIntent = new Intent();
            shareIntent.setType("image/*");
            shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            shareIntent.setAction(Intent.ACTION_SEND);
            //without the below line intent will show error
            shareIntent.setType("text/plain");
            shareIntent.putExtra(Intent.EXTRA_TEXT, image_url);
                    // Target whatsapp:
            shareIntent.setPackage("com.whatsapp");
            shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    
                    try {
                        startActivity(shareIntent);
                    } catch (android.content.ActivityNotFoundException ex) {
                        Toast.makeText(InventoryManageOnlineActivity.this,
                                "Whatsapp have not been installed.",
                                Toast.LENGTH_SHORT).show();
                    }
    

    【讨论】:

    • 您好 penta,分享信息工作正常。但图片 url 不起作用..如果你已经解决了这个问题,请分享该图片共享代码
    • 要直接分享图片而不是分享图片的url吗?
    • 现在检查,直接使用答案中的代码,如果不起作用,请转到链接
    • 对不起,我在答案中使用了 uri,我删除了它,现在使用代码
    • 嗨..我需要通过whatsapp分享图片,因为我有图片网址
    【解决方案3】:

    通过使用它,您可以在 whatsapp 上发送文字和网址。

    sendIntent.setPackage("com.whatsapp");
    

    仅在 whatsapp 上使用分享消息,您可以在其中选择要分享的联系人。

    Intent sendIntent = new Intent();
    sendIntent.setAction(Intent.ACTION_SEND);
    sendIntent.putExtra(Intent.EXTRA_TEXT, "http://images.cartradeexchange.com//img//800//vehicle//Honda_Brio_562672_5995_6_1438153637072.jpg");
     sendIntent.setType("text/plain");
     sendIntent.setPackage("com.whatsapp");
     startActivity(sendIntent);
    

    在清单中添加互联网权限

    <uses-permission android:name="android.permission.INTERNET" />
    

    【讨论】:

      【解决方案4】:

      使用下面的代码:-

         whatsapp.setOnClickListener(new View.OnClickListener() {
                      @Override
                      public void onClick(View v) {
                          Intent intent1 = c.getPackageManager().getLaunchIntentForPackage("com.whatsapp");
                          if(intent1!=null)
                          {
                              Intent whatsappIntent = new Intent(Intent.ACTION_SEND);
                              whatsappIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                              whatsappIntent.setType("image/*");
                              whatsappIntent.setPackage("com.whatsapp");
                              String url = Spacecraft.new_image_array.get(position);
                              new Download_GIF(url).execute();
                              Uri imageUri = Uri.parse("file:///storage/emulated/0/downloadedFile.gif");
                              whatsappIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
                              c.startActivity(whatsappIntent);
                          }
      

      下载_GIF类。

      public class Download_GIF extends AsyncTask<String, Void, String> {
          static String url_image=null;
      
          public Download_GIF(String url) {
              this.url_image = url;
          }
      
          @Override
          protected void onPreExecute() {
              super.onPreExecute();
          }
      
          @Override
          protected String doInBackground(String... params) {
      
              String filepath = null;
              try {
                  //set the download URL, a url that points to a file on the internet
                  //this is the file to be downloaded
                  URL url = new URL(url_image);
                  //create the new connection
                  HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
      
                  //set up some things on the connection
                  urlConnection.setRequestMethod("GET");
                  urlConnection.setDoOutput(true);
                  //and connect!
                  urlConnection.connect();
                  //set the path where we want to save the file
                  //in this case, going to save it on the root directory of the
                  //sd card.
                  File SDCardRoot = Environment.getExternalStorageDirectory();
                  //create a new file, specifying the path, and the filename
                  //which we want to save the file as.
      
                  String filename = "downloadedFile.gif";   // you can download to any type of file ex:.jpeg (image) ,.txt(text file),.mp3 (audio file)
                  Log.i("Local filename:", "" + filename);
                  File file;
                  file = new File(SDCardRoot, filename);
                  if (file.createNewFile()) {
                      file.createNewFile();
                  }
      
                  //this will be used to write the downloaded data into the file we created
                  FileOutputStream fileOutput = new FileOutputStream(file);
      
                  //this will be used in reading the data from the internet
                  InputStream inputStream = urlConnection.getInputStream();
      
                  //this is the total size of the file
                  int totalSize = urlConnection.getContentLength();
                  //variable to store total downloaded bytes
                  int downloadedSize = 0;
      
                  //create a buffer...
                  byte[] buffer = new byte[1024];
                  int bufferLength = 0; //used to store a temporary size of the buffer
      
                  //now, read through the input buffer and write the contents to the file
                  while ((bufferLength = inputStream.read(buffer)) > 0) {
                      //add the data in the buffer to the file in the file output stream (the file on the sd card
                      fileOutput.write(buffer, 0, bufferLength);
                      //add up the size so we know how much is downloaded
                      downloadedSize += bufferLength;
                      //this is where you would do something to report the prgress, like this maybe
                      Log.i("Progress:", "downloadedSize:" + downloadedSize + "totalSize:" + totalSize);
      
                  }
                  //close the output stream when done
                  fileOutput.close();
                  if (downloadedSize == totalSize) filepath = file.getPath();
      
                  //catch some possible errors...
              } catch (MalformedURLException e) {
                  e.printStackTrace();
              } catch (IOException e) {
                  filepath = null;
                  e.printStackTrace();
              }
              Log.i("filepath:", " " + filepath);
      
              return filepath;
      
      
          }
      
          @Override
          protected void onPostExecute(String s) {
              super.onPostExecute(s);
          }
      }
      

      【讨论】:

      • 请不要只写代码。也提供解释。看看如何answer
      • @Vinesh Chauhan 是否可以将文件从其 http url(即远程文件)发送到 whatsapp 或任何可共享媒体??
      • @KJEjava48 实际上,如果您将 URL 共享给 whatsapp 意图,它将仅作为 URL 共享,如果您希望将远程文件发送到 Whatapp 意图,您必须先下载文件
      【解决方案5】:

      首先您需要在 glide 中加载图片,然后您可以将其分享到任何地方。

      从 glide 加载图像的代码(图像正在保存到存储中,您可以稍后将其删除)

      Glide.with(getApplicationContext())
                          .load(imagelink)   \\link of your image file (url)
                          .asBitmap().skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE)
                          .into(new SimpleTarget<Bitmap>(250, 250) {@Override
                           public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {
      
      
                          Intent intent = new Intent(Intent.ACTION_SEND);
                          intent.putExtra(Intent.EXTRA_TEXT, "Hey view/download this image");
                          String path = MediaStore.Images.Media.insertImage(getContentResolver(), resource, "", null);
                          Log.i("quoteswahttodo", "is onresoursereddy" + path);
                          Uri screenshotUri = Uri.parse(path);
                          Log.i("quoteswahttodo", "is onresoursereddy" + screenshotUri);
                          intent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
                          intent.setType("image/*");
                          startActivity(Intent.createChooser(intent, "Share image via..."));  // if you want to share with whatsapp only replace with below code 
                      }
                      @Override public void onLoadFailed(Exception e, Drawable errorDrawable) {
                                  Toast.makeText(getApplicationContext(), "Something went wrong", Toast.LENGTH_SHORT).show();
      
      
                                  super.onLoadFailed(e, errorDrawable);
                              }
      
                      @Override public void onLoadStarted(Drawable placeholder) {
                                  Toast.makeText(getApplicationContext(), "Starting", Toast.LENGTH_SHORT).show();
                                  super.onLoadStarted(placeholder);
                     }
      });
      

      这里替换为 Whatsapp:

       sendd.setPackage("com.whatsapp");
       try {
               startActivity(sendd);
       } catch (Exception e) {
               Toast.makeText(FinishedDoing.this, "It seem like Whatsapp is not been installed", Toast.LENGTH_SHORT).show();
                      e.printStackTrace();
       }  
      

      【讨论】:

      • 我如何从 url 而不是图像共享任何类型的文件
      猜你喜欢
      • 2014-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多