• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps [Code] Quick tip: How to write a .nomedia file

alostpacket

Over Macho Grande?
Hi all,

Just a quick code snippet on writing a .nomedia file to a directory.

All you need is a path to the folder you want to write to.

Notes:
- the TAG varible is just the name of the class (in this case "FileUtil")
- the D varible is just a boolen to indicate you want to debug or not

Code:
/**
 * 
 * @param   directoryPath   The full path to the directory to place the .nomedia file
 * @return   Returns true if the file was successfully written or appears to already exist
 */


public boolean writeNoMediaFile( String directoryPath )
{
    String storageState = Environment.getExternalStorageState();

    if ( Environment.MEDIA_MOUNTED.equals( storageState ) )
    {
        try
        {
            File noMedia = new File ( directoryPath, ".nomedia" );
            
            if ( noMedia.exists() )
            {
                if (D) Log.i ( TAG, ".no media appears to exist already, returning without writing a new file" );
                return true;
            }
            
            FileOutputStream noMediaOutStream = new FileOutputStream ( noMedia );
            noMediaOutStream.write ( 0 );
            noMediaOutStream.close ( );
        }
        catch ( Exception e )
        {
            if (D) Log.e( TAG, "error writing file" );            
            if (D) e.printStackTrace();
            return false;
        }
    }
    else
    {
        if (D) Log.e( TAG, "storage appears unwritable" );
        return false;
    }
    
    return true;
    
}
 
Back
Top Bottom