Поделиться изображением с URL андроид поделиться намерением
Мне нужно знать, возможно ли поделиться изображением, используя только его URL с намерением поделиться. Вот мой код
Intent imageIntent = new Intent(Intent.ACTION_SEND);
Uri imageUri = Uri.parse("http://eofdreams.com/data_images/dreams/face/face-03.jpg");
imageIntent.setType("image/*");
imageIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
startActivity(imageIntent);
Пока что он не работает, и я не нашел никаких полезных ответов в Интернете. Я хотел бы сделать это, используя намерение поделиться и без загрузки изображения.
5 ответов
Вы можете поделиться изображением, используя намерение поделиться, но вы должны декодировать изображение в локализованное растровое изображение
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, "Hey view/download this image");
String path = Images.Media.insertImage(getContentResolver(), loadedImage, "", null);
Uri screenshotUri = Uri.parse(path);
intent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
intent.setType("image/*");
startActivity(Intent.createChooser(intent, "Share image via..."));
loadedImage
загруженное растровое изображение с http://eofdreams.com/data_images/dreams/face/face-03.jpg
Смотрите здесь ЗДЕСЬ
final ImageView imgview= (ImageView)findViewById(R.id.feedImage1);
Uri bmpUri = getLocalBitmapUri(imgview);
if (bmpUri != null) {
// Construct a ShareIntent with link to image
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
shareIntent.setType("image/*");
// Launch sharing dialog for image
startActivity(Intent.createChooser(shareIntent, "Share Image"));
} else {
// ...sharing failed, handle error
}
затем добавьте это к своей деятельности:
public Uri getLocalBitmapUri(ImageView imageView) {
// Extract Bitmap from ImageView drawable
Drawable drawable = imageView.getDrawable();
Bitmap bmp = null;
if (drawable instanceof BitmapDrawable){
bmp = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
} else {
return null;
}
// Store image to default external storage directory
Uri bmpUri = null;
try {
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), "share_image_" + System.currentTimeMillis() + ".png");
file.getParentFile().mkdirs();
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
bmpUri = Uri.fromFile(file);
} catch (IOException e) {
e.printStackTrace();
}
return bmpUri;
}
Я пробовал несколько методов, однако ни один из них не работал у меня, и части операций были неясны, поэтому вот что я использую для обмена контентом типа изображения или видео в случае, если у меня есть абсолютный путь к данным.
В файле android manifest.xml добавьте следующие строки:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
//Other codes
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.example.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths" />
</provider>
//Other codes
</application>
В каталоге ресурсов res создайте новую папку с именем xml . Поместите в него новый файл с тем же именем, которое вы использовали в manifest.xml в части метаданных, в данном случае provider_paths.xml :
android:resource="@xml/provider_paths"
Поместите в него следующее:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path
name="external_files"
path="." />
<root-path
name="external_files"
path="/storage/"/>
</paths>
В действии, в котором вы хотите использовать функцию общего доступа, поместите следующий код, где путь — это строковая переменная, содержащая абсолютный путь к содержимому, а «com.example.fileprovider» — значение автора Fileprovider основано на одном из строка нового xml-файла, созданного выше, например:
android:authorities="com.example.fileprovider"
File file = new File(path);
//Checking if the file exists
if(file.exists()) {
//Creating the Uri for the file using the provider we just created
Uri contentUri =
FileProvider.getUriForFile(Gallery.this,"com.example.fileprovider", file);
//Creating the share intent
Intent S = new Intent(Intent.ACTION_SEND);
//Allowing different types to be shared
S.setType("*/*");
S.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//Providing the uri to the intent
S.putExtra(Intent.EXTRA_STREAM, contentUri);
//Starting the intent, can choose from apps which are listening for the
//content type
startActivity(Intent.createChooser(S, "Share content using"));
}
else{
Toast.makeText(getApplicationContext(),path + " does not
exist",Toast.LENGTH_SHORT).show();
}
Благодаря этому легко обмениваться контентом с устройства с помощью пути к нему. Полномочия и значения ресурсов имеют решающее значение в manifest.xml. Конечно, их можно изменить, но обязательно меняйте их при любых обстоятельствах.
Ресурсы :
Android Share Intent Совместное использование изображений не работает, кроме WhatsApp
https://www.geeksforgeeks.org/how-to-share-image-from-url-with-intent-in-android/
Конвертировать URL в формат строки
Intent imageIntent = new Intent(Intent.ACTION_SEND);
Uri imageUri = Uri.parse("http://eofdreams.com/data_images/dreams/face/face-03.jpg");
imageIntent.setType("image/*");
imageIntent.putExtra(Intent.EXTRA_STREAM, String.valueOf(imageUri));
startActivity(imageIntent);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT,"http://eofdreams.com/data_images/dreams/face/face-03.jpg");
startActivity(Intent.createChooser(intent, "Share Image"));