Android與js交互拍照上傳資料


應用場景:h5通知android端拍照,選相冊,然后將圖片路徑上傳成功之后,獲取到網絡路徑,將此路徑返還給h5界面,並展示出來。 
android與js快速交互 
效果圖如下: 
這里寫圖片描述 
這里寫圖片描述

1.在Activity類中,通過webview攔截協議,開始拍照或選擇相冊。

    mWebView = (WebView) findViewById(R.id.wv); 
//設置webview可以與js交互 mWebView.getSettings().setJavaScriptEnabled(true); //設置webview加載本地h5頁面 mWebView.loadUrl(“file:///android_asset/choosePic.html”); //設置監聽,獲取webview訪問的url mWebView.setWebViewClient(new WebViewClient() { public boolean shouldOverrideUrlLoading(WebView view, String url) { // 重寫此方法表明點擊網頁里面的鏈接還是在當前的webview里跳轉,不跳到瀏覽器那邊 if(url.contains(“hgj://take/photo”)){ //js定義的協議,android用webview進行攔截 然后本地調用拍照等功能 showPopupWindow((LinearLayout) findViewById(R.id.act_index)); }else { view.loadUrl(url); } return true; } @Override public void onPageFinished(WebView view, String url) { } }); 

 

2. 注冊js接口,JSInterface是自定義的類,里面放的方法必須與js中的方法一致,參數二也是與js協定的,必須與js保持一致。

  mWebView.addJavascriptInterface(new JSInterface(), "hgj");

 

//js接口類 private class JSInterface { @JavascriptInterface public void acceptUrl(String imgUrl) {//此方法是將android端獲取的url返給js } @JavascriptInterface public void fnUrl(String s) { //js可以調用此方法 將s值傳給android端,然后android端進行相應的操作,此參數可以是任意類型的 } @JavascriptInterface public void fnId(String received){ //android 調用js js會回傳參數 Log.i("received--","---"+received); } }

 

3.拍照、上傳圖片相關方法

  //確認上傳圖片 private void upload(String path) throws FileNotFoundException { //此處可以寫入上傳圖片的方法 這里就直接將拍照和選擇相冊得到的本地路徑返回 url=path; Message msg = new Message(); msg.what = 0; mHandler1.sendMessage(msg); } 

 

