Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
How to Load Image From URL in Android using Jetpack Compose?
Next article icon

How to Share Image From URL with Intent in Android?

Last Updated : 26 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will see how can we share images and text with Android Intent. In this activity URL of an image to be shared will be given with extra text and we will open the Dialog where the user chooses using which he wants to share this image as shown on the screen. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.

Step by Step Implementation

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.

Step 2: Working with the activity_main.xml file

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. 

XML
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout      xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:app="http://schemas.android.com/apk/res-auto"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     tools:context=".MainActivity">      <TextView         android:id="@+id/textView"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_marginTop="32dp"         android:text="Image Sharing Intent"         android:textSize="24sp"         app:layout_constraintEnd_toEndOf="parent"         app:layout_constraintStart_toStartOf="parent"         app:layout_constraintTop_toTopOf="parent" />      <EditText         android:id="@+id/img_url"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:layout_marginTop="28dp"         android:layout_marginLeft="20dp"         android:layout_marginRight="20dp"         android:ems="10"         android:minHeight="48dp"         android:hint="Image Url"         app:layout_constraintEnd_toEndOf="parent"         app:layout_constraintHorizontal_bias="0.497"         app:layout_constraintStart_toStartOf="parent"         app:layout_constraintTop_toBottomOf="@+id/textView" />      <EditText         android:id="@+id/text"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:layout_marginTop="28dp"         android:layout_marginLeft="20dp"         android:layout_marginRight="20dp"         android:ems="10"         android:minHeight="48dp"         android:hint="Extra Text"         app:layout_constraintEnd_toEndOf="parent"         app:layout_constraintStart_toStartOf="parent"         app:layout_constraintTop_toBottomOf="@+id/img_url" />      <Button         android:id="@+id/button"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_marginTop="44dp"         android:text="Share"         app:layout_constraintEnd_toEndOf="parent"         app:layout_constraintHorizontal_bias="0.498"         app:layout_constraintStart_toStartOf="parent"         app:layout_constraintTop_toBottomOf="@+id/text" />      <ProgressBar         android:id="@+id/progressBar"         style="?android:attr/progressBarStyle"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_marginTop="44dp"         android:visibility="gone"         app:layout_constraintEnd_toEndOf="parent"         app:layout_constraintHorizontal_bias="0.498"         app:layout_constraintStart_toStartOf="parent"         app:layout_constraintTop_toBottomOf="@+id/text" />  </androidx.constraintlayout.widget.ConstraintLayout> 

Now you will get the Layout. Let's write the logic now.

Step 3: Working with the MainActivity.java file

Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. 

