我的应用程序在原始文件夹中有一张照片。我想为用户提供选项,将该图像设置为壁纸或个人资料图片。选择该选项后,将弹出一个对话框。像这样:
我尝试使用以下代码显示此对话框
int resId = R.raw.a_day_without_thinking_mobile;
Resources resources = this.getResources();
Uri sendUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + resources.getResourcePackageName(resId) + '/' + resources.getResourceTypeName(resId) + '/' + resources.getResourceEntryName(resId));
Intent intent = new Intent(Intent.ACTION_ATTACH_DATA);
intent.setDataAndType(sendUri, "image/jpg");
intent.putExtra("mimeType", "image/jpg");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(intent, "Set As"));
但这给我看了一个像这样的对话:
我不想直接将图片设置为墙纸,而是应该显示一个对话框,用户可以从中选择是否要将图像用作壁纸或个人资料图片。
答案 0 :(得分:1)
首先,您必须将图像文件从原始文件夹下载到SD卡,然后使用SD卡文件将图像设置为壁纸
int resId = R.raw.a_day_without_thinking_mobile;
String filename = getResources().getResourceEntryName(resId );
String destfolder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath() + "/Motivational Quotes";
createDirIfNotExists(destfolder);
String destinationPath = destfolder +"/"+ filename + ".jpg";
File destination = new File(destinationPath);
InputStream ins = getResources().openRawResource(
getResources().getIdentifier(filename,
"raw", getPackageName()));
try {
copy2(ins,destination);
//Toast.makeText(this, "Image Downloaded", Toast.LENGTH_SHORT).show();
File externalFile=new File(destinationPath);
Uri sendUri2 = Uri.fromFile(externalFile);
Log.d("URI:", sendUri2.toString());
Intent intent = new Intent(Intent.ACTION_ATTACH_DATA);
intent.setDataAndType(sendUri2, "image/jpg");
intent.putExtra("mimeType", "image/jpg");
startActivityForResult(Intent.createChooser(intent, "Set As"), 200);
} catch (IOException e) {
e.printStackTrace();
}
public void copy2(InputStream src, File dst) throws IOException {
InputStream in = src;
OutputStream out = new FileOutputStream(dst);
//InputStream in = new FileInputStream(src);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
addImageGallery(dst);
}
private void addImageGallery( File file ) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg"); // setar isso
values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
}
public static boolean createDirIfNotExists(String path) {
boolean ret = true;
File file = new File(path);
if (!file.exists()) {
if (!file.mkdirs()) {
Log.e("TravellerLog :: ", "Problem creating Image folder");
ret = false;
}
}
return ret;
}
以下是您可以使用的代码
答案 1 :(得分:0)
从意图中删除额外的内容,并使用以下内容获取数据并输入
intent.setDataAndType(sendUri, "image/*");