“This is the second day of my participation in the Gwen Challenge in November. See details: The Last Gwen Challenge in 2021”

1 Adding Permission

Private void checkNeedPermissions(){if (build.version.sdk_int >= build.version_codes.m){ ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) ! = PackageManager. PERMISSION_GRANTED) {/ / permissions apply ActivityCompat. RequestPermissions (this, new String[]{ Manifest.permission.WRITE_EXTERNAL_STORAGE, }, 1); }}} /** * @param requestCode * @param permissions * @param grantResults */ @override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == 1) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (grantResults[0] ! = PackageManager. PERMISSION_GRANTED) {/ / if there is no access permissions, You can prompt the user to set the interface - > application permission to open the permissions Boolean b = shouldShowRequestPermissionRationale (permissions [0]). // Used to be! If b (b) {/ / users want to use my APP / / prompt the user to apply Settings interface manually open access showDialogTipUserGoToAppSettting (); } else{// toast.maketext (mainactivity.this," You are blocking access to the media database, if you want to use this function, please turn it on in the Settings ", toast.length_short).show(); //finish(); MakeText (this, "toast.length_long ", toast.length_long); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); }}}} / * * * prompt the user to apply Settings manually open access interface * / private void showDialogTipUserGoToAppSettting () {AlertDialog dialog = new Alertdialog.builder (this).setTitle(" Storage permissions not available ").setMessage(" Apply Settings - Permissions -, Allows applications to use storage permissions to save user data. "). SetPositiveButton (" Enable now ", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, Int which) {// Jump to goToAppSetting(); }}). SetNegativeButton (" Cancel ", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // finish(); } }).setCancelable(false).show(); } private void goToAppSetting() {Intent Intent = new Intent(); intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); Uri uri = Uri.fromParts("package", getPackageName(), null); intent.setData(uri); startActivityForResult(intent, 123); }Copy the code

Bety []

2.1 Transferring local Resource Images to Bety []

* Read local files, Conversion to a byte array * @param URL Local file path * @Return * @throws IOException */ private byte[] getImage(String URL) throws IOException{ BufferedInputStream in = new BufferedInputStream(new FileInputStream(url)); ByteArrayOutputStream out = new ByteArrayOutputStream(1024); byte[] temp = new byte[2048]; int size = 0; while ((size = in.read(temp)) ! = -1) { out.write(temp, 0, size); } in.close(); byte[] content = out.toByteArray(); return content; }Copy the code

2.2 Transferring network Resource images to Bety []

* Obtain file stream * @param URL * @return * @throws IOException */ private static byte[] getFile(String URL) throws IOException{ URL urlConet = new URL(url); HttpURLConnection con = (HttpURLConnection)urlConet.openConnection(); con.setRequestMethod("GET"); con.setConnectTimeout(4 * 1000); InputStream inStream = con .getInputStream(); ByteArrayOutputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[2048]; int len = 0; while( (len=inStream.read(buffer)) ! = -1 ){ outStream.write(buffer, 0, len); } inStream.close(); byte[] data = outStream.toByteArray(); return data; }Copy the code

Write system gallery, update to album

/** * Save the image to the specified path * @param context * @param *bitmap the image to save * @param fileName custom image name */ public void saveImageToGallery( Context context, byte[] data, String fileName) { Bitmap bitmap = BitmapFactory.decodeByteArray(data,0,data.length); DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss"); fileName = fileName + format.format(new Date())+".JPEG"; // Save the image to the specified path String storePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath()+"LS" ; File appDir = new File(storePath); if (! appDir.exists()) { appDir.mkdir(); } File file = new File(appDir, fileName); try { FileOutputStream fos = new FileOutputStream(file); / / IO flow ways to save the file compression (80 on behalf of the compressed 20%) Boolean isSuccess = bitmap.com press (bitmap.com pressFormat. JPEG, 80, fos); fos.flush(); fos.close(); / / the second file is inserted into the system gallery try {MediaStore. Images. Media. InsertImage (context. GetContentResolver (), the file. The getAbsolutePath (), fileName, null); } catch (FileNotFoundException e) { e.printStackTrace(); } system.out.println (" system.out.println "); Uri uri = Uri.fromFile(file); context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri)); Toast toast=; If (isSuccess) {toast.maketext (context," image saved to "+file, toast.length_short).show()} else {Toast Toast.maketext (context," failed to save image ", toast.length_short).show(); } } catch (IOException e) { e.printStackTrace(); }}}Copy the code