I have an application in which an ImageView is set and can be clicked to be opened in the gallery.
By default, I use the following code to get a file directory from the external storage to store my jpegs:
File picsDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"MyCameraApp");
But! Suppose the external storage is not mounted or simply does not exist (Galaxy Nexus), this doesn't work. So I wrote an if-statement around it and get the internal cache dir as a fall back.
String state = Environment.getExternalStorageState()
if(Environment.MEDIA_MOUNTED.equals(state)){
File picsDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"MyCameraApp");
}else{
context.getCacheDir();
}
The images show up fine in the ImageView, but don't come through when my intent launches.
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(imgFile), "image/jpeg");
startActivity(intent);
The gallery gets loaded, but shows a black screen. Presumably because the gallery has no access to files in the cache dir of my app.
As an alternative, I tried using the media content provider that uses MediaStore.Images.Media.INTERNAL_CONTENT_URI, but this leads to an error when trying to inser the image:
java.lang.UnsupportedOperationException: Writing to internal storage is not supported.
What should I do?
i suppose the problem here is that you are trying open with the gallery a file saved in a private space of memory (getCacheDir return a path relative to your application and only your application can access that memory path)
If you can't save in external memory, you can try to save in a public path (but that way your media files can be manipulated by every app and if you uninstall your application it doesn't clean generated media that you saved there)
If you want to use private internal memory, you can write your ContentProvider
i edit to post a content provider i use to acomplish what i said.
this is my content provider (i just posted the relevant part you need):
public class MediaContentProvider extends ContentProvider {
private static final String TAG = "MediaContentProvider";
// name for the provider class
public static final String AUTHORITY = "com.way.srl.HandyWay.contentproviders.media";
private MediaData _mediaData;
// UriMatcher used to match against incoming requests
private UriMatcher _uriMatcher;
#Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
// TODO Auto-generated method stub
return 0;
}
#Override
public String getType(Uri uri) {
// TODO Auto-generated method stub
return null;
}
#Override
public Uri insert(Uri uri, ContentValues values) {
// TODO Auto-generated method stub
return null;
}
#Override
public boolean onCreate() {
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
// Add a URI to the matcher which will match against the form
// 'content://com.stephendnicholas.gmailattach.provider/*'
// and return 1 in the case that the incoming Uri matches this pattern
_uriMatcher.addURI(AUTHORITY, "*", 1);
return true;
}
#Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
// TODO Auto-generated method stub
return null;
}
#Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
// TODO Auto-generated method stub
return 0;
}
#Override
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
Log.v(TAG, "Called with uri: '" + uri + "'." + uri.getLastPathSegment());
// Check incoming Uri against the matcher
switch (_uriMatcher.match(uri)) {
// If it returns 1 - then it matches the Uri defined in onCreate
case 1:
// The desired file name is specified by the last segment of the
// path
// E.g.
// 'content://com.stephendnicholas.gmailattach.provider/Test.txt'
// Take this and build the path to the file
// String fileLocation = getContext().getCacheDir() + File.separator + uri.getLastPathSegment();
Integer mediaID = Integer.valueOf(uri.getLastPathSegment());
if (_mediaData == null) {
_mediaData = new MediaData();
}
Media m = _mediaData.get(mediaID);
// Create & return a ParcelFileDescriptor pointing to the file
// Note: I don't care what mode they ask for - they're only getting
// read only
ParcelFileDescriptor pfd = ParcelFileDescriptor.open(new File(m.filePath), ParcelFileDescriptor.MODE_READ_ONLY);
return pfd;
// Otherwise unrecognised Uri
default:
Log.v(TAG, "Unsupported uri: '" + uri + "'.");
throw new FileNotFoundException("Unsupported uri: " + uri.toString());
}
}
then you need in the manifest the reference to your contentprovider, in my case it was
<provider
android:name=".contentproviders.MediaContentProvider"
android:authorities="com.way.srl.HandyWay.contentproviders.media" >
</provider>
and then use it like this
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("content://" + MediaContentProvider.AUTHORITY + "/" + m.id), "image/jpg");
in my case m is an entity that store an id that point to a sqlite db and i use a class that fetch data to populate again the object (with _mediaData), you can just change the code to fit your needs
this way i solved exactly your problem in my application
I have understood that this fallback is not needed. Devices that have Google Play are guaranteed to have at least 2 GB available in Environment.getExternalStorageDirectory().
I suppose in the Galaxy Nexus this is a partition on the internal memory marked as external. I'll just show a warning if it is not available.
Related
Background
I have an App-Manager app, which allows to send APK files to other apps.
Up until Android 4.4 (including), all I had to do for this task is to send the paths to the original APK files (all were under "/data/app/..." which is accessible even without root).
This is the code for sending the files (docs available here) :
intent=new Intent(Intent.ACTION_SEND_MULTIPLE);
intent.setType("*/*");
final ArrayList<Uri> uris=new ArrayList<>();
for(...)
uris.add(Uri.fromFile(new File(...)));
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM,uris);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_NO_HISTORY|Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET|Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
The problem
What I did worked since all apps' APK files had a unique name (which was their package name).
Ever since Lollipop (5.0), all apps' APK files are simply named "base.APK" , which make other apps unable to comprehend attaching them.
This means I have some options to send the APK files. This is what I was thinking about:
copy them all to a folder, rename them all to unique names and then send them.
compress them all to a single file and then send it. The compression level could be minimal, as APK files are already compressed anyway.
The problem is that I would have to send the files as quickly as possible, and if I really have to have those temporary files (unless there is another solution), to also dispose them as quickly as possible.
Thing is, I don't get notified when third party apps have finished handling the temporary file, and I also think that choosing multiple files would take quite some time to prepare no matter what I choose.
Another issue is that some apps (like Gmail) actually forbid sending APK files.
The question
Is there an alternative to the solutions I've thought of? Is there maybe a way to solve this problem with all the advantages I had before (quick and without junk files left behind) ?
Maybe some sort of way to monitor the file? or create a stream instead of a real file?
Will putting the temporary file inside a cache folder help in any way?
Any app registered for that Intent should be able to process files with the same file name but different paths. To be able to cope with the fact that access to files provided by other apps can only be accessed while the receiving Activity is running (see Security Exception when trying to access a Picasa image on device running 4.2 or SecurityException when downloading Images with the Universal-Image-Downloader) receiving apps need to copy the files to a directory they have permanently access to. My guess is that some apps haven't implemented that copy process to deal with identical file names (when copied the file path would likely be the same for all files).
I'd suggest to serve the files through a ContentProvider instead of directly from the file system. That way you can create a unique file name for each file you want to send.
Receiving apps "should" receive files more or less like this:
ContentResolver contentResolver = context.getContentResolver();
Cursor cursor = contentResolver.query(uri, new String[] { OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE }, null, null, null);
// retrieve name and size columns from the cursor...
InputStream in = contentResolver.openInputStream(uri);
// copy file from the InputStream
Since apps should open the file using contentResolver.openInputStream() a ContentProvider should/will work instead of just passing a file uri in the Intent. Of course there might be apps that misbehave and this needs to be tested thoroughly but in case some apps won't handle ContentProvider served files you could add two different share options (one legacy and the regular one).
For the ContentProvider part there's this:
https://developer.android.com/reference/android/support/v4/content/FileProvider.html
Unfortunately there's also this:
A FileProvider can only generate a content URI for files in
directories that you specify beforehand
If you can define all directories you want to share files from when the app is built, the FileProvider would be your best option.
I'm assuming your app would want to share files from any directory, so you'll need your own ContentProvider implementation.
The problems to solve are:
How do you include the file path in the Uri in order to extract the very same path at a later stage (in the ContentProvider)?
How do you create a unique file name that you can return in the ContentProvider to the receiving app? This unique file name needs to be the same for multiple calls to the ContentProvider meaning you can't create a unique id whenever the ContentProvider is called or you'd get a different one with each call.
Problem 1
A ContentProvider Uri consists of a scheme (content://), an authority and the path segment(s), e.g.:
content://lb.com.myapplication2.fileprovider/123/base.apk
There are many solutions to the first problem. What I suggest is to base64 encode the file path and use it as the last segment in the Uri:
Uri uri = Uri.parse("content://lb.com.myapplication2.fileprovider/" + new String(Base64.encode(filename.getBytes(), Base64.DEFAULT));
If the file path is e.g.:
/data/data/com.google.android.gm/base.apk
then the resulting Uri would be:
content://lb.com.myapplication2.fileprovider/L2RhdGEvZGF0YS9jb20uZ29vZ2xlLmFuZHJvaWQuZ20vYmFzZS5hcGs=
To retrieve the file path in the ContentProvider simply do:
String lastSegment = uri.getLastPathSegment();
String filePath = new String(Base64.decode(lastSegment, Base64.DEFAULT) );
Problem 2
The solution is pretty simple. We include a unique identifier in the Uri generated when we create the Intent. This identifier is part of the Uri and can be extracted by the ContentProvider:
String encodedFileName = new String(Base64.encode(filename.getBytes(), Base64.DEFAULT));
String uniqueId = UUID.randomUUID().toString();
Uri uri = Uri.parse("content://lb.com.myapplication2.fileprovider/" + uniqueId + "/" + encodedFileName );
If the file path is e.g.:
/data/data/com.google.android.gm/base.apk
then the resulting Uri would be:
content://lb.com.myapplication2.fileprovider/d2788038-53da-4e84-b10a-8d4ef95e8f5f/L2RhdGEvZGF0YS9jb20uZ29vZ2xlLmFuZHJvaWQuZ20vYmFzZS5hcGs=
To retrieve the unique identifier in the ContentProvider simply do:
List<String> segments = uri.getPathSegments();
String uniqueId = segments.size() > 0 ? segments.get(0) : "";
The unique file name the ContentProvider returns would be the original file name (base.apk) plus the unique identifier inserted after the base file name. E.g. base.apk becomes base<unique id>.apk.
While this might all sound very abstract, it should become clear with the full code:
Intent
intent=new Intent(Intent.ACTION_SEND_MULTIPLE);
intent.setType("*/*");
final ArrayList<Uri> uris=new ArrayList<>();
for(...)
String encodedFileName = new String(Base64.encode(filename.getBytes(), Base64.DEFAULT));
String uniqueId = UUID.randomUUID().toString();
Uri uri = Uri.parse("content://lb.com.myapplication2.fileprovider/" + uniqueId + "/" + encodedFileName );
uris.add(uri);
}
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM,uris);
ContentProvider
public class FileProvider extends ContentProvider {
private static final String[] DEFAULT_PROJECTION = new String[] {
MediaColumns.DATA,
MediaColumns.DISPLAY_NAME,
MediaColumns.SIZE,
};
#Override
public boolean onCreate() {
return true;
}
#Override
public String getType(Uri uri) {
String fileName = getFileName(uri);
if (fileName == null) return null;
return MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileName);
}
#Override
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
String fileName = getFileName(uri);
if (fileName == null) return null;
File file = new File(fileName);
return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
}
#Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
String fileName = getFileName(uri);
if (fileName == null) return null;
String[] columnNames = (projection == null) ? DEFAULT_PROJECTION : projection;
MatrixCursor ret = new MatrixCursor(columnNames);
Object[] values = new Object[columnNames.length];
for (int i = 0, count = columnNames.length; i < count; i++) {
String column = columnNames[i];
if (MediaColumns.DATA.equals(column)) {
values[i] = uri.toString();
}
else if (MediaColumns.DISPLAY_NAME.equals(column)) {
values[i] = getUniqueName(uri);
}
else if (MediaColumns.SIZE.equals(column)) {
File file = new File(fileName);
values[i] = file.length();
}
}
ret.addRow(values);
return ret;
}
private String getFileName(Uri uri) {
String path = uri.getLastPathSegment();
return path != null ? new String(Base64.decode(path, Base64.DEFAULT)) : null;
}
private String getUniqueName(Uri uri) {
String path = getFileName(uri);
List<String> segments = uri.getPathSegments();
if (segments.size() > 0 && path != null) {
String baseName = FilenameUtils.getBaseName(path);
String extension = FilenameUtils.getExtension(path);
String uniqueId = segments.get(0);
return baseName + uniqueId + "." + extension;
}
return null;
}
#Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
return 0; // not supported
}
#Override
public int delete(Uri uri, String arg1, String[] arg2) {
return 0; // not supported
}
#Override
public Uri insert(Uri uri, ContentValues values) {
return null; // not supported
}
}
Note:
My sample code uses the org.apache.commons library for the file name manipulations (FilenameUtils.getXYZ)
using base64 encoding for the file path is a valid approach because all character used in base64 ([a-zA-Z0-9_-=] according to this https://stackoverflow.com/a/6102233/534471) are valid in an Uri path (0-9, a-z, A-Z, _-!.~'()*,;:$&+=/# --> see https://developer.android.com/reference/java/net/URI.html)
Your manifest would have to define the ContentProvider like so:
<provider
android:name="lb.com.myapplication2.fileprovider.FileProvider"
android:authorities="lb.com.myapplication2.fileprovider"
android:exported="true"
android:grantUriPermissions="true"
android:multiprocess="true"/>
It won't work without android:grantUriPermissions="true" and android:exported="true" because the other app wouldn't have permission to access the ContentProvider (see also http://developer.android.com/guide/topics/manifest/provider-element.html#exported) . android:multiprocess="true" on the other hand is optional but should make it more efficient.
Here's a working solution for using SymLinks. Disadvantages:
works from API 14, and not on API 10 , not sure about in between.
uses reflection, so might not work in the future, and on some devices.
must create the symlinks in the path of "getFilesDir", so you have to manage them by yourself, and create unique files names as needed.
The sample shares the APK of the current app.
Code:
public class SymLinkActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(lb.com.myapplication2.R.layout.activity_main);
final Intent intent=new Intent(Intent.ACTION_SEND_MULTIPLE);
intent.setType(MimeTypeMap.getSingleton().getMimeTypeFromExtension("apk"));
final String filePath;
try
{
final android.content.pm.ApplicationInfo applicationInfo=getPackageManager().getApplicationInfo(getPackageName(),0);
filePath=applicationInfo.sourceDir;
}
catch(NameNotFoundException e)
{
e.printStackTrace();
finish();
return;
}
final File file=new File(filePath);
final String symcLinksFolderPath=getFilesDir().getAbsolutePath();
findViewById(R.id.button).setOnClickListener(new android.view.View.OnClickListener(){
#Override
public void onClick(final android.view.View v)
{
final File symlink=new File(symcLinksFolderPath,"CustomizedNameOfApkFile-"+System.currentTimeMillis()+".apk");
symlink.getParentFile().mkdirs();
File[] oldSymLinks=new File(symcLinksFolderPath).listFiles();
if(oldSymLinks!=null)
{
for(java.io.File child : oldSymLinks)
if(child.getName().endsWith(".apk"))
child.delete();
}
symlink.delete();
// do some dirty reflection to create the symbolic link
try
{
final Class<?> libcore=Class.forName("libcore.io.Libcore");
final java.lang.reflect.Field fOs=libcore.getDeclaredField("os");
fOs.setAccessible(true);
final Object os=fOs.get(null);
final java.lang.reflect.Method method=os.getClass().getMethod("symlink",String.class,String.class);
method.invoke(os,file.getAbsolutePath(),symlink.getAbsolutePath());
final ArrayList<Uri> uris=new ArrayList<>();
uris.add(Uri.fromFile(symlink));
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM,uris);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_NO_HISTORY|Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET|Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
startActivity(intent);
android.widget.Toast.makeText(SymLinkActivity.this,"succeeded ?",android.widget.Toast.LENGTH_SHORT).show();
}
catch(Exception e)
{
android.widget.Toast.makeText(SymLinkActivity.this,"failed :(",android.widget.Toast.LENGTH_SHORT).show();
e.printStackTrace();
// TODO handle the exception
}
}
});
}
}
EDIT: for the symlink part, for Android API 21 and above, you can use this instead of reflection :
Os.symlink(originalFilePath,symLinkFilePath);
I have the following code that correctly attaches the image to the email and sends:
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Set tht type to image/* and add the extra text field for the message to send
sharingIntent.setType(Application2.instance().getResString(R.string.share_intent_type_text_image));
sharingIntent.putExtra(Intent.EXTRA_TEXT, String.format(Application2.instance().getResString(R.string.share_intent_body_question), question.question));
if (destFile != null)
{
Uri uri = Uri.fromFile(destFile);
sharingIntent.putExtra(Intent.EXTRA_STREAM, uri);
((ActivityMain) getActivity()).startActivity(Intent.createChooser(sharingIntent, "Share via"));
}
R.string.share_intent_type_text_image is defined as "image/png"
destFile is an image grabbed from the external cache directory of the app, (((ActivityMain) getActivity()).getExternalCacheDir()
However, when I attempt to open the file in Gmail, a dialog appears that says: Info - No app can open this attachment for viewing. I've downloaded the file via my PC and the extension comes up as .File. I can open it with paint and other image viewers.
Anyone experience this before?
Considering the FileProvider problems, and also because I wanted to implement a max cache size for collected temp files, I went with a ContentProvider solution and it works a treat. Basically, you're allowed to use your internal cache without any problem but still provide third party apps with a URI they can use to reference your temporary files you want to share with them. Because you use your internal cache, there will be no unnecessary WRITE_EXTERNAL_STORAGE permission to ask for.
The added max cache size limit (that you can remove from the class by simply deleting everything from checkSize() to the end of the class, for instance, if you can make sure you delete all files directly after sharing, so they won't remain on the device) works by checking the cumulated max size upon each call and clearing up half the cache (deleting the oldest files) if necessary.
public class TemporaryFile extends ContentProvider {
private static final long MAX_SIZE = 512 * 1024;
// commented out on purpose so that you don't forget to rewrite it...
// public static final String AUTHORITY = "com.example.tempfile";
private UriMatcher uriMatcher;
#Override
public boolean onCreate() {
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(AUTHORITY, "*", 1);
return true;
}
#Override
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
if (uriMatcher.match(uri) == 1) {
final String file = getContext().getCacheDir() + File.separator + uri.getLastPathSegment();
return ParcelFileDescriptor.open(new File(file), ParcelFileDescriptor.MODE_READ_ONLY);
}
else
throw new FileNotFoundException(uri.toString());
}
#Override
public int update (Uri uri, ContentValues values, String selection, String[] selectionArgs) {
return 0;
}
#Override
public int delete (Uri uri, String selection, String[] selectionArgs) {
return 0;
}
#Override
public Uri insert(Uri uri, ContentValues values) {
return null;
}
#Override
public String getType(Uri uri) {
return null;
}
#Override
public Cursor query (Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
return null;
}
public static File getFile(Context context, String prefix, String extension) throws IOException {
checkSize(context);
File file = File.createTempFile(prefix, extension, context.getCacheDir());
file.setReadable(true);
file.deleteOnExit();
return file;
}
public static Uri getPublicUri(File file) {
return Uri.withAppendedPath(Uri.parse("content://" + AUTHORITY), file.getName());
}
public static void checkSize(Context context) throws IOException {
File dir = context.getCacheDir();
if (getDirSize(dir) > MAX_SIZE)
cleanDir(dir, MAX_SIZE / 2);
}
private static long getDirSize(File dir) {
long size = 0;
for (File file : dir.listFiles())
if (file.isFile())
size += file.length();
return size;
}
private static void cleanDir(File dir, long atLeast) {
long deleted = 0;
File[] files = dir.listFiles();
Arrays.sort(files, new Comparator<File>() {
public int compare(File f1, File f2) {
return Long.valueOf(f1.lastModified()).compareTo(f2.lastModified());
}
});
for (File file : files) {
deleted += file.length();
file.delete();
if (deleted >= atLeast)
break;
}
}
}
Using it couldn't be simpler, just call
File file = TemporaryFile.getFile(this, "prefix", ".extension");
whenever you want to create a new file and
TemporaryFile.getPublicUri(file)
whenever you want to get a public Uri to the file, eg. to pass it to an intent as data or Intent.EXTRA_STREAM.
Being a provider, don't forget to add the necessary manifest entry, either:
<provider
android:name=".TemporaryFile"
android:authorities="com.example.tempfile"
android:exported="true"
tools:ignore="ExportedContentProvider" >
</provider>
This works but requires external storage and the relating permissions. When downloading an app, a dialog will show that the app is requesting to be able to read/write data which may turn users away. Use the FileProvider as Simon suggested in my initial post if that's a concern.
Useful links:
https://developer.android.com/reference/android/support/v4/content/FileProvider.html
I attempted to use the File Provider as Simon suggested in my initial post to no avail. I received a NullPointerException on the following line:
final ProviderInfo info = context.getPackageManager()
.resolveContentProvider(authority, PackageManager.GET_META_DATA);
I was unable to track the problem after following the guide at:
https://developer.android.com/reference/android/support/v4/content/FileProvider.html
as well as the other thread at:
How to use support FileProvider for sharing content to other apps?
At this point I realized there is no file type set for the images being used. I simply added .png to the files and the attachments work correctly in Gmail as well as the previous apps that already worked.
I provided the following code if anyone was curious how I shared an internal file. It's not complete and does not handle errors completely but it may be useful for someone as a start.
// Copy image file to external memory and send with the intent
File srcFile = getImage();
File destDir = new File(((ActivityMain) getActivity()).getExternalCacheDir(),
Application2.instance().getResString(R.string.temporary_external_image_path));
if(!destDir.exists())
{
destDir.mkdirs();
}
if(destDir != null && srcFile != null)
{
File destFile = new File(destDir, srcFile.getName());
if (!destFile.exists())
{
try
{
Application2.instance().copy(srcFile, destFile);
}
catch (IOException e)
{
if (BuildConfig.DEBUG) Log.e("Failed to copy file '" + srcFile.getName() + "'");
}
}
if (destFile != null)
{
Uri uri = Uri.fromFile(destFile);
sharingIntent.putExtra(Intent.EXTRA_STREAM, uri);
((ActivityMain) getActivity()).startActivity(Intent.createChooser(sharingIntent, "Share via"));
}
}
As far as I can understand the right way of working with images in Android is to store images Uri in the database, not the image actual path.
Thats how we can get thumbnails for free. And we don't need to prepare them by ourself and hide somewere.
The code below takes thumbnails by Uri.
Code works on android 4.4 and below. But to get image id it doesn't query content provider. It takes ID from Uri itself. The question is: Is it a stable solution, can I rely on it?
#TargetApi(Build.VERSION_CODES.KITKAT)
public static Bitmap getImageThumbnail(Context context, Uri uri){
final ContentResolver resolver = context.getContentResolver();
long id;
try {
if (UIUtils.hasKitKat() && DocumentsContract.isDocumentUri(context, uri)) {
String wholeID = DocumentsContract.getDocumentId(uri);
// Split at colon, use second item in the array
id = Long.parseLong(wholeID.split(":")[1]);
}
else if (isMediaUri(uri)){
id = ContentUris.parseId(uri);
}
else return null;
return MediaStore.Images.Thumbnails.getThumbnail(
resolver,
id,
MediaStore.Images.Thumbnails.MINI_KIND,
null);
}
catch (Exception e) {
if (DEBUG) Log.e(TAG, "getThumbnail", e);
return null;
}
}
public static boolean isMediaUri(Uri uri) {
return "media".equalsIgnoreCase(uri.getAuthority());
}
you should be using DocumentsContract.getDocumentThumbnail(). this is guaranteed to work with any document uri, not just the builtin media provider.
Some of my users have reported to Google Play the following error when trying to select a ringtone in my app. (there's more to it, but it's not relevant)
java.lang.SecurityException: Permission Denial:
reading com.android.providers.media.MediaProvider
uri content://media/external/audio/media
from pid=5738, uid=10122 requires android.permission.READ_EXTERNAL_STORAGE
I assume this issue is happening due to certain tones that are on external storage. I don't want to include the READ_EXTERNAL_STORAGE permission in my app unless I absolutely have to.
Is there a way to circumvent the issue and just exclude any tones that may be on the external storage?
Note: I'm getting ringtones with RingtoneManager and convert them between String and Uri. No other code is touching the user's media.
Also, I do not have a line number since the stacktrace is from obfuscated code and re-mapping the stack trace did not provide line number.
Just had the same problem and came up with the following solution:
private Cursor createCursor()
{
Uri uri = MediaStore.Audio.Media.INTERNAL_CONTENT_URI;
String[] columns = new String[]
{
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.TITLE_KEY
};
String filter = createBooleanFilter(MediaStore.Audio.AudioColumns.IS_ALARM);
String order = MediaStore.Audio.Media.DEFAULT_SORT_ORDER;
return getContext().getContentResolver().query(uri, columns, filter, null, order);
}
private String createBooleanFilter(String... columns)
{
if(columns.length > 0)
{
StringBuilder sb = new StringBuilder();
sb.append("(");
for(int i = columns.length - 1; i > 0; i--)
{
sb.append(columns[i]).append("=1 or ");
}
sb.append(columns[0]);
sb.append(")");
return sb.toString();
}
return null;
}
To get the Uri of a ringtone you need to combine the INTERNAL_CONTENT_URI with the _ID column value, you can do this by using ContentUris class:
Uri uri = ContentUris.withAppendedId(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, cursor.getLong(0));
You can find the external storage directory without needing WRITE_EXTERNAL_STORAGE or READ_EXTERNAL_STORAGE by using Environment.getExternalStorageDirectory().
You can then compare the paths for the URIs provided by RingtoneManager to this path to see if they are on the external storage or not and if so add those items to a List.
Then, rather than passing the raw Cursor to the UI you can use that List with a ListAdapter instead.
For example (untested, you may need to change the method of comparing paths):
class RingtoneDetails
{
public String ID;
public String Title;
public Uri Uri;
public RingtoneDetails(String id, String title, Uri uri)
{
ID = id;
Title = title;
Uri = uri;
}
}
private List<RingtoneDetails> getNonExternalRingtones(RingtoneManager manager)
{
List<RingtoneDetails> ringtones = new List<RingtoneDetails>();
Cursor cursor = manager.getCursor();
String extDir = Environment.getExternalStorageDirectory().getAbsolutePath();
while (cursor.moveToNext())
{
String id = cursor.getString(cursor.getColumnIndex(RingtoneManager.ID_COLUMN_INDEX));
String title = cursor.getString(cursor.getColumnIndex(RingtoneManager.TITLE_COLUMN_INDEX));
Uri uri= cursor.getString(cursor.getColumnIndex(RingtoneManager.URI_COLUMN_INDEX));
if(!uri.getPath().contains(extDir))
{
ringtones.add(new Ringtone(id, title, uri));
}
}
return ringtones;
}
Previously, I was using RingtoneManager to get a list and display that in a dialog for a user to select. It was throwing the SecurityException on ringtoneManager.getCursor();
I did not want to add the external storage permission, so I switched to doing:
final Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, "Select Ringtone");
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, true);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, true);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE,RingtoneManager.TYPE_ALL);
startActivityForResult( intent, RINGTONE_RESULT);
And then in onActivityResult
if (requestCode == RINGTONE_RESULT&&resultCode == RESULT_OK&&data!=null) {
try {
Uri uri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
if (uri==null){
setSilent(); //UI stuff in this method
} else {
Ringtone ringtone = RingtoneManager.getRingtone(context, uri);
String name = ringtone.getTitle(context);
changeTone.setText(name); //changeTone is a button
}
} catch (SecurityException e){
setSilent();
Toast.makeText(context, "Error. Tone on user storage. Select a different ringtone.", Toast.LENGTH_LONG).show();
} catch (Exception e){
setSilent();
Toast.makeText(context, "Unknown error. Select a different ringtone.", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(context, "Ringtone not selected. Tone set to silent.", Toast.LENGTH_SHORT).show();
setSilent();
}
In my app the user can choose a notification using RingtonePreference. From the latter I'm able to retrieve the Uri of the selected notification, and using the following code to extract the real file name:
private String getUriRealPath(Uri contentUri) {
if (BuildConfig.DEBUG) {
Log.d(TAG, "Getting real path of uri: " + contentUri.toString());
}
String path = null;
final String[] projection = new String [] { MediaStore.Audio.Media.DATA };
final Cursor cursor;
try {
cursor = mContext.getContentResolver().query(contentUri, projection, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
int idx = cursor.getColumnIndex(projection[0]);
if (idx != -1) {
path = cursor.getString(idx);
if (BuildConfig.DEBUG) {
Log.d(TAG, "Real path is: " + path);
}
}
else {
if (BuildConfig.DEBUG) {
Log.d(TAG, "Path can't be resolved.");
}
}
}
} catch (Exception e) {
Log.e(TAG, "getUriRealPath - " + e);
}
return path;
}
However, once the user chooses a notification that was downloaded via a 3-rd party, the above code can't find the real path.
The reason for the extraction is I need the path for playing the notification in a SoundPool object.
I may be over seeing this, but getContentResolver() returns a ContentResolver instance for my application. Should I be using a "global" ContentResolver ?
However, once the user chooses a notification that was downloaded via a 3-rd party, the above code can't find the real path.
You may not have access to the actual file, anyway. First, it may not exist as a file, but only as a stream. Second, it may not be in storage for which you have read access. You can only reliably access this media via the Uri supplied to you.
The reason for the extraction is I need the path for playing the notification in a SoundPool object.
Then you will have to stop using SoundPool and switch to MediaPlayer, AudioTrack, or something else.
Should I be using a "global" ContentResolver ?
There is no "global" ContentResolver.