Как совместно использовать изображение + текст, используя ACTION_SEND в android?
Я хочу поделиться текстом + изображение вместе с помощью ACTION_SEND в android, я использую код ниже, я могу использовать только изображение, но я не могу обмениваться текстом с ним,
private Uri imageUri;
private Intent intent;
imageUri = Uri.parse("android.resource://" + getPackageName()+ "/drawable/" + "ic_launcher");
intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, "Hello");
intent.putExtra(Intent.EXTRA_STREAM, imageUri);
intent.setType("image/*");
startActivity(intent);
Любая помощь по этому поводу?
Ответы
Ответ 1
вы можете обмениваться простым текстом с помощью этих кодов
String shareBody = "Here is the share content body";
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject Here");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, getResources().getString(R.string.share_using)));
поэтому ваш полный код (ваше изображение + текст) станет
private Uri imageUri;
private Intent intent;
imageUri = Uri.parse("android.resource://" + getPackageName()
+ "/drawable/" + "ic_launcher");
intent = new Intent(Intent.ACTION_SEND);
//text
intent.putExtra(Intent.EXTRA_TEXT, "Hello");
//image
intent.putExtra(Intent.EXTRA_STREAM, imageUri);
//type of things
intent.setType("*/*");
//sending
startActivity(intent);
Я только что заменил image/*
на */*
Обновление
Uri imageUri = Uri.parse("android.resource://" + getPackageName()
+ "/drawable/" + "ic_launcher");
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_TEXT, "Hello");
shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
shareIntent.setType("image/jpeg");
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(shareIntent, "send"));
Ответ 2
пожалуйста, посмотрите на этот код, чтобы я мог совместно использовать текст и изображение.
Intent shareIntent;
Bitmap bitmap= BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher);
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)+"/Share.png";
OutputStream out = null;
File file=new File(path);
try {
out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
path=file.getPath();
Uri bmpUri = Uri.parse("file://"+path);
shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
shareIntent.putExtra(Intent.EXTRA_TEXT,"Hey please check this application " + "https://play.google.com/store/apps/details?id=" +getPackageName());
shareIntent.setType("image/png");
startActivity(Intent.createChooser(shareIntent,"Share with"));
Не забудьте указать WRITE_EXTERNAL_STORAGE Разрешение
также в facebook он может делиться только изображением, потому что facebook не позволяет обмениваться текстом с помощью намерения
Ответ 3
Возможно, это связано с тем, что приложение для обмена (FB, Twitter и т.д.) Может не иметь прав для чтения изображения.
Документ Google гласит:
Получающему приложению требуется разрешение для доступа к данным, на которые указывает Uri. Рекомендуемые способы сделать это:
http://developer.android.com/training/sharing/send.html
Я не уверен, что приложения для обмена имеют разрешения на чтение изображения в комплекте наших приложений. Но мои файлы сохранены в
Activity.getFilesDir()
не может быть прочитано Как указано в приведенной выше ссылке, мы можем рассмотреть возможность хранения изображений в MediaStore, где приложения для обмена имеют разрешения на чтение.
Обновление 1: ниже приведен рабочий код для обмена изображением с текстом в Android 4.4.
Bitmap bm = BitmapFactory.decodeFile(file.getPath());
intent.putExtra(Intent.EXTRA_TEXT, Constant.SHARE_MESSAGE
+ Constant.SHARE_URL);
String url= MediaStore.Images.Media.insertImage(this.getContentResolver(), bm, "title", "description");
intent.putExtra(Intent.EXTRA_STREAM, Uri.parse(url));
intent.setType("image/*");
startActivity(Intent.createChooser(intent, "Share Image"));
Побочным эффектом является добавление изображения в MediaStore.
Ответ 4
Я искал решение этого вопроса какое-то время и нашел, что он работает, надеюсь, что это поможет.
private BitmapDrawable bitmapDrawable;
private Bitmap bitmap1;
//write this code in your share button or function
bitmapDrawable = (BitmapDrawable) mImageView.getDrawable();// get the from imageview or use your drawable from drawable folder
bitmap1 = bitmapDrawable.getBitmap();
String imgBitmapPath= MediaStore.Images.Media.insertImage(getContentResolver(),bitmap1,"title",null);
Uri imgBitmapUri=Uri.parse(imgBitmapPath);
String shareText="Share image and text";
Intent shareIntent=new Intent(Intent.ACTION_SEND);
shareIntent.setType("*/*");
shareIntent.putExtra(Intent.EXTRA_STREAM,imgBitmapUri);
shareIntent.putExtra(Intent.EXTRA_TEXT, shareText);
startActivity(Intent.createChooser(shareIntent,"Share Wallpaper using"));
Ответ 5
попробуйте использовать этот код. Я загружаю ic_launcher из drawable.you можно изменить это с вашим файлом из gallary или bitmap.
void share() {
Bitmap icon = BitmapFactory.decodeResource(getResources(),
R.drawable.ic_launcher);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
icon.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "temporary_file.jpg");
try {
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
share.putExtra(Intent.EXTRA_TEXT, "hello #test");
share.putExtra(Intent.EXTRA_STREAM,
Uri.parse("file:///sdcard/temporary_file.jpg"));
startActivity(Intent.createChooser(share, "Share Image"));
}
Ответ 6
String text = "Look at my awesome picture";
Uri pictureUri = Uri.parse("file://my_picture");
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_TEXT, text);
shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
shareIntent.setType("image/*");
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(shareIntent, "Share images..."));
Ответ 7
Проверьте код ниже, он работал для меня
Picasso.with(getApplicationContext()).load("image url path").into(new Target() {
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
Intent i = new Intent(Intent.ACTION_SEND);
i.putExtra(Intent.EXTRA_TEXT, "Let me recommend you this application" +
"\n"+ "your share url or text ");
i.setType("image/*");
i.putExtra(Intent.EXTRA_STREAM, getLocalBitmapUri(bitmap));
context.startActivity(Intent.createChooser(i, "Share using"));
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
private Uri getLocalBitmapUri(Bitmap bmp) {
Uri bmpUri = null;
try {
File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), "share_image_" + System.currentTimeMillis() + ".png");
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 50, out);
out.close();
bmpUri = Uri.fromFile(file);
} catch (IOException e) {
e.printStackTrace();
}
return bmpUri;
}
Ответ 8
Чтобы поделиться нарисованным изображением, оно должно быть сначала сохранено в кеше устройства или во внешнем хранилище.
Мы проверяем, существует ли "sharable_image.jpg" в кэше, если существует, путь извлекается из существующего файла.
Иначе, нарисованное изображение сохраняется в кеше.
Сохраненное изображение затем передается с использованием намерения.
private void share() {
int sharableImage = R.drawable.person2;
Bitmap bitmap= BitmapFactory.decodeResource(getResources(), sharableImage);
String path = getExternalCacheDir()+"/sharable_image.jpg";
java.io.OutputStream out;
java.io.File file = new java.io.File(path);
if(!file.exists()) {
try {
out = new java.io.FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
path = file.getPath();
Uri bmpUri = Uri.parse("file://" + path);
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
shareIntent.putExtra(Intent.EXTRA_TEXT, "This is a sample body with more detailed description");
shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
shareIntent.setType("image/*");
startActivity(Intent.createChooser(shareIntent,"Share with"));
}
Ответ 9
Случайно (часть текстового сообщения, я отказался от этого), я заметил, что когда я выбрал Message App для обработки запроса, приложение Message откроется с текстом из Intent.EXTRA_SUBJECT плюс изображение, готовое для отправки, Я надеюсь, что это поможет.
String[] recipient = {"your_email_here"};
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_EMAIL, recipient);
intent.putExtra(Intent.EXTRA_SUBJECT, "Hello, this is the subject line");
intent.putExtra(Intent.EXTRA_TEXT, messageEditText.getText().toString());
intent.putExtra(Intent.EXTRA_STREAM, imageUri);
intent.setType("image/*");
Ответ 10
String bitmapPath = MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, "title", null);
Uri bitmapUri = Uri.parse(bitmapPath);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/png");
intent.putExtra(Intent.EXTRA_STREAM, bitmapUri);
intent.putExtra(Intent.EXTRA_TEXT, "This is a playstore link to download.. " + "https://play.google.com/store/apps/details?id=" + getPackageName());
startActivity(Intent.createChooser(intent, "Share"));