Bootstrap

Android 日常使用整理

1.打开APP的权限设置页面

Uri uri = Uri.parse("package:" + "包名");
Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, uri);
startActivityForResult(intent, 100);

2.打开设置页面的所有APP列表

Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
startActivityForResult(intent, 100);

3.拨打电话

 Intent intent = new Intent(Intent.ACTION_CALL); //直接拨打电话
   Intent intent = new Intent(Intent.ACTION_DIAL);// 跳转到拨号界面
   Uri data = Uri.parse("tel:" + phoneNum);
   intent.setData(data);
   startActivity(intent);

4.本地安装apk

    Intent intent = new Intent(Intent.ACTION_VIEW);
       intent.addCategory(Intent.CATEGORY_DEFAULT);
       intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
       Uri contentUri;
       if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // 需要配置FileProvider
           intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
           contentUri = FileProvider.getUriForFile(
                   activity.getApplicationContext(), activity.getPackageName() + ".provider", apkFile);
       } else {
           contentUri = Uri.fromFile(apkFile);
       }
       intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
       activity.startActivity(intent);

5.打开系统照相机的方法

需要配置FileProvider,读写权限,相机权限
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri imageUri = null;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
       imageUri = Uri.fromFile(new File(path));
} else {
      intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        imageUri = FileProvider.getUriForFile(context, context.getPackageName() + ".provider", new File(path));
 }
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, requestcode);

5.打开系统相册

第一种方法:
     Intent intent = new Intent();
     intent.setType("image/*");
     intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
     startActivityForResult(intent, 1);
     
第二种方法:
      Intent intent = new Intent();
      intent.setType("image/*");
      intent.setAction(Intent.ACTION_GET_CONTENT);
      startActivityForResult(intent, 1);
  
第三种方法:
       Intent intent = new Intent(Intent.ACTION_PICK);
       intent.setType("image/*");
       startActivityForResult(intent, 1);
第四种方法: 
       Intent intent  = new Intent(Intent.ACTION_PICK,
               android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
       startActivityForResult(intent , 1);      
     
// 获取图片      
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(data != null){
            Uri selectedImageUri = data.getData();
            imgageview.setImageURI(selectedImageUri);
        }
    }

6.图片一般处理

    /**
     * 图片质量压缩
     * @param maxFileSize : 图片最大值
     */
    private static Bitmap  compressQuality(Bitmap bitmap, int maxFileSize) {
        if (bitmap == null) {
            return null;
        }
        String mSrcSize = bitmap.getByteCount() / 1024 + "kb";
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        int quality = 100;
        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, bos);
        while (bos.toByteArray().length > maxFileSize) {
            bos.reset();
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, bos);
            if (quality > 5) {
                if (bos.toByteArray().length > (maxFileSize * 2)) {
                    quality -= 10;
                } else {
                    quality -= 5;
                }
            } else {
                break;
            }
        }
        byte[] bytes = bos.toByteArray();
        Bitmap bitmapCompress = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
        return bitmapCompress ;
    }

    /**
     * 图片像素压缩
     */
  public Bitmap compressImage(String imagePath) {
        Bitmap bitmap;
        // 先算出图片的高宽
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(imagePath, options);
        // 缩放到最高500像素
        int compress = 500int be = 1;
        if (options.outHeight > options.outWidth) {
            be = (int) (options.outHeight / (float) compress );
        } else {
            be = (int) (options.outWidth / (float) compress );
        }
        if (be <= 0)
            be = 1;
        options.inSampleSize = be;
        options.inJustDecodeBounds = false;
        bitmap = BitmapFactory.decodeFile(imagePath, options);
        return bitmap;
    }
    /**
     * 判断照片角度
     */
    public static int getBitmapDegree(String path) {
        int degree = 0;

        ExifInterface exifInterface = null;
        try {
            exifInterface = new ExifInterface(path);
        } catch (IOException e) {
            e.printStackTrace();
            return degree;
        }

        int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);

        switch (orientation) {

            case ExifInterface.ORIENTATION_ROTATE_90:
                degree = 90;
                break;

            case ExifInterface.ORIENTATION_ROTATE_180:
                degree = 180;
                break;

            case ExifInterface.ORIENTATION_ROTATE_270:
                degree = 270;
                break;
        }
        return degree;
    }

    /**
     * 旋转照片
     * @param degress : 图片需要纠正角度
     */
    public static Bitmap rotateBitmap(Bitmap bitmap, int degress) {
        if (bitmap != null) {
            Matrix m = new Matrix();
            m.postRotate(degress);
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                    bitmap.getHeight(), m, true);
            return bitmap;
        }
        return bitmap;
    }