/* * 相冊或相機 * */ private void showPopupWindow(LinearLayout parent) { if (popWindow == null) { View view = LayoutInflater.from(context).inflate(R.layout.pop_select_photo, null); // 相機/相冊/取消選擇界面 popWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true); initPop(view);// 初始化popwindow參數 } popWindow.setAnimationStyle(android.R.style.Animation_InputMethod); popWindow.setFocusable(true); popWindow.setOutsideTouchable(true); popWindow.setBackgroundDrawable(new BitmapDrawable()); popWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE); popWindow.showAtLocation(parent, Gravity.CENTER, 0, 0); } // 初始化popwindow參數 public void initPop(View view) { photograph = (TextView) view.findViewById(R.id.photograph);// 拍照 albums = (TextView) view.findViewById(R.id.albums);// 相冊 cancel = (LinearLayout) view.findViewById(R.id.cancel);// 取消 // 相機拍照監聽 photograph.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { popWindow.dismiss(); photoSaveName = String.valueOf(System.currentTimeMillis()) + ".png"; photoSavePath = Environment.getExternalStorageDirectory() + "/usershg/cache/"; Uri imageUri = null; Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); imageUri = Uri.fromFile(new File(photoSavePath, photoSaveName)); openCameraIntent.putExtra(MediaStore.Images.Media.ORIENTATION, 0); openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); startActivityForResult(openCameraIntent, PHOTOTAKE); } }); // 相冊獲取監聽 albums.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { popWindow.dismiss(); Intent openAlbumIntent = new Intent(Intent.ACTION_GET_CONTENT); openAlbumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*"); startActivityForResult(openAlbumIntent, PHOTOZOOM); } }); // 取消監聽 cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { popWindow.dismiss(); } }); } @SuppressLint("NewApi") @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode != RESULT_OK) { return; } Uri uri = null; switch (requestCode) { case PHOTOZOOM:// 相冊 if (data == null) { return; } uri = data.getData(); path = getImageAbsolutePath(this, uri); //獲取到圖片路徑,開始上傳 try { upload(path); } catch (FileNotFoundException e) { e.printStackTrace(); } break; case PHOTOTAKE:// 拍照 path = photoSavePath + photoSaveName; //獲取到圖片路徑,開始上傳 try { upload(path); } catch (FileNotFoundException e) { e.printStackTrace(); } break; default: break; } } /** * 根據Uri獲取圖片絕對路徑,解決Android4.4以上版本Uri轉換 * * @param * @param imageUri * @author yaoxing * @date 2014-10-12 */ @TargetApi(19) public static String getImageAbsolutePath(Activity context, Uri imageUri) { if (context == null || imageUri == null) return null; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, imageUri)) { if (isExternalStorageDocument(imageUri)) { String docId = DocumentsContract.getDocumentId(imageUri); String[] split = docId.split(":"); String type = split[0]; if ("primary".equalsIgnoreCase(type)) { return Environment.getExternalStorageDirectory() + "/" + split[1]; } } else if (isDownloadsDocument(imageUri)) { String id = DocumentsContract.getDocumentId(imageUri); Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id)); return getDataColumn(context, contentUri, null, null); } else if (isMediaDocument(imageUri)) { String docId = DocumentsContract.getDocumentId(imageUri); String[] split = docId.split(":"); String type = split[0]; Uri contentUri = null; if ("image".equals(type)) { contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; } else if ("video".equals(type)) { contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; } else if ("audio".equals(type)) { contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; } String selection = MediaStore.Images.Media._ID + "=?"; String[] selectionArgs = new String[]{split[1]}; return getDataColumn(context, contentUri, selection, selectionArgs); } } // MediaStore (and general) else if ("content".equalsIgnoreCase(imageUri.getScheme())) { // Return the remote address if (isGooglePhotosUri(imageUri)) return imageUri.getLastPathSegment(); return getDataColumn(context, imageUri, null, null); } // File else if ("file".equalsIgnoreCase(imageUri.getScheme())) { return imageUri.getPath(); } return null; } public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) { Cursor cursor = null; String column = MediaStore.Images.Media.DATA; String[] projection = {column}; try { cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null); if (cursor != null && cursor.moveToFirst()) { int index = cursor.getColumnIndexOrThrow(column); return cursor.getString(index); } } finally { if (cursor != null) cursor.close(); } return null; } /** * @param uri The Uri to check. * @return Whether the Uri authority is ExternalStorageProvider. */ public static boolean isExternalStorageDocument(Uri uri) { return "com.android.externalstorage.documents".equals(uri.getAuthority()); } /** * @param uri The Uri to check. * @return Whether the Uri authority is DownloadsProvider. */ public static boolean isDownloadsDocument(Uri uri) { return "com.android.providers.downloads.documents".equals(uri.getAuthority()); } /** * @param uri The Uri to check. * @return Whether the Uri authority is MediaProvider. */ public static boolean isMediaDocument(Uri uri) { return "com.android.providers.media.documents".equals(uri.getAuthority()); } /** * @param uri The Uri to check. * @return Whether the Uri authority is Google Photos. */ public static boolean isGooglePhotosUri(Uri uri) { return "com.google.android.apps.photos.content".equals(uri.getAuthority()); }

 

4.拍照成功獲取url后傳給js

 //此處將拍照或選擇相冊返回的url傳給js mWebView.loadUrl("javascript:acceptUrl('" + url + "')");

 

 

5. js給android傳數據

js只需要調用window.hgj.fnId(received);就可以了。 hgj:是我們之前android和js定的,如mWebView.addJavascriptInterface(new JSInterface(), "hgj");中的最后一個參數 fnId()是方法名,js把參數傳進去,我們android端只要寫好這個方法,直接loadUrl獲取參數就可以了,如wv.loadUrl("javascript:fnId()");

h5頁面: 
這里寫圖片描述

源碼位置:https://download.csdn.net/download/feitailang/10839514
源碼項目截圖: 
這里寫圖片描述


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM