我在该应用程序中有图像厨房应用程序我将所有图像放入drawable-hdpi文件夹中。 我在我的活动中调用了这样的图像:
private Integer[] imageIDs = {
R.drawable.wall1, R.drawable.wall2,
R.drawable.wall3, R.drawable.wall4,
R.drawable.wall5, R.drawable.wall6,
R.drawable.wall7, R.drawable.wall8,
R.drawable.wall9, R.drawable.wall10
};
所以现在我想知道我如何使用共享意图分享这个图像我推出的共享代码如下:
Button shareButton = (Button) findViewById(R.id.share_button);
shareButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
Uri screenshotUri = Uri.parse(Images.Media.EXTERNAL_CONTENT_URI + "/" + imageIDs);
sharingIntent.setType("image/jpeg");
sharingIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
startActivity(Intent.createChooser(sharingIntent, "Share image using"));
}
});
当我点击分享按钮分享框打开时,我也有共享按钮 但当我克服任何服务时,主要是崩溃或某些服务说:无法打开图像 那么我怎么能解决这个问题还是有任何其他格式代码来共享图像????
修改:
我尝试使用下面的代码。但它不起作用。
Button shareButton = (Button) findViewById(R.id.share_button);
shareButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
Uri screenshotUri = Uri.parse("android.resource://com.android.test/*");
try {
InputStream stream = getContentResolver().openInputStream(screenshotUri);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sharingIntent.setType("image/jpeg");
sharingIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
startActivity(Intent.createChooser(sharingIntent, "Share image using"));
}
});
如果不介意某人plz更正我的上述代码或给我一个正确的例子plz如何从drawable-hdpi文件夹分享我的图像
答案 0 :(得分:109)
Bitmap icon = mBitmap;
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_STREAM, Uri.parse("file:///sdcard/temporary_file.jpg"));
startActivity(Intent.createChooser(share, "Share Image"));
答案 1 :(得分:36)
superM提出的解决方案已经为我工作了很长时间,但最近我在4.2(HTC One)上测试了它并且它在那里停止工作。我知道这是一种解决方法,但它是唯一一款适用于所有设备和版本的解决方案。
根据文档,开发人员被要求"use the system MediaStore"发送二进制内容。但是,这具有(不)优势,即媒体内容将永久保存在设备上。
如果这是您的选项,您可能需要授予权限WRITE_EXTERNAL_STORAGE
并使用系统范围的MediaStore。
Bitmap icon = mBitmap;
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
ContentValues values = new ContentValues();
values.put(Images.Media.TITLE, "title");
values.put(Images.Media.MIME_TYPE, "image/jpeg");
Uri uri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI,
values);
OutputStream outstream;
try {
outstream = getContentResolver().openOutputStream(uri);
icon.compress(Bitmap.CompressFormat.JPEG, 100, outstream);
outstream.close();
} catch (Exception e) {
System.err.println(e.toString());
}
share.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(share, "Share Image"));
答案 2 :(得分:20)
首先添加权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
使用res中的位图
Bitmap b =BitmapFactory.decodeResource(getResources(),R.drawable.userimage);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(getContentResolver(),
b, "Title", null);
Uri imageUri = Uri.parse(path);
share.putExtra(Intent.EXTRA_STREAM, imageUri);
startActivity(Intent.createChooser(share, "Select"));
通过蓝牙和其他信使进行测试
像魅力一样工作。
答案 3 :(得分:16)
我发现最简单的方法是使用MediaStore临时存储您要共享的图像:
Drawable mDrawable = mImageView.getDrawable();
Bitmap mBitmap = ((BitmapDrawable) mDrawable).getBitmap();
String path = MediaStore.Images.Media.insertImage(getContentResolver(), mBitmap, "Image Description", null);
Uri uri = Uri.parse(path);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/jpeg");
intent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(intent, "Share Image"));
答案 4 :(得分:11)
简单易用的代码,您可以使用它来共享图库中的图像。
String image_path;
File file = new File(image_path);
Uri uri = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_SEND);
intent .setType("image/*");
intent .putExtra(Intent.EXTRA_STREAM, uri);
context.startActivity(intent );
答案 5 :(得分:11)
如何以机器方式在android中共享图像,有时您想拍摄视图的快照,然后想分享它 请按照以下步骤操作:1。添加mainfest文件的权限
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
2.Very首先拍摄视图的屏幕截图,例如它 Imageview,Textview,Framelayout,LinearLayout等
例如,您有一个图像视图来截取屏幕截图 在oncreate()
中调用此方法 ImageView image= (ImageView)findViewById(R.id.iv_answer_circle);
///take a creenshot
screenShot(image);
在按钮
上截取屏幕截图呼叫共享图像方法后
点击或你想要的地方
shareBitmap(screenShot(image),"myimage");
在创建方法之后定义这两个方法##
public Bitmap screenShot(View view) {
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(),
view.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}
//////// this method share your image
private void shareBitmap (Bitmap bitmap,String fileName) {
try {
File file = new File(getContext().getCacheDir(), fileName + ".png");
FileOutputStream fOut = new FileOutputStream(file);
bitmap.compress(CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
file.setReadable(true, false);
final Intent intent = new Intent( android.content.Intent.ACTION_SEND);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
intent.setType("image/png");
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
答案 6 :(得分:10)
这是一个适合我的解决方案。一个问题是您需要将图像存储在共享或非应用程序私有位置(http://developer.android.com/guide/topics/data/data-storage.html#InternalCache)
许多建议都说要存储在Apps
“私有”缓存位置,但这当然不能通过其他外部应用程序访问,包括正在使用的通用共享文件意图。当你尝试这个时,它会运行,但是例如dropbox会告诉你文件不再可用。
/ *步骤1 - 使用下面的文件保存功能在本地保存位图文件。 * /
localAbsoluteFilePath = saveImageLocally(bitmapImage);
/ *步骤2 - 将非私有绝对文件路径共享到共享文件意图* /
if (localAbsoluteFilePath!=null && localAbsoluteFilePath!="") {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
Uri phototUri = Uri.parse(localAbsoluteFilePath);
File file = new File(phototUri.getPath());
Log.d(TAG, "file path: " +file.getPath());
if(file.exists()) {
// file create success
} else {
// file create fail
}
shareIntent.setData(phototUri);
shareIntent.setType("image/png");
shareIntent.putExtra(Intent.EXTRA_STREAM, phototUri);
activity.startActivityForResult(Intent.createChooser(shareIntent, "Share Via"), Navigator.REQUEST_SHARE_ACTION);
}
/ *保存图像功能* /
private String saveImageLocally(Bitmap _bitmap) {
File outputDir = Utils.getAlbumStorageDir(Environment.DIRECTORY_DOWNLOADS);
File outputFile = null;
try {
outputFile = File.createTempFile("tmp", ".png", outputDir);
} catch (IOException e1) {
// handle exception
}
try {
FileOutputStream out = new FileOutputStream(outputFile);
_bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
} catch (Exception e) {
// handle exception
}
return outputFile.getAbsolutePath();
}
/ *第3步 - 处理共享文件意图结果。需要远程临时文件等* /
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// deal with this with whatever constant you use. i have a navigator object to handle my navigation so it also holds all mys constants for intents
if (requestCode== Navigator.REQUEST_SHARE_ACTION) {
// delete temp file
File file = new File (localAbsoluteFilePath);
file.delete();
Toaster toast = new Toaster(activity);
toast.popBurntToast("Successfully shared");
}
}
我希望能帮助别人。
答案 7 :(得分:7)
我厌倦了搜索从我的应用程序到其他应用程序共享视图或图像的不同选项。最后我得到了解决方案。
第1步: 分享意图处理阻止。这将弹出您的窗口,其中包含手机中的应用程序列表
public void share_bitMap_to_Apps() {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("image/*");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
/*compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] bytes = stream.toByteArray();*/
i.putExtra(Intent.EXTRA_STREAM, getImageUri(mContext, getBitmapFromView(relative_me_other)));
try {
startActivity(Intent.createChooser(i, "My Profile ..."));
} catch (android.content.ActivityNotFoundException ex) {
ex.printStackTrace();
}
}
第2步: 将视图转换为BItmap
public static Bitmap getBitmapFromView(View view) {
//Define a bitmap with the same size as the view
Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
//Bind a canvas to it
Canvas canvas = new Canvas(returnedBitmap);
//Get the view's background
Drawable bgDrawable = view.getBackground();
if (bgDrawable != null)
//has background drawable, then draw it on the canvas
bgDrawable.draw(canvas);
else
//does not have background drawable, then draw white background on the canvas
canvas.drawColor(Color.WHITE);
// draw the view on the canvas
view.draw(canvas);
//return the bitmap
return returnedBitmap;
}
第3步:
从位图图像获取URI
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
答案 8 :(得分:3)
我遇到了同样的问题。
这是一个答案,它不会在你的主代码中使用任何明确的文件写入(让api为你处理它)。
Drawable mDrawable = myImageView1.getDrawable();
Bitmap mBitmap = ((BitmapDrawable)mDrawable).getBitmap();
String path = MediaStore.Images.Media.insertImage(getContentResolver(), mBitmap, "Image I want to share", null);
Uri uri = Uri.parse(path);
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
shareIntent.setType("image/*");
startActivity(Intent.createChooser(shareIntent, "Share Image"));
这是路径...您只需要在Drawable对象中添加图像ID。 在我的情况下(上面的代码),drawable是从ImageView中提取的。
答案 9 :(得分:3)
参考: - http://developer.android.com/training/sharing/send.html#send-multiple-content
ArrayList<Uri> imageUris = new ArrayList<Uri>();
imageUris.add(imageUri1); // Add your image URIs here
imageUris.add(imageUri2);
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris);
shareIntent.setType("image/*");
startActivity(Intent.createChooser(shareIntent, "Share images to.."));
答案 10 :(得分:3)
SuperM答案对我有用,但是使用Uri.fromFile()而不是Uri.parse()。
使用Uri.parse(),它只适用于Whatsapp。
这是我的代码:
sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(mFile));
Uri.parse()的输出:
/storage/emulated/0/Android/data/application_package/Files/17072015_0927.jpg
Uri.fromFile的输出:
文件:///storage/emulated/0/Android/data/application_package/Files/17072015_0927.jpg
答案 11 :(得分:2)
试试这个,
Uri imageUri = Uri.parse("android.resource://your.package/drawable/fileName");
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/png");
intent.putExtra(Intent.EXTRA_STREAM, imageUri);
startActivity(Intent.createChooser(intent , "Share"));
答案 12 :(得分:2)
谢谢,我尝试了给出的几个选项,但这些选项似乎不适用于最新的android版本,因此添加了修改后的步骤以适用于最新的android版本。这些基于上面的一些答案,但是经过修改,解决方案基于File Provider的使用:
步骤:1
在清单文件中添加以下代码:
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_provider_paths" />
</provider>
步骤:2 在res> xml
中创建XML文件在xml内创建file_provider_paths文件。
请注意,这是我们在上一步中包含在android:resource中的文件。
在file_provider_paths中写入以下代码:
<?xml version="1.0" encoding="utf-8"?>
<paths>
<cache-path name="cache" path="/" />
<files-path name="files" path="/" />
</paths>
步骤:3
之后转到您的按钮,点击:
Button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Bitmap bit = BitmapFactory.decodeResource(context.getResources(), R.drawable.filename);
File filesDir = context.getApplicationContext().getFilesDir();
File imageFile = new File(filesDir, "birds.png");
OutputStream os;
try {
os = new FileOutputStream(imageFile);
bit.compress(Bitmap.CompressFormat.PNG, 100, os);
os.flush();
os.close();
} catch (Exception e) {
Log.e(getClass().getSimpleName(), "Error writing bitmap", e);
}
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Uri imageUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID, imageFile);
intent.putExtra(Intent.EXTRA_STREAM, imageUri);
intent.setType("image/*");
context.startActivity(intent);
}
});
有关详细说明,请访问https://droidlytics.wordpress.com/2020/08/04/use-fileprovider-to-share-image-from-recyclerview/
答案 13 :(得分:1)
通过Intent共享文本和图像的完美解决方案是:
在共享按钮上,单击:
Bitmap image;
shareimagebutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
URL url = null;
try {
url = new URL("https://firebasestorage.googleapis.com/v0/b/fir-notificationdemo-dbefb.appspot.com/o/abc_text_select_handle_middle_mtrl_light.png?alt=media&token=c624ab1b-f840-479e-9e0d-6fe8142478e8");
image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
shareBitmap(image);
}
});
然后创建shareBitmap(image)方法。
private void shareBitmap(Bitmap bitmap) {
final String shareText = getString(R.string.share_text) + " "
+ getString(R.string.app_name) + " developed by "
+ "https://play.google.com/store/apps/details?id=" + getPackageName() + ": \n\n";
try {
File file = new File(this.getExternalCacheDir(), "share.png");
FileOutputStream fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
file.setReadable(true, false);
final Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Intent.EXTRA_TEXT, shareText);
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
intent.setType("image/png");
startActivity(Intent.createChooser(intent, "Share image via"));
} catch (Exception e) {
e.printStackTrace();
}
}
然后进行测试.. !!
答案 14 :(得分:1)
实施更严格的安全策略后,在应用程序外部暴露uri会引发错误并导致应用程序崩溃。
@Ali Tamoor的答案说明了如何使用文件提供程序,这是推荐的方法。
有关更多详细信息,请参见-https://developer.android.com/training/secure-file-sharing/setup-sharing
此外,您还需要在项目中包含androidx核心库。
implementation "androidx.core:core:1.2.0"
当然,这是一个有点笨重的库,仅用于共享文件就需要它-如果有更好的方法,请告诉我。
答案 15 :(得分:0)
Strring temp="facebook",temp="whatsapp",temp="instagram",temp="googleplus",temp="share";
if(temp.equals("facebook"))
{
Intent intent = getPackageManager().getLaunchIntentForPackage("com.facebook.katana");
if (intent != null) {
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("image/png");
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + "/sdcard/folder name/abc.png"));
shareIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
shareIntent.setPackage("com.facebook.katana");
startActivity(shareIntent);
}
else
{
Toast.makeText(MainActivity.this, "Facebook require..!!", Toast.LENGTH_SHORT).show();
}
}
if(temp.equals("whatsapp"))
{
try {
File filePath = new File("/sdcard/folder name/abc.png");
final ComponentName name = new ComponentName("com.whatsapp", "com.whatsapp.ContactPicker");
Intent oShareIntent = new Intent();
oShareIntent.setComponent(name);
oShareIntent.setType("text/plain");
oShareIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Website : www.google.com");
oShareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(filePath));
oShareIntent.setType("image/jpeg");
oShareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
MainActivity.this.startActivity(oShareIntent);
} catch (Exception e) {
Toast.makeText(MainActivity.this, "WhatsApp require..!!", Toast.LENGTH_SHORT).show();
}
}
if(temp.equals("instagram"))
{
Intent intent = getPackageManager().getLaunchIntentForPackage("com.instagram.android");
if (intent != null)
{
File filePath =new File("/sdcard/folder name/"abc.png");
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("image");
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + "/sdcard/Chitranagari/abc.png"));
shareIntent.setPackage("com.instagram.android");
startActivity(shareIntent);
}
else
{
Toast.makeText(MainActivity.this, "Instagram require..!!", Toast.LENGTH_SHORT).show();
}
}
if(temp.equals("googleplus"))
{
try
{
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
String strDate = sdf.format(c.getTime());
Intent shareIntent = ShareCompat.IntentBuilder.from(MainActivity.this).getIntent();
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, "Website : www.google.com");
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + "/sdcard/folder name/abc.png"));
shareIntent.setPackage("com.google.android.apps.plus");
shareIntent.setAction(Intent.ACTION_SEND);
startActivity(shareIntent);
}catch (Exception e)
{
e.printStackTrace();
Toast.makeText(MainActivity.this, "Googleplus require..!!", Toast.LENGTH_SHORT).show();
}
}
if(temp.equals("share")) {
File filePath =new File("/sdcard/folder name/abc.png"); //optional //internal storage
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_TEXT, "Website : www.google.com");
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(filePath)); //optional//use this when you want to send an image
shareIntent.setType("image/jpeg");
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(shareIntent, "send"));
}
答案 16 :(得分:0)
所有上述解决方案在Android Api 26 & 27 (Oreo)
中不适用于我,Error: exposed beyond app through ClipData.Item.getUri
。适合我情况的解决方案是
FileProvider.getUriForFile(Context,packagename,File)
作为void shareImage() {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(this,getPackageName(),deleteFilePath));
startActivity(Intent.createChooser(intent,"Share with..."));
}
<provider>
中将Manifest.xml
定义为<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.example.stickerapplication"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths">
</meta-data>
</provider>
resource
文件<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="." />
</paths>
*Note this solution is for `external storage` `uri`
答案 17 :(得分:0)
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Log.d(TAG, "Permission granted");
} else {
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
100);
}
fab.setOnClickListener(v -> {
Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.refer_pic);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/*");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(requireActivity().getContentResolver(),
b, "Title", null);
Uri imageUri = Uri.parse(path);
share.putExtra(Intent.EXTRA_STREAM, imageUri);
share.putExtra(Intent.EXTRA_TEXT, "Here is text");
startActivity(Intent.createChooser(share, "Share via"));
});