Android开发hrm5调摄像头拍照后调jsAndroid5.0的可以Android4.2.2和Android4.1.1不行

发布于 2022-09-02 09:15:52 字数 22738 浏览 15 评论 0

jsp页面
<html>

<head>
    <meta charset="GBK">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 引入JQuery Mobile标签 -->
    <%@ include file="/importMobile.jsp"%>
    
</head>
<mt:body>
    <mt:page id="pa">
        <script type="text/javascript">
            function show(){
                androidInt.showToast("钮ss开始");
                mUtil.showToast("钮ss开始");
            }
            function returnDetectFace(qrcode){
                mUtil.showToast("钮ss开始");
                viewProcessDiagram(qrcode);
            }
            function viewProcessDiagram(qrcode){
                
                turnto("siQuery.m?method=getIamge&qrcode=" + qrcode ,'true');
            }
        </script>
        <mt:fixheader title="摄像头拍照"  theme="f" sy="true" back="true"></mt:fixheader>
        <mt:content theme="e">
               <div><input type="file" capture="camera" accept="image/*" id="cameraInput"  name="cameraInput" class="sign_file"/> </div>
        </mt:content>
    </mt:page>
</mt:body>

</html>

Android代码

package com.dareway.rsmc;

import java.io.ByteArrayOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.dareway.rsmc.R;
import com.dareway.sixxcx.PollingUtil.Installation;
import com.dareway.sixxcx.PollingUtil.PollingService;
import com.dareway.sixxcx.PollingUtil.PollingUtils;
import com.dareway.sixxcx.Util.DataObject;
import com.dareway.sixxcx.Util.DataStore;
import com.dareway.sixxcx.Util.LesbUtil;
import com.dareway.sixxcx.Util.PubInfo;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.webkit.ConsoleMessage;
import android.webkit.DownloadListener;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.webkit.SslErrorHandler;
import android.net.Uri;
import android.net.http.SslError;

