首先,您必须将图像文件从原始文件夹下载到 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;
}
这是您可以使用的代码