For example, we may want to play the default MP3 file in background.
The simple way is just put the files you want in the directory assets.
During your development stage, those files in this directory will not dealt with.
When you build the apk, they will be included at the same time.
Then, how can our program access them after installing the apk?
Some people may use the path "file://android_asset/" to access them.
However, the suggested method is to access them by AssetManager.
Assume that you put a file called "t.mp3" in the assets directory.
AssetManager assetManager = getAssets(); InputStream in = null; OutputStream out = null; File sdCardDir = Environment.getExternalStorageDirectory(); in = assetManager.open("t.mp3"); out = new FileOutputStream(new File(sdCardDir+"/myFolder", "t.mp3")); byte[] buffer = new byte[1024]; int read; while((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } in.close(); in = null; out.flush(); out.close(); out = null;
The method shown above is to copy the file "t.mp3" to directory "/myFolder".
Then we can access it by FileInputStream or another file access methods.
Of course, there have many different ways.
For example, if you want to play it directly:
AssetFileDescriptor fileDescriptor = getAssets().openFd("t.mp3"); MediaPlayer mp = new MediaPlayer(); mp.setDataSource(fileDescriptor.getFileDescriptor());
沒有留言:
張貼留言