Android 个人配置代码(包括webview 配置和本地下载监听)
需要引进httpclient的jar包
package com.example.lsk.fisrstandroid;
import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.WindowManager;
import android.webkit.DownloadListener;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
public class MainActivity extends AppCompatActivity {
private FrameLayout mWebContainer;
private WebView webview;
private ProgressDialog mDialog;
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE };
/**
* Checks if the app has permission to write to device storage
*
* If the app does not has permission then the user will be prompted to
* grant permissions
*
* @param activity
*/
public static void verifyStoragePermissions(Activity activity) {
// Check if we have write permission
int permission = ActivityCompat.checkSelfPermission( activity,
Manifest.permission.WRITE_EXTERNAL_STORAGE );
if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions( activity, PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE );
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mWebContainer = ( FrameLayout) findViewById(R.id.web_container);
webview = new WebView(this);
mWebContainer.addView(webview);
verifyStoragePermissions(MainActivity.this);
// mWebContainer.
// webview = (WebView)findViewById(R.id.webview1);
// if(Build.VERSION.SDK_INT >= 19) {
// webview.getSettings().setLoadsImagesAutomatically(true);
// } else {
// webview.getSettings().setLoadsImagesAutomatically(false);
// }
//透明状态栏
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
// getWindow().addFlags(
// WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// getWindow().addFlags(
// WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
// }
//透明状态栏
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//透明导航栏
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
//输入框被遮挡
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE |
WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
webview.requestFocusFromTouch();
//webview.getSettings().setWin
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setRenderPriority( WebSettings.RenderPriority.HIGH);
webview.getSettings().setUseWideViewPort(true);
webview.getSettings().setSupportZoom(true); //支持缩放,默认为true。是下面那个的前提。
webview.getSettings().setBuiltInZoomControls(true); //设置内置的缩放控件。
webview.getSettings().setDisplayZoomControls(false);
webview.getSettings().setLoadWithOverviewMode(true);
webview.getSettings().setLayoutAlgorithm( WebSettings.LayoutAlgorithm.SINGLE_COLUMN); //支持内容重新布局
webview.getSettings().supportMultipleWindows(); //多窗口
//webview.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //关闭webview中缓存
webview.getSettings().setAllowFileAccess(true); //设置可以访问文件
webview.getSettings().setNeedInitialFocus(true); //当webview调用requestFocus时为webview设置节点
webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
webview.getSettings().setLoadsImagesAutomatically(true); //支持自动加载图片
webview.getSettings().setDefaultTextEncodingName("utf-8");//设置编码格式
// webview.getSettings().setPluginsEnabled(true); //支持插件
// webview.loadUrl(url);
webview.loadUrl(url);
webview.setWebViewClient(new HelloWebViewClient());
//设置WebChromeClient
webview.setWebChromeClient(new WebChromeClient(){
//获得网页的加载进度,显示在右上角的TextView控件中
@Override
public void onProgressChanged(WebView view, int newProgress) {
if (newProgress < 100) {
String progress = newProgress + "%";
} else {
}
}
//处理javascript中的alert
public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
//构建一个Builder来显示网页中的对话框
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Alert");
builder.setMessage(message);
builder.setPositiveButton(android.R.string.ok,
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
});
builder.setCancelable(false);
builder.create();
builder.show();
return true;
};
//处理javascript中的confirm
public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("confirm");
builder.setMessage(message);
builder.setPositiveButton(android.R.string.ok,
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
});
builder.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
result.cancel();
}
});
builder.setCancelable(false);
builder.create();
builder.show();
return true;
};
});
webview.setDownloadListener( (DownloadListener) new MyWebViewDownLoadListener() );
// webview.setWebChromeClient(new WebChromeClient(){
// @Override
// public void onProgressChanged(WebView view, int newProgress) {
// //get the newProgress and refresh progress bar
// }
// });
// webview.setWebChromeClient(new WebChromeClient(){
// @Override
// public void onReceivedTitle(WebView view, String title) {
// titleview.setText(title);//a textview
// }
// });
// WebView webview = new WebView(this);
// //设置WebView属性,能够执行Javascript脚本
// webview.getSettings().setJavaScriptEnabled(true);
// //加载需要显示的网页
// webview.loadUrl("http://192.168.1.163/ymw/home/");
//
// //设置Web视图
// setContentView(webview);
// LinearLayout layout =new LinearLayout(this);
// super.setContentView(layout);
// layout.setOrientation(LinearLayout.VERTICAL);
// final TextView show = new TextView(this);
// Button bn= new Button(this);
// bn.setText(R.string.ok);
// bn.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT));
// layout.addView(show);
// layout.addView(bn);
// bn.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// show.setText("Hello Android ,"+new java.util.Date());
// }
// });
// setContentView(R.layout.activity_main);
// TextView tv = new TextView(this);
// tv.setText("Lucky boy!");
// setContentView(tv);
// Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
//
// FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
// fab.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
// .setAction("Action", null).show();
// }
// });
}
// private class MyWebViewDownLoadListener implements DownloadListener{
//
// @Override
// public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
// long contentLength) {
// //调用自己的下载方式
//// new HttpThread(url).start();
// Log.i("tag", "url="+url);
// Log.i("tag", "userAgent="+userAgent);
// Log.i("tag", "contentDisposition="+contentDisposition);
// Log.i("tag", "mimetype="+mimetype);
// Log.i("tag", "contentLength="+contentLength);
// Uri uri = Uri.parse(url);
// Intent intent = new Intent(Intent.ACTION_VIEW, uri);
// startActivity(intent);
// }
// }
private class HelloWebViewClient extends WebViewClient{
// 在WebView中而不是默认浏览器中显示页面
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}
}
//设置回退
//覆盖Activity类的onKeyDown(int keyCoder,KeyEvent event)方法
// public boolean onKeyDown(int keyCode, KeyEvent event) {
// if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
// webview.goBack(); //goBack()表示返回WebView的上一页面
// return true;
// }
// return false;
// }
public boolean onKeyDown(int keyCode, KeyEvent event) {//捕捉返回键
if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
webview.goBack();
return true;
}else if(keyCode == KeyEvent.KEYCODE_BACK){
ConfirmExit();//按了返回键,但已经不能返回,则执行退出确认
return true;
}
return super.onKeyDown(keyCode, event);
}
public void ConfirmExit(){//退出确认
AlertDialog.Builder ad=new AlertDialog.Builder(MainActivity.this);
ad.setTitle("退出");
ad.setMessage("是否退出软件?");
ad.setPositiveButton("是", new DialogInterface.OnClickListener() {//退出按钮
@Override
public void onClick(DialogInterface dialog, int i) {
// TODO Auto-generated method stub
MainActivity.this.finish();//关闭activity
}
});
ad.setNegativeButton("否",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
//不退出不用执行任何操作
}
});
ad.show();//显示对话框
}
private class WebViewClientDemo extends WebViewClient {
// 如果页面中链接,如果希望点击链接继续在当前browser中响应,
// 而不是新开Android的系统browser中响应该链接,必须覆盖 webview的WebViewClient对象。
public boolean shouldOverviewUrlLoading(WebView view, String url) {
Log.i("tag","shouldOverviewUrlLoading");
view.loadUrl(url);
return true;
}
public void onPageStarted(WebView view, String url, Bitmap favicon) {
Log.i("tag","onPageStarted");
showProgressDialog();
}
public void onPageFinished(WebView view, String url) {
Log.i("tag","onPageFinished");
closeProgressDialog();
}
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
Log.i("tag","onReceivedError");
closeProgressDialog();
}
@Override
// 在WebView中而不是默认浏览器中显示页面
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
protected void onDestroy() {
super.onDestroy();
mWebContainer.removeAllViews();
webview.destroy();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
protected void onResume() {
/**
* 设置为竖屏
*/
if(getRequestedOrientation()!= ActivityInfo.SCREEN_ORIENTATION_PORTRAIT){
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
super.onResume();
}
/**
*
* 文件下载
* **/
//内部类
private class MyWebViewDownLoadListener implements DownloadListener{
@Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
long contentLength) {
if(!Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)){
Toast t= Toast.makeText(getApplicationContext(), "需要SD卡。", Toast.LENGTH_LONG);
t.setGravity( Gravity.CENTER, 0, 0);
t.show();
return;
}
DownloaderTask task=new DownloaderTask();
task.execute(url);
}
}
//内部类
private class DownloaderTask extends AsyncTask<String, Void, String> {
public DownloaderTask() {
}
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String url=params[0];
// Log.i("tag", "url="+url);
String fileName=url.substring(url.lastIndexOf("/")+1);
fileName= URLDecoder.decode(fileName);
Log.i("tag", "fileName="+fileName);
File directory=Environment.getExternalStorageDirectory();
File file=new File(directory,fileName);
if(file.exists()){
Log.i("tag", "The file has already exists.");
return fileName;
}
try {
HttpClient client = new DefaultHttpClient();
// client.getParams().setIntParameter("http.socket.timeout",3000);//设置超时
HttpGet get = new HttpGet(url);
HttpResponse response = client.execute(get);
if(HttpStatus.SC_OK==response.getStatusLine().getStatusCode()){
HttpEntity entity = response.getEntity();
InputStream input = entity.getContent();
mDialog.setMax( (int) entity.getContentLength() );
writeToSDCard(fileName,input);
input.close();
// entity.consumeContent();
return fileName;
}else{
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
@Override
protected void onCancelled() {
// TODO Auto-generated method stub
super.onCancelled();
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
closeProgressDialog();
if(result==null){
Toast t=Toast.makeText(getApplicationContext(), "连接错误!请稍后再试!", Toast.LENGTH_LONG);
t.setGravity(Gravity.CENTER, 0, 0);
t.show();
return;
}
Toast t=Toast.makeText(getApplicationContext(), "已保存到SD卡。", Toast.LENGTH_LONG);
t.setGravity(Gravity.CENTER, 0, 0);
t.show();
File directory=Environment.getExternalStorageDirectory();
File file=new File(directory,result);
Log.i("tag", "Path="+file.getAbsolutePath());
Intent intent = getFileIntent( file );
startActivity(intent);
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
showProgressDialog();
}
@Override
protected void onProgressUpdate(Void... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
}
/***
*
* **/
private void showProgressDialog(){
if(mDialog==null){
mDialog = new ProgressDialog(MainActivity.this);
mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);//设置风格为圆形进度条
mDialog.setMessage("正在加载 ,请等待...");
mDialog.setIndeterminate(false);//设置进度条是否为不明确
mDialog.setCancelable(true);//设置进度条是否可以按退回键取消
mDialog.setCanceledOnTouchOutside(false);
mDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
// TODO Auto-generated method stub
mDialog=null;
}
});
mDialog.show();
}
}
private void closeProgressDialog(){
if(mDialog!=null){
mDialog.dismiss();
mDialog=null;
}
}
public Intent getFileIntent(File file){
// Uri uri = Uri.parse("http://m.ql18.com.cn/hpf10/1.pdf");
Uri uri = Uri.fromFile(file);
String type = getMIMEType(file);
Log.i("tag", "type="+type);
Intent intent = new Intent("android.intent.action.VIEW");
intent.addCategory("android.intent.category.DEFAULT");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(uri, type);
return intent;
}
public void writeToSDCard(String fileName,InputStream input){
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
File directory=Environment.getExternalStorageDirectory();
File file=new File(directory,fileName);
// if(file.exists()){
// Log.i("tag", "The file has already exists.");
// return;
// }
try {
FileOutputStream fos = new FileOutputStream(file);
byte[] b = new byte[2048];
int j = 0;
int total=0;
while ((j = input.read(b)) != -1) {
fos.write(b, 0, j);
total+=j;
mDialog.setProgress( total );
}
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
Log.i("tag", "NO SDCard.");
}
}
private String getMIMEType(File f){
String type="";
String fName=f.getName();
/* 取得扩展名 */
String end=fName.substring(fName.lastIndexOf(".")+1,fName.length()).toLowerCase();
/* 依扩展名的类型决定MimeType */
if(end.equals("pdf")){
type = "application/pdf";//
}
else if(end.equals("m4a")||end.equals("mp3")||end.equals("mid")||
end.equals("xmf")||end.equals("ogg")||end.equals("wav")){
type = "audio/*";
}
else if(end.equals("3gp")||end.equals("mp4")){
type = "video/*";
}
else if(end.equals("jpg")||end.equals("gif")||end.equals("png")||
end.equals("jpeg")||end.equals("bmp")){
type = "image/*";
}
else if(end.equals("apk")){
/* android.permission.INSTALL_PACKAGES */
type = "application/vnd.android.package-archive";
}
// else if(end.equals("pptx")||end.equals("ppt")){
// type = "application/vnd.ms-powerpoint";
// }else if(end.equals("docx")||end.equals("doc")){
// type = "application/vnd.ms-word";
// }else if(end.equals("xlsx")||end.equals("xls")){
// type = "application/vnd.ms-excel";
// }
else{
// /*如果无法直接打开,就跳出软件列表给用户选择 */
type="*/*";
}
return type;
}
}
浙公网安备 33010602011771号