How to use getCropAndSetWallpaperIntent?

2019-05-09 23:47发布

问题:

I tried to use getCropAndSetWallpaperIntent method but I got an error.

Here is my code :

Uri uri = Uri.parse("content://" + getFilesDir() + "/"+ image.path);
ContentResolver contentResolver = getContentResolver();
contentResolver.getType(uri); // Type is null
Intent intent = wallpaperManager.getCropAndSetWallpaperIntent(uri);
intent.setType("image/*");
startActivityForResult(intent, 42);

Here is what I got in my logs :

java.lang.IllegalArgumentException: Cannot use passed URI to set wallpaper; check that the type returned by ContentProvider matches image/*

Can you help me please?

回答1:

You have to query the MediaStore without using the "content://" protocol, for instance like this (code can be improved):

String[] paths = {"/example.png"};
final String[] FIELDS = { MediaStore.MediaColumns._ID };
// Images
Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
Cursor ca = context.getContentResolver().query(uri, FIELDS, MediaStore.MediaColumns.DATA + "=?", paths, null);
for (ca.moveToFirst(); !ca.isAfterLast(); ca.moveToNext()) {
   int id = ca.getInt(ca.getColumnIndex(MediaStore.MediaColumns._ID));
   uri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id);
   found = true; 
}
ca.close();

if (found) {
   return uri;
}