@SuppressLint("NewApi")
public class MainActivity extends Activity {

private WebView webView = null;// 调用浏览器容器
public String pathLength = "";// 记录浏览器路径长度
private String url = PubInfo.URL + "/mhso/welcome.jsp";// 服务器访问地址
private String errorMsg = "网络连接失败,请检查!";// 错误提示信息
private int resultcode=2;
private ProgressDialog dialog;// 信息提示面板
public Handler handler = new Handler();
//创建MyDatabaseHelper对象,指定数据库版本为1
//此处使用相对路径,数据库文件自动会保存在程序的数据文件夹的databases目录下
MyDatabaseHelper dbHelper;
UpdateManager mUpdateManager;// 检测自动更新对象

@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    
    //加载数据库
    dbHelper = new MyDatabaseHelper(this,"sixxcx.db3",1);
    dbHelper.getReadableDatabase();
    
    
    // android3.0以上凡是涉及到网络,下载等耗时操作,都不能在主线程中运行,加上以下代码,可以取消严格限制
    if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }
    if(checkURL()){// 判断服务器连接情况
        Installation.id(this);
        // 设置页面无表头(全屏显示)
        requestWindowFeature(Window.FEATURE_NO_TITLE);

// // 设置全屏,包括通知栏
// getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
// WindowManager.LayoutParams.FLAG_FULLSCREEN);

        // 设置键盘使用模式
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN |
                WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        setContentView(R.layout.activity_main);
        //开始轮询
        PollingUtils.startPollingService(this, PubInfo.POLLINGTIME, PollingService.class, PollingService.ACTION);   
            
        webView = (WebView) this.findViewById(R.id.webView);
        webView.setBackgroundColor(0);//先设置背景色为transparent
        webView.setBackgroundResource(R.drawable.bg_zz);//然后设置背景图片
         //检测版本是否需要更新  
        mUpdateManager = new UpdateManager(this, webView);  
        mUpdateManager.checkUpdateInfo(this); 

        webView.setDownloadListener(new DownloadListener() { 
            @Override 
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) { 
             // 监听下载功能,当用户点击下载链接的时候,直接调用系统的浏览器来下载 
             Uri uri = Uri.parse(url); 
             Intent intent = new Intent(Intent.ACTION_VIEW, uri); 
             startActivity(intent); 
             } 
        }); 

        webView.setWebChromeClient(new WebChromeClient()
        {

// public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
// FileChooserParams fileChooserParams) {
// super.onShowFileChooser(webView, filePathCallback, fileChooserParams);
// Intent i = new Intent(Intent.ACTION_GET_CONTENT);
// i.addCategory(Intent.CATEGORY_OPENABLE);
// i.setType("image/*");
// startActivityForResult(Intent.createChooser(i, "File Chooser"), 222);
// return false;
// }

                //The undocumented magic method override
                //Eclipse will swear at you if you try to put @Override here
                // For Android 3.0+
                public void openFileChooser(ValueCallback<Uri> uploadMsg) {
                    Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        
                    startActivityForResult(Intent.createChooser(i, "File Chooser"), resultcode);
                    }
                    
                // For Android 3.0+
                public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
                    Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                
                    startActivityForResult(Intent.createChooser(i, "File Browser"), resultcode);
                }
                    
                //For Android 4.1
                public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                //openFileChooser(uploadMsg);
                    Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(Intent.createChooser(i, "File Chooser"), resultcode);
                        
                }
                    
                
                @Override
                public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
                    // TODO Auto-generated method stub
                    Toast.makeText(MainActivity.this, consoleMessage.message(), Toast.LENGTH_SHORT).show();
                        
                    return true;
                                        
                }

                @Override
                public boolean onJsAlert(WebView view, String url,
                        String message, JsResult result) {
                    // TODO Auto-generated method stub
                    Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
                    return true;
                }
            @Override
                public boolean onJsConfirm(WebView view, String url,
                            String message, JsResult result) {
                                // TODO Auto-generated method stub
                    Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
                    return true;
                }
            @Override
            public boolean onJsPrompt(WebView view, String url,
                        String message, String defaultValue,JsPromptResult result) {
                    // TODO Auto-generated method stub
                    
                    return true;
                }
            @Override
            public boolean onJsTimeout() {
                            // TODO Auto-generated method stub
                    return true;
            }
            @Override
            public boolean onJsBeforeUnload(WebView view, String url,
                    String message, JsResult result) {
                // TODO Auto-generated method stub
                    return super.onJsBeforeUnload(view, url, message, result);
            }
            
        });
        // 帮助WebView处理各种通知、请求事件
        webView.setWebViewClient(new WebViewClient() 
        { 
            @Override 
            public void onPageFinished(WebView view,String url) 
            { 
                dialog.dismiss(); // 页面加载完毕,关闭弹出的提示信息框
            }
            
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
           
                //在2.3上面不加这句话,可以加载出页面,在4.0上面必须要加入,不然出现白屏
                //view.loadUrl(url);//在当前的webview中跳转到新的url
                
                //启动手机浏览器来打开新的url
                Intent i = new Intent(Intent.ACTION_VIEW);
                i.setData(Uri.parse(url));
                startActivity(i);
                
                //返回值是true的时候控制去WebView打开,为false调用系统浏览器或第三方浏览器
                return true;
            }
            
            //add WebView访问https by hdz 2015.5.7
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error)
            {
                //handler.cancel(); // Android默认的处理方式,webview空白
                handler.proceed();  // 接受所有网站的证书
                //handleMessage(Message msg); // 进行其他处理
            }
        }); 
        
        webView.getSettings().setJavaScriptEnabled(true);// 使用js
        webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);// 使用缓存
        // 自适应屏幕大小,居中显示
        webView.getSettings().setUseWideViewPort(true); 
        webView.getSettings().setLoadWithOverviewMode(true);
        // 手动开启DOM Storage
        webView.getSettings().setDomStorageEnabled(true);
        //取消滚动条 
        webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);

        // 设置在webview中调用js的对象
        webView.addJavascriptInterface(new JsObject(this,handler), "androidInt");
         // 加载页面
        dialog = ProgressDialog.show(this,null,"页面加载中,请稍后.."); // 加载页面时弹出提示加载窗口,加载完毕自动关闭
        
        loadURL(url);
    }else{
        // 连接服务器失败,提示错误信息
        setContentView(R.layout.activity_error);
        TextView info =(TextView) findViewById(R.id.error);
        info.setText(errorMsg) ;
        
        OnClickListener okListener = new OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        };
                
            Button btnOk = (Button)findViewById(R.id.ok);
            btnOk.setOnClickListener(okListener);
        }
}

