【Android開發】打開各種類型文件、預覽不同類型文件


在Android開發中,經過需要用到調用外部應用來打開一個文件,


而且,該文件可能是圖片、視頻、音頻、CAD文件、壓縮包文件等等……


那麼,如何做到呢


eieihihi在這裏總結了一個比較簡單的方法,希望幫得上大家……


/**
 * 打開一個文件
 * 
 * @param filePath
 *            文件的絕對路徑
 */
private void openFile(final String filePath)
{
	String ext = filePath.substring(filePath.lastIndexOf('.')).toLowerCase(Locale.US);
	try
	{
		MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
		String temp = ext.substring(1);
		String mime = mimeTypeMap.getMimeTypeFromExtension(temp);

		Intent intent = new Intent();
		intent.setAction(android.content.Intent.ACTION_VIEW);
		File file = new File(filePath);
		intent.setDataAndType(Uri.fromFile(file), mime);
		startActivity(intent);
	}
	catch (Exception e)
	{
		e.printStackTrace();
		Toast.makeText(getApplicationContext(), "無法打開後綴名爲." + ext + "的文件!",
				Toast.LENGTH_LONG).show();
	}
}


上面用到MimeTypeMap 類,用於獲取MIME映射信息,這個方法簡單實用,不用自己去寫一大堆MIME映射了……



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章