The article directories

    • preface
    • Step1: WebView adds the long press event
    • Step2: Pop up the bottom dialog box for saving the picture
    • Step3: turn the image into a Bitmap
    • Step4: save to album (dynamic permission application)
    • Step5 save the album successfully and notify the system to update the album
    • Step6 perform the callback of dynamic permission application in the Fragment
    • supplement

preface

This paper is based on the implementation of fragment to save H5 images to the local album. Compared with the implementation of Acvitity, trimming is a little complicated, but there is no significant difference in the code

Step1: WebView adds the long press event

private WebView.HitTestResult hitTestResult; . webView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { hitTestResult=webView.getHitTestResult(); / / if the image type or with the type of image links if (hitTestResult. GetType () = = WebView. HitTestResult. IMAGE_TYPE | | hitTestResult. GetType () = = WebView. HitTestResult. SRC_ANCHOR_TYPE) {/ / showBottomDialog pop-up store image dialog box (); return true; } return false; }});Copy the code

Step2: Pop up the bottom dialog box for saving the picture

Private void bottomDialog (){private void bottomDialog (){private void bottomDialog (); View View = view.inflate (context, r.layout. dialog_custom_layout,null); dialog.setContentView(view); Window window = dialog.getWindow(); // Set the pop-up position window.setgravity (Gravity.BOTTOM); / / / / set the popup animation window. SetWindowAnimations (R.s tyle. Main_menu_animStyle); / / Settings dialog window size. SetLayout (ViewGroup. LayoutParams. MATCH_PARENT, ViewGroup. LayoutParams. WRAP_CONTENT); dialog.show(); dialog.findViewById(R.id.tv_take_photo).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialog.dismiss(); picUrl = hitTestResult.getExtra(); @override public void run() {urlToBitMap(picUrl); } }).start(); }}); dialog.findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialog.dismiss(); }}); }Copy the code

Custom popover layout r.layout. dialog_custom_layout is omitted, write not conducive to install force, do not blame

Step3: turn the image into a Bitmap

Private void urlToBitMap(String picUrl) {Bitmap Bitmap =null; try { URL iconUrl=new URL(picUrl); URLConnection connection=iconUrl.openConnection(); HttpURLConnection httpURLConnection= (HttpURLConnection) connection; int length = httpURLConnection.getContentLength(); connection.connect(); inputStream=connection.getInputStream(); bufferedInputStream=new BufferedInputStream(inputStream,length); bitmap=BitmapFactory.decodeStream(bufferedInputStream); bufferedInputStream.close(); inputStream.close(); if (bitmap ! = null){ saveToAlbum(bitmap); }} catch (Exception e) {logutils. e(" save failed :", e.tostring ()); Activity.runonuithread (new Runnable() {@override public void run() {// toast.makeText (context, "save failed ", Toast.LENGTH_SHORT).show(); }}); e.printStackTrace(); }}Copy the code

Step4: save to album (dynamic permission application)

/** * saveToAlbum * @param bitmap */ private void saveToAlbum(bitmap bitmap) {permissions= new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}; If (build.version.sdk_int >= build.version_codes.m){// Mobile system 6.0 (23) above dynamically apply permission int i=ContextCompat.checkSelfPermission(context,permissions[0]); if (i! = PackageManager. PERMISSION_GRANTED) {/ / unauthorized users, Remind authorization ActivityCompat. RequestPermissions ((Activity) context, new String [] {the Manifest. Permission. WRITE_EXTERNAL_STORAGE}, 111);  }else { appDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "kuaizai"); if (! appDir.exists()) { appDir.mkdirs(); }}} else {/ / system under 23 don't need a dynamic authorization appDir = new File (Environment) external.getexternalstoragedirectory () getAbsolutePath (), "kuaizai"); if (! appDir.exists()) { appDir.mkdirs(); } } // savePicture(); String[] str = picUrl.split("/"); String fileName = str[str.length - 1]; if (appDir ! = null){ File file = new File(appDir, fileName); try { fos = new FileOutputStream(file); / / solution to open the sd card 7.0 system could not find the problem if file (Build) VERSION) SDK_INT > = Build. VERSION_CODES. N) {StrictMode. VmPolicy. Builder Builder = new StrictMode.VmPolicy.Builder(); StrictMode.setVmPolicy(builder.build()); } bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos); fos.flush(); fos.close(); onSaveSuccess(file); } catch (final IOException e) { activity.runOnUiThread(new Runnable() { @Override public void run() { Toast.maketext (context, "save failed "+ e.tostring (), toast.length_short).show(); toast.maketext (context," save failed "+ e.tostring (), toast.length_short). Logutils.e (" save failed :", e.tostring ()); }}); e.printStackTrace(); }}else {toast. makeText(context, "Authorization failed!" , Toast.LENGTH_SHORT).show(); }}Copy the code

Step5 save the album successfully and notify the system to update the album

@param file */ private void onSaveSuccess(final file file) {activity.runonuithRead (new Runnable() { @Override public void run() { ~~try { MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), file.getName(), null); } catch (FileNotFoundException e) { e.printStackTrace(); ContentValues values = new ContentValues();} ContentValues = new ContentValues(); values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath()); values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg"); Uri uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); Context. SendBroadcast (new Intent(intent.action_media_scanner_scan_file, uri. fromFile(file))); Toast.maketext (context, "save successful ", toast.length_short).show(); }}); }Copy the code

Step6 perform the callback of dynamic permission application in the Fragment

@Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode){ case 111: if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){ if (grantResults[0] == PackageManager.PERMISSION_GRANTED){ new Thread(new Runnable() { @Override public void run() { urlToBitMap(picUrl); } }).start(); }else {toastutils.showtoast2 (context," User rejected! ); return; } } break; Default: toastutils. showToast2(context," save failed! ") ); }}Copy the code

supplement

Step is above, the picture in the growing according to the identification of the webview H5 album and save to the phone system, and then inform the system update photo album, you just completed on the Android end throughout the whole process, does not need as many colleagues say online need to interact with the front-end alignment and then the method to complete, this option is only on the primary side can perfect solution, And it works on all versions including the Pad. But to also said, if you are in acvitity for the operation, finally you just need to let your acvitity ActivityCompat. OnRequestPermissionsResultCallback interface, Then rewrite onRequestPermissionsResult way to go, remember must implement the interface, or rewrite method is to won’t go, but if in fragments, performed the operation, you will surprise, Fragments of onRequestPermissionsResult callback method still didn’t go, there are two reasons for this, A fragment is you also want to like acvitity ActivityCompat. OnRequestPermissionsResultCallback Interface, as well as your fragments onRequestPermissionsResult callback method by your carrier acvitity to intercept, so want to be in acvitity onRequestPermissionsResult callback methods do a bit in the hands and feet, Let the onRequestPermissionsResult acvitity callback method is passed to the dependent on the current acvitity fragments, nice just the way they are. That is, the following operations:

@Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); List<Fragment> fragments =getSupportFragmentManager().getFragments(); if (fragments == null){ return; } for (Fragment fragment : fragments) { if (fragment ! = null) {/ / call the onRequestPermissionsResult fragments fragment.onRequestPermissionsResult(requestCode,permissions,grantResults); }}}}Copy the code