public void queryAndSetLogon(){
    //获得本地数据库中保存的内容
    queryLogin(dbHelper.getReadableDatabase());
    //N秒钟后设置登录信息
    initLogHandler.sendEmptyMessageDelayed(0,0);
}
String username = "";
String password = "";
String zddlbz = "";
/**
    • 获取登录信息

    • @author dy

    • @time 2013-10-30
      */

    1. String queryLogin(SQLiteDatabase db){

         Cursor c = db.rawQuery("select * from userinfo where zddlbz = '1' ", new String[]{});
         if(c.moveToFirst() != false){
             int usernameCol = c.getColumnIndex("username");
             int passwordCol = c.getColumnIndex("password");
             username = c.getString(usernameCol);
             password = c.getString(passwordCol);
             zddlbz = "1";
         }else{
             zddlbz = "0";
             queryUser(db);
         }
         String result = username + "-;-" + password;
         return result;

      }

      /**

      • 注销

      • @author dy

      • @time 2014-01-20
        */

    2. void logout(SQLiteDatabase db){

         db.execSQL("update userinfo set zddlbz = '0' ", new String[]{});

      }
      /**

      • 查询登录用户历史信息

      • @author dy

      • @time 2013-11-14
        */

    3. String queryUser(SQLiteDatabase db){

         Cursor c = db.rawQuery("select * from userinfo order by logontime desc ", new String[]{});
         if(c.moveToFirst() != false){
             int usernameCol = c.getColumnIndex("username");
             int passwordCol = c.getColumnIndex("password");
             username = c.getString(usernameCol);
             password = c.getString(passwordCol);
         }else{
             username = "";
             password = "";
         }
         String result = username + "-;-" + password;
         return result;

      }
      /**

      • 更新登录信息

      • @author dy

      • @time 2013-11-14
        */

    4. void updateLogin(SQLiteDatabase db,String username,String password,String save,String zddl){

         SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
         String date = sDateFormat.format(new Date());  
         db.execSQL("delete from userinfo where username = '" + username + "'");
         if("1".equals(zddl)){
             db.execSQL("insert into userinfo(username,password,zddlbz,logontime) values(?,?,?,?)",new String[]{username,password,"1",date});
         }else if("1".equals(save)){
             db.execSQL("insert into userinfo(username,password,zddlbz,logontime) values(?,?,?,?)",new String[]{username,password,"0",date});
         }else{
             db.execSQL("insert into userinfo(username,password,zddlbz,logontime) values(?,?,?,?)",new String[]{username,"","0",date});
         }

      }

      /**

      • 使用webView加载url页面

      • @author cw

      • @time 2013-6-14
        */

    5. void loadURL(String url) {

         if (webView != null) {
             webView.loadUrl(url);
         }

      }
      /**

      • 判断服务器是否连接

      • @author dy

      • @return isConn
        */

    6. boolean isConnByHttp(String urlString){

         boolean isConn = false;
         URL url;
         HttpURLConnection conn = null;
         try {
             url = new URL(urlString);
             conn = (HttpURLConnection)url.openConnection();
             conn.setConnectTimeout(1000*PubInfo.connectTime);
             conn.setReadTimeout(1000*PubInfo.connectTime);
             if(conn.getResponseCode()==200){
                 isConn = true;
             }
         } catch (Exception e) {
             errorMsg = "网络连接失败,请检查网络状态。";
         }
         return isConn;

      }

      /**

      • 先查询手机本机存储查询url地址

      • 如果不通调用公司服务查询对应dbid的url地址

      • @return
        */

    7. boolean checkURL() {

         boolean isConn = false;
         SQLiteDatabase db = dbHelper.getReadableDatabase();
         Cursor c = db.rawQuery("select * from urlinfo where dbid = '" + PubInfo.DBID + "'", new String[]{});
         if(c.moveToFirst() != false){
             int urlCol = c.getColumnIndex("url");
             url = c.getString(urlCol);
         }
         if(!isConnByHttp(url)){
             try{
                 DataObject pdo = new DataObject();
                 pdo.put("dsbh", PubInfo.DBID);
                 DataObject result = LesbUtil.invokeService(pdo, "CmsService", "getCityServiceUrl");
                 DataStore vds = result.getDataStore("fwdzds");
                 if(vds.rowCount() > 0){
                     url = vds.getString(0, "fwdz");
                 }
                 if(isConnByHttp(url)){
                     isConn = true;
                     updateUrl(db, url);
                 }
             }catch (Exception e) {
                 errorMsg = "网络连接失败,请检查网络状态。";
             }
         }else{
             isConn = true;
         }
         return isConn;

      }

      /**

      • 更新url地址

      • @author dy

      • @time 2014-01-20
        */

    8. void updateUrl(SQLiteDatabase db,String urlStr){

         db.execSQL("delete from urlinfo where username = '" + PubInfo.DBID + "'");
         db.execSQL("insert into urlinfo(dbid,url) values(?,?)",new String[]{PubInfo.DBID ,urlStr + "/mhso/welcome.jsp"});

      }

      /**

      • 扫描二维码activity跳转

      • @author dy

      • @time 2014-03-28
        */

    9. void QRCode(){

         Intent intent = new Intent();
      
         intent.setClass(MainActivity.this, CaptureActivity.class);
      
         startActivityForResult(intent, 0);

      }
      /**

      • 当屏幕旋转时,调用方法

      • @author dy

      • @ 2013-8-26
        */
        @Override

    10. void onConfigurationChanged(Configuration newConfig){

         super.onConfigurationChanged(newConfig);        
         //当屏幕旋转时,调用方法,设置按钮的位置
         if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE
                 ||newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
             if(webView != null){
                 webView.loadUrl("javascript:setButtonToMiddle()");
             }
         }
         

      }

    11. waitTime = 2000;

    12. isExit;

      /**

      • 点击返回按钮时,返回上一页

      • @author cw

      • @time 2013-6-14
        */
        @Override

    13. boolean onKeyDown(int keyCode, KeyEvent event) {

         if (event.getAction() == KeyEvent.ACTION_DOWN
                 && KeyEvent.KEYCODE_MENU == keyCode) {
             exit();
         }
         if (event.getAction() == KeyEvent.ACTION_DOWN
                 && KeyEvent.KEYCODE_BACK == keyCode) {
             if("0".equals(pathLength) || "".equals(pathLength)){
                 exit();
             }else{
                 if(webView != null){
                     webView.loadUrl("javascript:goBack()");
                 }
             }
         }
         return true;

      }

      /**

      • 点击功能键时执行方法

      • @author dy

      • @time 2014-01-29
        */

    14. void exit() {

         if (!isExit) {
             isExit = true;
             Toast.makeText(getApplicationContext(), "再按一次退出程序",
                     Toast.LENGTH_SHORT).show();
             mHandler.sendEmptyMessageDelayed(0, waitTime);
         } else {
             System.exit(0);
         }

      }

      Handler mHandler = new Handler() {

         @Override
         public void handleMessage(Message msg) {
             if (msg.what == 0x1) {
                 webView.loadUrl("file:///android_asset/dwWelcome.html");
             } else {
                 super.handleMessage(msg);
                 isExit = false;
             }
         }
      

      };

      /**

      • 登录
        */
        Handler initLogHandler = new Handler() {

          @Override
          public void handleMessage(Message msg) {
              webView.loadUrl("javascript:doLogon('"+username+"','"+password+"','"+zddlbz+"')");
          }
        

      };
      @SuppressLint("HandlerLeak")
      @Override

    15. void onActivityResult(int requestCode,int resultCode,Intent data){

           
           switch(resultCode){  
             case RESULT_OK:  
                 /*取得来自扫码页面的数据,并显示到画面*/  
                 Bundle bundle = data.getExtras(); 
                 
                 String qrcode = bundle.getString("qrcode");
                 if(webView != null){
                     webView.loadUrl("javascript:returnQRCode('" + qrcode + "')");
                 }
             case DEFAULT_KEYS_SHORTCUT:  
                 /*取得来自摄像头照片,并显示到画面*/
                 Log.e("Main", "data--->" + data.toString());
                 String imageData="";
                 Uri uri = data.getData();
                 try {
                         //get the image path
                         String[] projection = {MediaStore.Images.Media.DATA};
                         CursorLoader cursorLoader = new CursorLoader(this,uri,projection,null,null,null);
                         Cursor cursor = cursorLoader.loadInBackground();
                         int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                         cursor.moveToFirst();
      
                         String path = cursor.getString(column_index);
                         imageData= encode(path);
                     } catch (Exception ex) {
                         Log.e("Main", "failed." + ex.getMessage());
                      }
      
                 if(webView != null){
                     Log.d("Main", "ok." +imageData);
                     webView.loadUrl("javascript:show()");
                     //webView.loadUrl("javascript:returnDetectFace('" + imageData + "')");
                     
                 }
             }  

      }

    16. String encode(String path) {

         //decode to bitmap
         Bitmap bitmap = BitmapFactory.decodeFile(path);
         Log.e("main", "bitmap width: " + bitmap.getWidth() + " height: " + bitmap.getHeight());
         //convert to byte array
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
         bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
         byte[] bytes = baos.toByteArray();
      
         //base64 encode
         byte[] encode = Base64.encode(bytes,Base64.DEFAULT);
         String encodeString = new String(encode);
         return encodeString;

      }
      @Override

    17. void onDestroy()
      {

         super.onDestroy();
         // 退出程序时关闭MyDatabaseHelper里的SQLiteDatabase
         if (dbHelper != null)
         {
             dbHelper.close();
         }

      }
      }

    如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

    扫码二维码加入Web技术交流群

    发布评论

    需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
    列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文