Tuesday 15 March 2016

Android, invisible files, and folders that look like empty files

Ugh.

That took a long time, a lot of poking, swearing, reading stackoverflow, more poking, more swearing, and finally digging around in an open source file manager to find out how they'd done it.

So.

If you create a file on an Android device and attempt to view it with MTP/PTP, and it isn't there, you need to do this:

sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(f)));

That tells the media scanner that it needs to know about this new file.

Cool. Great. Now, don't do this.


File f = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "MyStuff/");
f.mkdirs();
//THIS! DON'T DO THIS ON A DIRECTORY!
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(f)));



Or you'll end up with folders that you can't access from windows via MTP/PTP. They'll look like empty/unknown type files. Just do

File f = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "MyStuff/");
f.mkdirs();

and the folder will appear straight away as it should.