简单齐全的webview与H5 交互 多中自定义进度条
demo下载
http://download.csdn.net/detail/menglele1314/9213035
/****************************红色的可以重点看下*************************************/
package com.hexun.webview.activity;
import com.hexun.webview.view.MyProgressBar;
import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
/**
*
*
* @author menglele Create at 2015年6月5日下午2:16:39
*
*/
public class MainActivity extends Activity {
private Button submit;
private TimeCount time;
private AnimationDrawable fightnimation, fightnimationab;
private ImageView pb, net, netab;
private Dialog mLoading;
private Animation animation;
private MyProgressBar progressBar1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
submit = (Button) findViewById(R.id.btn_login_submit);
pb = (ImageView) findViewById(R.id.iv_failure);
animation = AnimationUtils.loadAnimation(MainActivity.this, R.anim.cirle);
animation.setInterpolator(new LinearInterpolator());
netab = (ImageView) findViewById(R.id.iv_netab);
netab.setBackgroundResource(R.anim.fight);
fightnimationab = (AnimationDrawable) netab.getBackground();
net = (ImageView) findViewById(R.id.iv_net);
net.setBackgroundResource(R.anim.loading);
fightnimation = (AnimationDrawable) net.getBackground();
progressBar1 = (MyProgressBar) findViewById(R.id.progressBar1);
time = new TimeCount(60000, 1000);
submit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// // 对话框加载进度条
// mLoading = createLoadingDialog(MainActivity.this);
// mLoading.show();
// // mLoading.dismiss();
// // 常用加载进度条 带动画的
// pb.startAnimation(animation);
// fightnimationab.start();
// fightnimation.start();
// // 带刻度值的横向进度条
// progressBar1.setProgress(65);
startActivity(new Intent(MainActivity.this,
WebViewActivity.class));
// time.start();// 开始计时
}
});
// 注册广播
registerReceiver(homeKeyEventReceiver, new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
}
// 监听home键和菜单键
private BroadcastReceiver homeKeyEventReceiver = new BroadcastReceiver() {
String REASON = "reason";
String HOMEKEY = "homekey";
String RECENTAPPS = "recentapps";
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
String reason = intent.getStringExtra(REASON);
if (TextUtils.equals(reason, HOMEKEY)) {
// 点击 Home键
Toast.makeText(getApplicationContext(), "Home", 1).show();
} else if (TextUtils.equals(reason, RECENTAPPS)) {
// 点击 菜单键
Toast.makeText(getApplicationContext(), "菜单键", 1).show();
}
}
}
};
// 倒计时
class TimeCount extends CountDownTimer {
public TimeCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onFinish() {// 计时完毕
submit.setText("获取验证码");
submit.setClickable(true);
}
@Override
public void onTick(long millisUntilFinished) {// 计时过程
submit.setClickable(false);// 防止重复点击
submit.setText(millisUntilFinished / 1000 + "s");
}
}
/**
* 得到自定义的progressDialog
*
* @param context
* @return
*/
public static Dialog createLoadingDialog(Context context) {
LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.layout_loading_dialog, null); // 得到加载view
LinearLayout layout = (LinearLayout) v.findViewById(R.id.dialog_view); // 加载布局
ImageView spaceshipImage = (ImageView) v.findViewById(R.id.img);
Animation animation = AnimationUtils.loadAnimation(context, R.anim.cirle); // 加载动画
animation.setInterpolator(new LinearInterpolator());
spaceshipImage.startAnimation(animation); // 使用ImageView显示动画
Dialog loadingDialog = new Dialog(context, R.style.loading_dialog); // 创建自定义样式dialog
// loadingDialog.setCancelable(false);// 不可以用"返回键"取消
loadingDialog.setContentView(layout, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
return loadingDialog;
}
}
/************************************************************************************************************************/
package com.hexun.webview.activity;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.hexun.webview.network.DataCleanManager;
public class WebViewActivity extends Activity {
private WebView webView;
private ProgressBar pb;
private ProgressBar pb1;
private ImageView iv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.webview);
webView = (WebView) findViewById(R.id.webView);
iv = (ImageView) findViewById(R.id.iv_net);
pb = (ProgressBar) findViewById(R.id.pb_web);
pb1 = (ProgressBar) findViewById(R.id.progressBar1);
}
@SuppressLint({ "SetJavaScriptEnabled", "JavascriptInterface" })
protected void onStart() {
super.onStart();
WebSettings webSettings = webView.getSettings();
webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
webView.addJavascriptInterface(this, "javatojs");
webView.getSettings().setJavaScriptEnabled(true);
// WebView加载web资源
// webView.loadUrl("");
// 从assets目录下面的加载html
// webView.loadUrl("file:///android_asset/ZheXianR.html");
webView.loadUrl("http://finance.sina.com.cn");
webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// 返回值是true的时候控制去WebView打开,为false调用系统浏览器或第三方浏览器
// 这里也可以用Intent传给其它WebView,的其它浏览器中打开
view.loadUrl(url);
return true;
}
@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
// 重写此方法可以让webview处理https请求。
super.onReceivedSslError(view, handler, error);
handler.proceed();
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// 在页面加载开始时调用。
super.onPageStarted(view, url, favicon);
webView.setVisibility(View.GONE);
pb.setVisibility(View.VISIBLE);
}
@Override
public void onPageFinished(WebView view, String url) {
// 在页面加载结束时调用。
super.onPageFinished(view, url);
webView.setVisibility(View.VISIBLE);
pb.setVisibility(View.GONE);
}
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
// 网络不通,加载失败
super.onReceivedError(view, errorCode, description, failingUrl);
view.loadData("网络连接失败,请稍后重试!", "text/html; charset=utf-8", "utf-8");
iv.setVisibility(View.VISIBLE);
}
@Override
public void onLoadResource(WebView view, String url) {
// 在加载页面资源时会调用,每一个资源(比如图片)的加载都会调用一次。
super.onLoadResource(view, url);
}
});
// 主要处理解析,渲染网页等浏览器做的事情 辅助WebView处理Javascript的对话框,网站图标,网站title,加载进度等
webView.setWebChromeClient(new WebChromeClient() {
@Override
public void onProgressChanged(WebView view, int newProgress) {
// 网页加载的进度值newProgress
super.onProgressChanged(view, newProgress);
pb1.setVisibility(View.VISIBLE);
pb1.setProgress(newProgress);
if (newProgress == 100) {
pb1.setVisibility(View.GONE);
}
}
@Override
public void onReceivedTitle(WebView view, String title) {
setTitle(title);
}
});
// 点击后退按钮,让WebView后退一页(也可以覆写Activity的onKeyDown方法)
webView.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) { // 表示按返回键
webView.goBack(); // 后退
return true;
}
}
return false;
}
});
}
@JavascriptInterface
public void fromWidth() {
DisplayMetrics metric = new DisplayMetrics();
// 取得窗口属性
getWindowManager().getDefaultDisplay().getMetrics(metric);
int width = metric.widthPixels; // 屏幕宽度(像素)
int height = metric.heightPixels; // 屏幕高度(像素)
float density = metric.density; // 屏幕密度(0.75 / 1.0 / 1.5)
int densityDpi = metric.densityDpi; // 屏幕密度DPI(120 / 160 / 240)
webView.loadUrl("javascript:toWidthH5('" + width / density + "')");
}
// App调用H5的方法 也可以传参数
@JavascriptInterface
public void reqDataFromApp() {
webView.loadUrl("javascript:resDataToH5('" + "15858168869" + "')");
}
// H5调用App的方法 也可以传参数
@JavascriptInterface
public void goToBack() {
finish();
}
@Override
protected void onStop() {
DataCleanManager.cleanInternalCache(this);
DataCleanManager.cleanSharedPreference(this);
// 清除cookie即可彻底清除缓存
CookieSyncManager.createInstance(this);
CookieSyncManager.getInstance().startSync();
CookieManager.getInstance().removeAllCookie();
Log.i("WebViewActivity", "<<<<<<<<<<<<<<<<<<<<<<<");
webView.clearCache(true);
webView.clearHistory();
System.gc();
finish();
super.onStop();
}
}
<!-- 自定义进度条 -->
<style name="ProgressBarBg" parent="@android:style/Widget.ProgressBar.Horizontal">
<item name="android:maxHeight">10dip</item>
<item name="android:minHeight">10dip</item>
<item name="android:indeterminateOnly">false</item>
<item name="android:indeterminateDrawable">@android:drawable/progress_indeterminate_horizontal</item>
<item name="android:progressDrawable">@drawable/progressbarbg</item>
</style>
<?xml version="1.0" encoding="utf-8"?>
<!-- 自定义进度条 -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@android:id/background">
<shape>
<corners android:radius="0dip" />
<gradient
android:endColor="#ffffff"
android:startColor="#ffffff" />
</shape>
</item>
<item android:id="@android:id/secondaryProgress">
<clip>
<shape>
<corners android:radius="0dip" />
<gradient
android:endColor="#00FF00"
android:startColor="#00FF00" />
</shape>
</clip>
</item>
<item android:id="@android:id/progress">
<clip>
<shape>
<corners android:radius="0dip" />
<gradient
android:endColor="#00FF00"
android:startColor="#00FF00" />
</shape>
</clip>
</item>
</layer-list>
demo下载
http://download.csdn.net/detail/menglele1314/9213035