6.view的一般处理

     /**
     * 给view设置左边或右边图标
     *
     * @param view    要设置的view TextView 和 EditText
     * @param resId   图标id
     * @param isRight
     */
    public static void setViewDrawables(View view, int resId, boolean isRight) {
        Drawable drawable = view.getContext().getResources().getDrawable(resId);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(),
                drawable.getMinimumHeight());
        if (view instanceof TextView) {
            if (isRight) {
                ((TextView) view).setCompoundDrawables(null, null, drawable, null);
            } else {
                ((TextView) view).setCompoundDrawables(drawable, null, null, null);
            }
        } else if (view instanceof EditText) {
            if (isRight) {
                ((EditText) view).setCompoundDrawables(null, null, drawable, null);
            } else {
                ((EditText) view).setCompoundDrawables(drawable, null, null, null);
            }
        }
    }

7.文件的处理

  • 文件创建
  // 创建文件:
    public static File createFile(String dir, String name) {
        try {
            File file = new File(dir , name);
            if (file.exists()) {
                return file;
            }
            file.createNewFile();
            return file;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
  // 创建文件夹:
   public static File createDir(String dirName) {
        File dir = new File(dirName);
        if (dir.exists() || dir.mkdir() || dir.mkdirs()){
            return dir;
        }
        return null;
    }
  • 读文件
	//获取文件后缀名 
    public static String getFileSuffix(String filePath) {
        return filePath.substring(filePath.lastIndexOf("/") + 1);
    }
    /**
     * 读取一个文本文件的内容
     */
    public static String readTextFile(File file) throws IOException {

        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(new FileInputStream(file), "UTF-8"));
        StringBuffer sb = new StringBuffer();
        String line;
        if (bufferedReader != null) {
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
            }
            bufferedReader.close();
        }
        return sb.toString();
    }
    public static String formetFileSize(File file) {
		long fileS = file.length();
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        String wrongSize = "0B";
        if (fileS == 0) {
            return wrongSize;
        }
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "KB";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "MB";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "GB";
        }
        return fileSizeString;
    }
  • 写文件
    /**
     * 保存图片到本地
     * @param sdkPath  sdk的目录
     * @param fileName 文件名
     */
    public static void saveBitmap(Bitmap bitmap, String sdkPath, String fileName) {
        try {
            File dirFile = new File(sdkPath);
            if (!dirFile.exists()) {
                dirFile.mkdirs();
            }
            File file = new File(sdkPath, fileName);
            FileOutputStream fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 保存文件
     */
    public static boolean saveToFile(String sFile, String info) {

        boolean Result = false;
        File file = new File(sFile);   //创建sFile这个目录
        if(file.exists() && file.length() > 10){
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        FileOutputStream fos;  //创建创建字节输出流对象
        try {
            fos = new FileOutputStream(file);
            try {
                if (info != null && info.length() > 0)
                    fos.write(info.getBytes(StandardCharsets.UTF_8));
                fos.close();
                Result = true;
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        return Result;
    }
  • 删除文件
// 删除单个文件
   public static boolean deleteFile(String filePath) {
        File file = new File(filePath);
        if (file.isFile() && file.exists()) {
            return file.delete();
        }
        return true;
    }
    /**
     * 删除目录(文件夹)以及目录下的文件
     *
     * @param fileDir被删除目录的文件路径
     * @return 目录删除成功返回true,否则返回false
     */
    public static boolean deleteDirectory(String fileDir) {
        //如果fileDir不以文件分隔符结尾,自动添加文件分隔符
        if (!fileDir.endsWith(File.separator)) {
            fileDir += File.separator;
        }
        File dirFile = new File(fileDir);
        //如果dir对应的文件不存在,或者不是一个目录,则退出
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            return true;
        }
        boolean flag = true;
        //删除文件夹下的所有文件(包括子目录)
        File[] files = dirFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            //删除子文件
            if (files[i].isFile()) {
                flag = deleteFile(files[i].getAbsolutePath());
                if (!flag) {
                    break;
                }
            } else {//删除子目录
                flag = deleteDirectory(files[i].getAbsolutePath());
                if (!flag) {
                    break;
                }
            }
        }
        if (!flag) {
            return false;
        }
        return dirFile.delete();
    }

悦读

道可道,非常道;名可名,非常名。 无名,天地之始,有名,万物之母。 故常无欲,以观其妙,常有欲,以观其徼。 此两者,同出而异名,同谓之玄,玄之又玄,众妙之门。

;