如何以编程方式将图片从图库分享到 WhatsApp? [英] How to share Image to WhatsApp from Gallery programmatically?
问题描述
我尝试使用以下代码将图像分享到 WhatsApp.目前,我手动添加了图片路径.
我想在用户单击我的应用程序中的按钮时打开图库,并且他必须能够选择要在 WhatsApp 中共享的图像.
我该怎么做?
PS:我需要动态设置图片路径
button.setOnClickListener(new View.OnClickListener() {@覆盖public void onClick(View v) {Toast.makeText(MainActivity.this, "Testing Button", Toast.LENGTH_SHORT).show();File f=new File("/sdcard/Download/myimage.jpg");Uri uri = Uri.parse("file://"+f.getAbsolutePath());意图份额 = 新意图(Intent.ACTION_SEND);share.setPackage("com.whatsapp");share.putExtra(Intent.EXTRA_STREAM, uri);share.setType("图像/*");share.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);v.getContext().startActivity(Intent.createChooser(share, "Share image File"));}});
您可以使用以下代码动态获取图像 Uri.它将适用于所有版本的 Android.
主活动
public class MainActivity extends Activity {@覆盖protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);意图意图=新意图(Intent.ACTION_GET_CONTENT);intent.setType("image/*");startActivityForResult(intent, 0);}@覆盖protected void onActivityResult(int reqCode, int resCode, Intent data) {if(resCode == Activity.RESULT_OK && 数据 != null){字符串真实路径;如果 (Build.VERSION.SDK_INT < 11)realPath = RealPathUtil.getRealPathFromURI_BelowAPI11(this, data.getData());否则如果(Build.VERSION.SDK_INT <19)realPath = RealPathUtil.getRealPathFromURI_API11to18(this, data.getData());别的realPath = RealPathUtil.getRealPathFromURI_API19(this, data.getData());getImageInfo(Build.VERSION.SDK_INT, data.getData().getPath(),realPath);}}private void getImageInfo(int sdk, String uriPath,String realPath){Uri uriFromPath = Uri.fromFile(new File(realPath));Log.d("Log", "Build.VERSION.SDK_INT:"+sdk);Log.d("Log", "URI 路径:"+uriPath);Log.d("Log", "真实路径:"+realPath);}}
RealPathUtil.java
import android.annotation.SuppressLint;导入 android.content.Context;导入 android.content.CursorLoader;导入 android.database.Cursor;导入android.net.Uri;导入 android.provider.DocumentsContract;导入 android.provider.MediaStore;公共类 RealPathUtil {@SuppressLint("NewApi")公共静态字符串 getRealPathFromURI_API19(上下文上下文,Uri uri){字符串文件路径 = "";String WholeID = DocumentsContract.getDocumentId(uri);//在冒号处拆分,使用数组中的第二项String id = WholeID.split(":")[1];String[] column = { MediaStore.Images.Media.DATA };//其中 id 等于String sel = MediaStore.Images.Media._ID + "=?";Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,列, sel, 新字符串[]{ id }, null);int columnIndex = cursor.getColumnIndex(column[0]);如果 (cursor.moveToFirst()) {filePath = cursor.getString(columnIndex);}游标.关闭();返回文件路径;}@SuppressLint("NewApi")public static String getRealPathFromURI_API11to18(Context context, Uri contentUri) {String[] proj = { MediaStore.Images.Media.DATA };字符串结果 = null;CursorLoader cursorLoader = new CursorLoader(语境,contentUri, proj, null, null, null);Cursor cursor = cursorLoader.loadInBackground();如果(光标!= null){int column_index =cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);cursor.moveToFirst();结果 = cursor.getString(column_index);}返回结果;}public static String getRealPathFromURI_BelowAPI11(Context context, Uri contentUri){String[] proj = { MediaStore.Images.Media.DATA };Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);整数列索引= cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);cursor.moveToFirst();返回 cursor.getString(column_index);}}
将此权限添加到 Manifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<块引用>
在 Android 6+ 中,您需要在运行时请求权限.
I tried the following code to share an image to WhatsApp. For now, I manually added the image path.
I want to open the gallery when the user clicks a button in my application and he must be able to select an image to share in WhatsApp.
How can I do that?
PS: I need to set the image path dynamically
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Testing Button", Toast.LENGTH_SHORT).show();
File f=new File("/sdcard/Download/myimage.jpg");
Uri uri = Uri.parse("file://"+f.getAbsolutePath());
Intent share = new Intent(Intent.ACTION_SEND);
share.setPackage("com.whatsapp");
share.putExtra(Intent.EXTRA_STREAM, uri);
share.setType("image/*");
share.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
v.getContext().startActivity(Intent.createChooser(share, "Share image File"));
}
});
You can use the below code to dynamically get the image Uri. It will work on all versions of Android.
MainActivity
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 0);
}
@Override
protected void onActivityResult(int reqCode, int resCode, Intent data) {
if(resCode == Activity.RESULT_OK && data != null){
String realPath;
if (Build.VERSION.SDK_INT < 11)
realPath = RealPathUtil.getRealPathFromURI_BelowAPI11(this, data.getData());
else if (Build.VERSION.SDK_INT < 19)
realPath = RealPathUtil.getRealPathFromURI_API11to18(this, data.getData());
else
realPath = RealPathUtil.getRealPathFromURI_API19(this, data.getData());
getImageInfo(Build.VERSION.SDK_INT, data.getData().getPath(),realPath);
}
}
private void getImageInfo(int sdk, String uriPath,String realPath){
Uri uriFromPath = Uri.fromFile(new File(realPath));
Log.d("Log", "Build.VERSION.SDK_INT:"+sdk);
Log.d("Log", "URI Path:"+uriPath);
Log.d("Log", "Real Path: "+realPath);
}
}
RealPathUtil.java
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.CursorLoader;
import android.database.Cursor;
import android.net.Uri;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
public class RealPathUtil {
@SuppressLint("NewApi")
public static String getRealPathFromURI_API19(Context context, Uri uri){
String filePath = "";
String wholeID = DocumentsContract.getDocumentId(uri);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String[] column = { MediaStore.Images.Media.DATA };
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{ id }, null);
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
return filePath;
}
@SuppressLint("NewApi")
public static String getRealPathFromURI_API11to18(Context context, Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
String result = null;
CursorLoader cursorLoader = new CursorLoader(
context,
contentUri, proj, null, null, null);
Cursor cursor = cursorLoader.loadInBackground();
if(cursor != null){
int column_index =
cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
result = cursor.getString(column_index);
}
return result;
}
public static String getRealPathFromURI_BelowAPI11(Context context, Uri contentUri){
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index
= cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}
Add this Permission to Manifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
In Android 6+, You need to request the Permission during RunTime.
这篇关于如何以编程方式将图片从图库分享到 WhatsApp?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!