不用reboot就可以让数据出现的方法.
As anyone who worked with android applications experienced, the files created by Android application in “External Storage” (I don’t like this term, as this usually refers to internal memory of the device), do not show up in windows explorer until the device is rebooted.
Initially we used recording to external media (USB drives, SD Cards) as a workaround. However, some smart guy working on Android added a “feature” since Honeycomb 3.2 , that made the external storage effectively write-protected for non-system applications. Since that avenue is closed, we are forced to record stuff to storage available on the device itself.
Storing stuff on the device poses a few challenges. One of them is copying those files to a PC. One strange behaviour we noticed was, if we just created the files from the application and then plug the tablet to PC, the files we have just created do not show up in windows explorer. However once you reboot the device, the files show up as usual.
I found that, for the MTP protocol to present the file to windows, the service should be aware of the file. When a device reboots, the MediaScanner scans the storage volumes and indexes all the files. However files created once the scan is complete are not automatically added to the index. I found an efficient way (for me) to add a single file to index without forcing a media scan of the whole drive.
importandroid.media.MediaScannerConnection; importandroid.media.MediaScannerConnection.MediaScannerConnectionClient; publicclassMediaScannerHelperimplementsMediaScannerConnectionClient { publicvoidaddFile(String filename)</pre> { String [] paths =newString[1]; paths[0] = filename; MediaScannerConnection.scanFile(context, paths,null,this); } publicvoidonMediaScannerConnected() { } publicvoidonScanCompleted(String path, Uri uri) { Log.i("ScannerHelper","Scan done - path:"+ path +" uri:"+ uri); } }
Once writing to a file is done and I close the FileOutputStream and call the addFile() method with the absolute file name. This adds the newly created file to index. Another thing I noticed is occasionally I have to unplug and re-plug the tablet from the PC usb drive for the files appear. I believe this is an easier thing to ask of end-users than to have them reboot the tablet for the files to show up. Hope this helps someone out there!
此外,也可以直接用MediaScannerConnection 来,而不是需要重新construct一个.
File dir = new File(root + "/SensorData3"); // File dir = new File("/sdcard/SensorData"); dir.mkdir(); File file = new File(dir, "myData.txt"); MediaScannerConnection.scanFile(this, new String[] {file.toString()}, null, new MediaScannerConnection.OnScanCompletedListener() { @Override public void onScanCompleted(String path, Uri uri) { Log.d(TAG, "ExternalStorage Scaned: " + path + ":" ); Log.d(TAG, "ExternatalStore: " + "-> uri: " + uri); } });