Java
package com.example.imageshare;  import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.Random;  public class MainActivity extends AppCompatActivity {     // lateinit declaration of views      EditText imgUrl, text;     Button btn;     ProgressBar progressBar;      @Override     protected void onCreate(Bundle savedInstanceState)     {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);          // reference of views         imgUrl = findViewById(R.id.img_url);         text = findViewById(R.id.text);         btn = findViewById(R.id.button);         progressBar = findViewById(R.id.progressBar);          // On Click listener will trigger code as soon as         // some clicks on the button         btn.setOnClickListener(view -> {             // validation condition to check if the any text             // is entered in the edit text fields or not             if (TextUtils.isEmpty(                     imgUrl.getText().toString())                 || TextUtils.isEmpty(                     text.getText().toString())) {                 Toast                     .makeText(MainActivity.this,                               "Please fill All Details",                               Toast.LENGTH_SHORT)                     .show();             }             else {                 progressBar.setVisibility(View.VISIBLE);                 btn.setVisibility(View.GONE);                 // Creating New thread                 Thread thread = new Thread(() ->                      URL url = null;                     try {                     url = new URL(                         imgUrl.getText().toString());                     } catch (MalformedURLException e) {                     e.printStackTrace();                     }                     HttpURLConnection connection = null;                     try {                     assert url != null;                     connection = (HttpURLConnection)                                      url.openConnection();                     } catch (IOException e) {                     e.printStackTrace();                     }                     assert connection != null;                     connection.setDoInput(true);                     try {                     connection.connect();                     } catch (IOException e) {                     e.printStackTrace();                     }                     InputStream input = null;                     try {                     input = connection.getInputStream();                     } catch (IOException e) {                     e.printStackTrace();                     }                     Bitmap imgBitmap = BitmapFactory.decodeStream(input);                     Random rand = new Random();                     int randNo = rand.nextInt(100000);                     String imgBitmapPath = MediaStore.Images.Media.insertImage(getContentResolver(), imgBitmap, "IMG:" + randNo, null);                     Uri imgBitmapUri = Uri.parse(imgBitmapPath);                      Intent shareIntent = new Intent(Intent.ACTION_SEND);                     shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);                     shareIntent.putExtra(Intent.EXTRA_STREAM, imgBitmapUri);                     shareIntent.setType("image/png");                     shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);                     shareIntent.putExtra(Intent.EXTRA_TEXT, text.getText().toString());                     startActivity(Intent.createChooser(shareIntent, "Share with"));                     progressBar.setVisibility(View.GONE);                     btn.setVisibility(View.VISIBLE);             });             thread.start();             }     }); } } 

Below is the Kotlin Implementation of above code. Refer the below code for MainActivity.kt file.  Comments are added inside the code to understand the code in more detail.

Please keep in mind that in Kotlin, however the approach outlined below works perfectly for the simple task at hand. Moreover, according to Google Developers documentation, Coroutines are preferred over Threads.

Kotlin
import android.content.Intent import android.graphics.BitmapFactory import android.net.Uri import android.os.Bundle import android.provider.MediaStore import android.text.TextUtils import android.view.View import android.widget.Button import android.widget.EditText import android.widget.ProgressBar import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import java.io.IOException import java.io.InputStream import java.net.HttpURLConnection import java.net.MalformedURLException import java.net.URL import java.util.* import kotlin.concurrent.thread   class MainActivity : AppCompatActivity() {      // lateinit declaration of views     lateinit var imgUrl: EditText     lateinit var text: EditText     lateinit var btn: Button     lateinit var progressBar: ProgressBar      override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main)          // reference of views         imgUrl = findViewById(R.id.img_url)         text = findViewById(R.id.text)         btn = findViewById(R.id.button)         progressBar = findViewById(R.id.progressBar)          // On Click listener will trigger code as soon as some clicks on the button         btn.setOnClickListener {             // validation condition to check if the any text is entered in the edit text fields or not             if(TextUtils.isEmpty(imgUrl.getText().toString()) || TextUtils.isEmpty(text.getText().toString())){                 Toast.makeText(this, "Please fill All Details", Toast.LENGTH_SHORT).show()             } else {                 // make progress bar visible                 progressBar.setVisibility(View.VISIBLE)                 btn.setVisibility(View.GONE)                  // Creating New thread                 thread {                     var url: URL? = null                     try {                         // get url from EditText view and converting                         // it to the URL                         url = URL(imgUrl.text.toString())                     } catch (e: MalformedURLException) {                         // will invoke if invalid url is entered                         e.printStackTrace()                     }                     var connection: HttpURLConnection? = null                     try {                         assert(url != null)                         connection = url!!.openConnection() as HttpURLConnection                     } catch (e: IOException) {                         e.printStackTrace()                     }                     assert(connection != null)                     connection!!.doInput = true                     try {                         connection.connect()                     } catch (e: IOException) {                         e.printStackTrace()                     }                     var input: InputStream? = null                     try {                         input = connection.inputStream                     } catch (e: IOException) {                         e.printStackTrace()                     }                     // generation of image form url Input                     val imgBitmap = BitmapFactory.decodeStream(input)                     val rand = Random()                     val randNo = rand.nextInt(100000)                     val imgBitmapPath = MediaStore.Images.Media.insertImage(                         contentResolver, imgBitmap,                         "IMG:$randNo", null                     )                     val imgBitmapUri = Uri.parse(imgBitmapPath)                       // share Intent                     val shareIntent = Intent(Intent.ACTION_SEND)                     shareIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK                     shareIntent.putExtra(Intent.EXTRA_STREAM, imgBitmapUri)                     shareIntent.type = "image/png"                     shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)                     shareIntent.putExtra(Intent.EXTRA_TEXT, text.text.toString())                     // Open the chooser dialog box                     startActivity(Intent.createChooser(shareIntent, "Share with"))                                          // disappear the progress bar view                      progressBar.visibility = View.GONE                     btn.visibility = View.VISIBLE                 }.start()             }         }     } } 

Now run the app in an emulator or Device you should get output like in the video.

Output:


Next Article
How to Load Image From URL in Android using Jetpack Compose?

V

vaibhavkhating
Improve
Article Tags :
  • Java
  • Android
Practice Tags :
  • Java

Similar Reads

  • How to Load SVG from URL in Android ImageView?
    It is seen that many Android apps require to use of high-quality images that will not get blur while zooming. So we have to use high-quality images. But if we are using PNG images then they will get blur after zooming because PNG images are made up of pixels and they will reduce their quality after
    4 min read
  • How to Load Image From URL in Android using Jetpack Compose?
    Most of the applications in android use images for displaying some useful information within the applications. Images are considered as easy to convey information to the user. An android application uses more than 100 different types of images. So it is not practically possible to add all the images
    4 min read
  • How to Send Email in Android App Without Using Intent?
    It is crucial to establish an email connection in the Android application. This enables us to send important messages to users. For example, when the user joins the app first time sending a welcome email is a common practice. Additionally in some applications if a user signs in from a new location a
    5 min read
  • How to Share Image of Your App with Another App in Android?
    Most of the time while using an app we want to share images from the app to another app. While using Many Social Media Platforms we find this feature to be very useful when we want to share information from one app to another. The Android Intent resolver is used when sending data to another app as p
    4 min read
  • How to Play Video from URL in Android?
    In this article, you will see how to play a video from a URL on Android. For showing the video in our Android application we will use the VideoView widget. The VideoView widget is capable of playing media files, and the formats supported by the VideoView are 3gp and MP4. By using VideoView you can p
    3 min read
  • How to Retrieve Image from Firebase in Realtime in Android?
    When we are creating an android app then instead of inserting an image manually we want to get that from the internet and using this process the app size will become less. So, using firebase we can do this. We can create our storage bucket and we can insert our image there and get it directly into o
    4 min read
  • Load PDF From URL in Android with Kotlin
    PDF View is most of the applications to display the PDF files within the application to display the pdf within our own application rather than redirecting to another application. If we want to display multiple pdf files within our application we have to host these files and then access these files w
    4 min read
  • Pick Color From Image with TouchEvents in Android
    In this article, we are going to learn how to get touched pixel color on an image. A Screenshot is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language.  Step by Step Implementation Step 1:  To create a n
    2 min read
  • How to Load PDF from URL in Android?
    Most of the apps require to include support to display PDF files in their app. So if we have to use multiple PDF files in our app it is practically not possible to add each PDF file inside our app because this approach may lead to an increase in the size of the app and no user would like to download
    5 min read
  • How to Open PDF From URL in Android Without Any Third Party Libraries?
    There are lots of libraries that are available online but it takes lots of space and time to render you can see these articles if you want to load pdf using third-party libraries Load PDF from URL in Android. But today we are going to load PDFs without using any third-party libraries the main purpos
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences