Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't see a file in Windows written by an Android app on SD card unless I "Force Close" the app

I wrote a file through my Android program like this:

String file = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Files/hello.txt";
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write(str + "\n");     \\ Yeah, 'str' has a value there
writer.close();

The program does its job and it finishes. Now I hit the back button on Android to close the application. If I then go to an Android file browser (like Astro) I can see the file, but if I mount the SD card on Windows, I can't see the file!

Now, if I go to SettingsApplicationsManage Applications"Force Stop" <application>, I'm able to see the file even in Windows.

What should I do so that I can see a file in Windows if the file is written by my Android app on the SD card and I don't want to go to settings and hit force close every time.

Actually the file is being written properly (I think), but since the default behaviour of Android 'back' button doesn't kill the app, and it looks like unless the app is killed I can't open the file outside Android (in Android, I'm still able to see it and even open it).

So, what would be the best solution for this case? Should I automatically kill the app when it is closing? People say that System.exit() is strictly not recommended.

like image 546
Atul Goyal Avatar asked Sep 15 '11 10:09

Atul Goyal


1 Answers

It´s necessary that you use the following code so that your archive will be shown in the file system of Windows or in the gallery of the phone.

You have two possibilities:

  1. It´s faster because Android updates only the file passed:

    MediaScannerConnection.scanFile(this, new String[]{"your path here</"}, null, null);

  2. It´s more expensive because Android will search all the files in the path passed. You can pass only the path of the folder to reduce the search of the files:

    context.sendBroadcast(
        new Intent(Intent.ACTION_MEDIA_MOUNTED, 
                   Uri.parse("file://" + "path of the folder")));
    
like image 174
thiagolsilva Avatar answered Nov 15 '22 15:11

thiagolsilva