Fork me on GitHub

Android WebView

PrintWebActivity
package com.zkc.pinter.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Picture;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.btpdemo76.R;

import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.zkc.helper.printer.*;

/**
 * Created by NickChung on 3/20/15.
 */
public class PrintWebActivity extends Activity {

    public WebView newWebView = null;
    List<Map<String, String>> listData = new ArrayList<Map<String, String>>();
    private long firstTime = 0;
    private String title;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_print_web);
        title = getTitle().toString();

        final EditText txtUrl = (EditText) findViewById(R.id.txtURL);
        final WebView mWebView = (WebView) findViewById(R.id.wvSite);
        final Button btnGo = (Button) findViewById(R.id.btnGo);
        final Button btnGoBack = (Button) findViewById(R.id.btnGoBack);
        final Button btnForward = (Button) findViewById(R.id.btnForward);
        final Button btnReload = (Button) findViewById(R.id.btnReload);

        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        mWebView.addJavascriptInterface(new WebAppInterface(this), "android");
        mWebView.getSettings().setSupportMultipleWindows(true);
        mWebView.getSettings().setDisplayZoomControls(true);
        mWebView.getSettings().setBuiltInZoomControls(true);
        txtUrl.setText("http://www.ri-pai.com/AdminHellToBid/index.php/Index/Index.html");
        //txtUrl.setText("http://192.168.0.106/bt.html");

        if (!txtUrl.getText().toString().isEmpty()) {
            mWebView.loadUrl(txtUrl.getText().toString());
        }

        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // TODO Auto-generated method stub
                //返回值是true的时候控制去WebView打开,为false调用系统浏览器或第三方浏览器
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                setTitle(title + "(Loading...)");
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                setTitle(title + "(100%)");
                super.onPageFinished(view, url);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode,
                                        String description, String failingUrl) {

                super.onReceivedError(view, errorCode, description, failingUrl);

                view.loadDataWithBaseURL("about:blank"
                        , "<a style="font-size: 36px;">访问出错,请检查:<br />1.WIFI是否已经连接 <br />2.网页地址是否正确 <br /<(^_^)</a>"
                        , "text/html"
                        , "UTF-8", null);
            }

        });

        mWebView.setWebChromeClient(new MyWebChromeClient());
        /*
        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, final int newProgress) {
                // TODO Auto-generated method stub
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        setTitle(title + "(" + String.valueOf(newProgress) + "%)");
                    }
                });
            }
        });*/

        btnGo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mWebView.loadUrl(txtUrl.getText().toString());
            }
        });

        btnGoBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mWebView.goBack();
            }
        });

        btnForward.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mWebView.goForward();
            }
        });

        btnReload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mWebView.reload();
            }
        });

        //PrintActivity.pl.printText(mWebView.getTitle() + "\r\n");
        //PrintActivity.pl.printImage(BitmapFactory.decodeResource(getResources(), R.drawable.demo));
    }


    public boolean dispatchKeyEvent(KeyEvent event) {
        // TODO Auto-generated method stub
        if (event.getAction() == KeyEvent.ACTION_DOWN
                && event.getKeyCode() == KeyEvent.KEYCODE_BACK) {

            Intent i = new Intent(Intent.ACTION_MAIN);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            i.addCategory(Intent.CATEGORY_HOME);
            startActivity(i);

            return true;//返回true,把事件消费掉,不会继续调用onBackPressed
        }
        return super.dispatchKeyEvent(event);
    }

    /*
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        Resources res = getResources();
        String[] cmdStr = res.getStringArray(R.array.cmd);
        for (int i = 0; i < cmdStr.length; i++) {
            String[] cmdArray = cmdStr[i].split(",");
            if (cmdArray.length == 2) {
                Map<String, String> map = new HashMap<String, String>();
                map.put("title", cmdArray[0]);
                map.put("description", cmdArray[1]);
                menu.add(0, i, i, cmdArray[0]);
                listData.add(map);
            }
        }

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(android.view.MenuItem item) {
        Map map = listData.get(item.getItemId());
        String cmd = map.get("description").toString();
        byte[] bt = PrintCmdActivity.hexStringToBytes(cmd);
        PrintActivity.pl.write(bt);
        return false;
    }*/
}
LabelViewActivity
package com.zkc.pinter.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Picture;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;

import com.example.btpdemo76.R;
import com.zkc.helper.printer.PrinterClass;
import com.zkc.helper.printer.WebAppInterface;

/**
 * Created by NickChung on 3/25/15.
 */
