public class FileOpenTestActivity extends Activity {
private WebView webView;
private Context mContext = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.mContext = this;
webView = (WebView) findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
webView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
//判斷是否是文件下載鏈接,如果不是則返回,直接訪問
String fileName = url.substring(url.lastIndexOf("/"));
if(null == getFileType(fileName) || getFileType(fileName).equals("")){
return false;
}
//如果是文件下載鏈接,先下載,再調用系統安裝的閱讀器打開
try {
//下載文件到SD卡
File file = downloadFile(url);
//調用適合的閱讀器顯示文件
startActivity(getFileIntent(file));
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
return true;
}
});
webView.loadUrl("http://localhost:8888/OpenFile/fileList.html");
}
/**
* 下載文件
* @param fileUrl
* @return
*/
public File downloadFile(String fileUrl) {
File apkFile = null;
String fileName = fileUrl.substring(fileUrl.lastIndexOf("/"));
try {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
// 獲得存儲卡的路徑
String sdpath = Environment.getExternalStorageDirectory() + "/";
String mSavePath = sdpath + "download";
URL url = new URL(fileUrl);
// 創建連接
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.connect();
// 獲取文件大小
//int length = conn.getContentLength();
// 創建輸入流
InputStream is = conn.getInputStream();
File file = new File(mSavePath);
// 判斷文件目錄是否存在
if (!file.exists()) {
file.mkdir();
}
apkFile = new File(mSavePath, fileName);
if(apkFile.exists()){
return apkFile;
}
FileOutputStream fos = new FileOutputStream(apkFile);
int count = 0;
int numread = 0;
byte buf[] = new byte[1024];
while ((numread = is.read(buf)) != -1) {
fos.write(buf, 0, numread);
}
fos.flush();
fos.close();
is.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return apkFile;
}
/**
* 獲取用於文件打開的intent
* @param file
* @return
*/
public Intent getFileIntent(File file)
{
Intent intent = new Intent("android.intent.action.VIEW");
intent.addCategory("android.intent.category.DEFAULT");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Uri uri = Uri.fromFile(file);
String fileType = getFileType(file.getName());
intent.setDataAndType(uri, fileType);
return intent;
}
/**
* 從配置文件獲取要下載的文件後綴和對應的MIME類型
* @param fileName
* @return
*/
public String getFileType(String fileName){
String [] names = this.mContext.getResources().getStringArray(R.array.file_name_array);
String [] types = this.mContext.getResources().getStringArray(R.array.file_type_array);
for(int i=0;i<names.length;i++){
if(fileName.toLowerCase().indexOf(names[i])>=0){
return types[i];
}
}
return "";
}
}
|