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 {
EditText imgUrl, text;
Button btn;
ProgressBar progressBar;
@Override
protected
void
onCreate(Bundle savedInstanceState)
{
super
.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgUrl = findViewById(R.id.img_url);
text = findViewById(R.id.text);
btn = findViewById(R.id.button);
progressBar = findViewById(R.id.progressBar);
btn.setOnClickListener(view -> {
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);
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();
}
});
}
}