public class LabelViewActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_label_view);

        final WebView mWebView = (WebView) findViewById(R.id.wvLabel);
        final Button btnPrint = (Button) findViewById(R.id.btnPrint);
        final Button btnCR = (Button) findViewById(R.id.btnCR);
        final Button btnBack = (Button) findViewById(R.id.btnBack);

        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.addJavascriptInterface(new WebAppInterface(this), "android");
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        mWebView.loadUrl(getIntent().getStringExtra("url"));

        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // TODO Auto-generated method stub
                //返回值是true的时候控制去WebView打开,为false调用系统浏览器或第三方浏览器
                view.loadUrl(url);
                return true;
            }

        });

        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Intent it = new Intent(LabelViewActivity.this, PrintWebActivity.class);
                //startActivity(it);
                LabelViewActivity.this.onBackPressed();

            }
        });

        btnCR.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(PrintActivity.pl.getState() != PrinterClass.STATE_CONNECTED) {
                    Intent intent = new Intent(LabelViewActivity.this, MainActivity.class);
                    startActivity(intent);
                }
                
                byte[] bt = PrintCmdActivity.hexStringToBytes("0A");
                PrintActivity.pl.write(bt);
            }
        });

        btnPrint.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if(PrintActivity.pl.getState() != PrinterClass.STATE_CONNECTED) {
                    Intent intent = new Intent(LabelViewActivity.this, MainActivity.class);
                    startActivity(intent);
                }
                Picture pic = mWebView.capturePicture();
                int width = pic.getWidth();
                int height = pic.getHeight();
                if (width > 0 && height > 0) {
                    Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
                    Canvas canvas = new Canvas(bmp);
                    pic.draw(canvas);
                    try {
                        /*
                        String fileName = Environment.getExternalStorageDirectory() + "/" + System.currentTimeMillis() + ".png";
                        FileOutputStream fos = new FileOutputStream(fileName);
                        if (fos != null) {
                            bmp.compress(Bitmap.CompressFormat.PNG, 90, fos);
                            fos.close();
                        }
                        Toast.makeText(getApplicationContext(), "截图成功,文件名是:" + fileName, Toast.LENGTH_SHORT).show();
                        */
                        PrintActivity.pl.printImage(bmp);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            }
        });
    }

    public boolean dispatchKeyEvent(KeyEvent event) {
        // TODO Auto-generated method stub
        if (event.getAction() == KeyEvent.ACTION_DOWN
                && event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            return true;//返回true,把事件消费掉,不会继续调用onBackPressed
        }
        return super.dispatchKeyEvent(event);
    }
}
WebAppInterface
package com.zkc.helper.printer;

import android.content.Context;
import android.content.Intent;
import android.webkit.JavascriptInterface;
import android.widget.Toast;

import com.zkc.pinter.activity.LabelViewActivity;

/**
 * Created by NickChung on 3/25/15.
 */
public class WebAppInterface {
    Context mContext;

    /**
     * Instantiate the interface and set the context
     */
    public WebAppInterface(Context c) {
        mContext = c;
    }

    /**
     * Show a toast from the web page
     */
    // 如果target 大于等于API 17,则需要加上如下注解
    @JavascriptInterface
    public void showWeb(String url) {
        Intent intent = new Intent(mContext, LabelViewActivity.class);
        intent.putExtra("url", url);
        mContext.startActivity(intent);
    }
}
bt.html
<html>
<head>
<script type="text/javascript">  
function showWeb(url){
	try{
		window.android.showWeb(url);
	}
	catch(ex){}
}
</script>
</head>
<body>
	<input type="button" value="View" onclick="showWeb('http://www.ybidder.com/PrintTest.html');">
</body>
</html>
MyWebChromeClient
package com.zkc.pinter.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;

import com.example.btpdemo76.R;


//****************************************************************************
public class MyWebChromeClient extends WebChromeClient {

    public WebView newWebView = null;

    @Override
    public boolean onCreateWindow(WebView view, boolean dialog, boolean userGesture, Message resultMsg) {
        newWebView = new WebView(view.getContext());
        view.addView(newWebView);
        WebSettings settings = newWebView.getSettings();
        settings.setJavaScriptEnabled(true);
        //这个setWebViewClient要加上,否则window.open弹出浏览器打开。
        newWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                View dlgView = LayoutInflater.from(view.getContext()).inflate(R.layout.popup, null);
                WebView wvPop = (WebView) dlgView.findViewById(R.id.wvPop);
                wvPop.setWebViewClient(new WebViewClient() {
                    @Override
                    public boolean shouldOverrideUrlLoading(WebView view, String url) {
                        // TODO Auto-generated method stub
                        //返回值是true的时候控制去WebView打开,为false调用系统浏览器或第三方浏览器
                        view.loadUrl(url);
                        return true;
                    }
                });
                wvPop.loadUrl(url);

                final AlertDialog dlg = new AlertDialog.Builder(view.getContext())
                        .setIcon(R.drawable.ic_launcher)
                        .setTitle(view.getTitle())
                        .setView(dlgView)
                        .setPositiveButton("返回",null)
                        .create();

                /*
                Button btnExit = (Button) dlgView.findViewById(R.id.btnExit);
                btnExit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dlg.cancel();
                    }
                });*/

                dlg.show();

                Window win = dlg.getWindow();
                win.getDecorView().setPadding(0, 0, 0, 0);
                WindowManager.LayoutParams lp = win.getAttributes();
                lp.width = WindowManager.LayoutParams.MATCH_PARENT;
                lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
                win.setAttributes(lp);

                return true;
            }
        });

        newWebView.setWebChromeClient(this);

        WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
        transport.setWebView(newWebView);
        resultMsg.sendToTarget();

        return true;
    }

    @Override
    public void onCloseWindow(WebView view) {
        if (newWebView != null) {
            newWebView.setVisibility(View.GONE);
            view.removeView(newWebView);
        }
    }
}

 Ref:Android WebView中的JavaScript代码使用

 Ref:Android WebView与JavaScript交互操作(Demo)

posted @ 2015-03-25 19:32  Nick.Chung  阅读(424)  评论(0编辑  收藏  举报