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 "";
}
}
|