工作時遇到一個問題,我在VideoActivty中找到一個視頻文件,啓動Gallery3D中的MovieView來進行播放,然後在MovieView端得到此文件的路徑。我當時傳進了一個:
String mpath = "/mnt/sdcard/葉問2.mp4";
的路徑,其中文件名是中文的。然後我在MovieView中得到的文件名竟然是亂碼,最開始我是這麼處理的:
VideoActivty處的代碼大致爲:
String mpath = "/mnt/sdcard/葉問2.mp4";
String type = "video";
File f = new File(mpath);
Uri uri = Uri.fromFile(f);
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(uri, type);
this.startActivity(intent);
MovieView處理時用了異想天開的轉碼方式:
path = new String(mUri.toString().getBytes("utf-8"), "GBK");
發現無論怎樣處理都無法轉成中文。通過查看官方文檔發現URI把我們的path轉成了RFC 2396格式,不懂啊。。。
其實URI已經考慮到了這種情況。琢磨後用了這種方式得到了中文路徑。
Intent intent2 = getIntent();
Uri mUri = intent2.getData();
String path = intent2.getDataString();
path = Uri.decode(path).substring(7, path.length());
android.util.Log.d("URI", "path is " + path);
Uri.decode函數Google已經幫我們實現好了。只是我這個碼農沒有發現。。。。。。記錄於此,供後來人參考。