引入 1 2 3 4 implementation 'com.blankj:utilcode:1.25.9' implementation 'com.blankj:utilcodex:1.25.9'
工具函数采用多种重载方式可以满足不同需求。
Android Activity 启动
1 ActivityUtils.startActivity(Main2Activity.class);
转向桌面
1 ActivityUtils.startHomeActivity();
获取活动
1 2 3 4 5 6 7 List<Activity> activities = ActivityUtils.getActivityList(); Activity activity = ActivityUtils.getTopActivity(); String activity = ActivityUtils.getLauncherActivity(); Activity activity = ActivityUtils.getActivityByView(view); Activity activity = ActivityUtils.getActivityByContext(view.getContext());
结束活动
1 2 3 4 5 6 ActivityUtils.finishActivity(this ); ActivityUtils.finishActivity(Main2Activity.class); ActivityUtils.finishOtherActivities(Main2Activity.class); ActivityUtils.finishAllActivities();
Service 类似
1 ServiceUtils.startService(MyService.class);
Fragment 1 FragmentUtils.add : 新增 fragment
Snackbar 1 2 SnackbarUtils.with(v).setMessage("SnackBar" ).show(); SnackbarUtils.with(v).setMessage("SnackBar" ).showError();
Toast 1 ToastUtils.showShort("Toast" );
SpannableString 1 SpannableStringBuilder builder = SpanUtils.with(textView).setStrikethrough().setFontSize(24 ).append("liuxiang" ).create();
SharedPreferences 1 2 3 4 SPUtils spUtils = SPUtils.getInstance(); spUtils.put("name" , "liuxiang" ); String name = spUtils.getString("name" );
App 安装,启动App
1 2 public static void installApp (final String filePath) ;public static void launchApp (final String packageName)
App 信息
1 String name = AppUtils.getAppName();
状态栏和导航栏 高度和颜色
1 2 3 int statusHeight = BarUtils.getStatusBarHeight();int naviColor = BarUtils.getNavBarColor(getWindow());int actionBarHeight = BarUtils.getActionBarHeight();
判断可见与否
1 boolean isVisible = BarUtils.isStatusBarVisible(this );
改变高度和颜色
1 2 BarUtils.setStatusBarColor(this , 0xff78ff ); public static void setStatusBarColor4Drawer (final DrawerLayout drawer, final View fakeStatusBar, final int color)
权限 所有的危险权限:
申请动态权限的正常逻辑是
1.先检查权限是否已经授权,如果已经授权,即可跳过后面步骤
2.再检查是否要提示UI,一般误操作点击“禁止”按钮后,此检查为真。
3.如果不需要提示UI,或者在提示UI里同意请求权限,则使用 ActivityCompat.requestPermissions。
4.最后在回调,方法里处理权限结果。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (ContextCompat.checkSelfPermission(MainActivity.this , Manifest.permission.READ_EXTERNAL_STORAGE) != PERMISSION_GRANTED) { Log.i("ContextCompat" , "检查权限状态 " ); if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this , Manifest.permission.READ_EXTERNAL_STORAGE)) { Log.i("ContextCompat" , "用户未彻底拒绝授予权限, 一般会提示用户进入设置权限界面 " ); new AlertDialog.Builder(MainActivity.this ) .setTitle("提示" ) .setMessage("应用需要开启拍照的权限,是否继续?" ) .setPositiveButton("确定" , -> { ActivityCompat.requestPermissions(MainActivity.this , new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1 ); }) .setNegativeButton("取消" , -> { } }).show(); } else { Log.i("ContextCompat" , "用户未彻底拒绝授予权限: " ); ActivityCompat.requestPermissions(MainActivity.this , new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1 ); } } } @Override public void onRequestPermissionsResult (int requestCode, String[] permissions, @NonNull int [] grantResults) { if (requestCode == 1 ) { for (int i = 0 ; i < permissions.length; i++) { if (grantResults[i] == PERMISSION_GRANTED) { Log.i("ContextCompat" , "申请成功: " +permissions[0 ]); } else { Log.i("ContextCompat" , "申请失败: " +grantResults[i]+" " +PERMISSION_GRANTED); } } } }
使用 PermissionUtils 可以简略如下,经过封装回调函数,不需要写两遍执行代码,也不需要继承权限回调方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 private void requestRecordAudio () { PermissionUtils.permission(PermissionConstants.STORAGE) .rationale(new PermissionUtils.OnRationaleListener() { @Override public void rationale (final ShouldRequest shouldRequest) { Log.i("ContextCompat" , "rationale: " ); new AlertDialog.Builder(MainActivity.this ) .setTitle("提示" ) .setMessage("应用需要开启拍照的权限,是否继续?" ) .setPositiveButton("确定" , -> { shouldRequest.again(true ); }) .setNegativeButton("取消" , -> { }) .show(); }) .callback(new PermissionUtils.FullCallback() { @Override public void onGranted (List<String> permissionsGranted) { String time = TimeUtils.millis2String(System.currentTimeMillis()); textView.setText(time); Log.i("ContextCompat" , "申请成功: " ); } @Override public void onDenied (List<String> permissionsDeniedForever, List<String> permissionsDenied) { Log.i("ContextCompat" , "申请失败: " ); } }) .request(); }
设备 像素(pt:每英寸像素数)
1 2 int px = AdaptScreenUtils.pt2Px(100 ); int pt = AdaptScreenUtils.px2Pt(100 );
亮度
1 2 int bright = BrightnessUtils.getBrightness();int windowBright = BrightnessUtils.getWindowBrightness(getWindow());
颜色
1 public static int getColor (@ColorRes int id) ;
内存缓存 1 CacheMemoryStaticUtils.setDefaultCacheMemoryUtils(CacheMemoryUtils.getInstance());
读写
1 2 int name = CacheMemoryStaticUtils.get("name" );CacheMemoryStaticUtils.put("name" ,"liuxiang" );
磁盘缓存 创建
1 2 CacheDiskStaticUtils.setDefaultCacheDiskUtils(CacheDiskUtils.getInstance());
写入
1 CacheDiskStaticUtils.put("name" ,"liuxiang" );
读取
1 String name = CacheDiskStaticUtils.getString("name" );
Clean 1 2 3 4 5 CleanUtils.cleanInternalCache(); CleanUtils.cleanExternalCache(); CleanUtils.cleanInternalDbs(); CleanUtils.cleanInternalSp(); CleanUtils.cleanCustomDir(File);
键盘 1 KeyboardUtils.showSoftInput(MainActivity.this );
震动 1 VibrateUtils.vibrate(2000 );
Java 数组 创建各种类型数组
1 2 3 4 int [] nums = ArrayUtils.newIntArray(1 ,2 ,3 ,4 );char [] chars = ArrayUtils.newCharArray('a' ,'b' ,'c' ,'d' );Character[] chars = ArrayUtils.newArray('a' ,'b' ,'c' ,'d' );
检空和长度
1 2 3 4 5 boolean isEmpty = ArrayUtils.isEmpty(chars);int len = ArrayUtils.getLength(chars);boolean isSameLength = ArrayUtils.isSameLength(nums, chars);boolean isSameLength = ArrayUtils.equals(nums_1, nums_2);
排序和逆序
1 2 ArrayUtils.sort(nums); ArrayUtils.reverse(chars);
取值和写入
1 2 3 4 5 int num = (int ) ArrayUtils.get(nums, 3 );ArrayUtils.set(nums, 3 , 13 ); ArrayUtils.add(nums_1, nums_2); ArrayUtils.subArray(nums_1, 2 , 4 );
字符串 检空
1 2 3 boolean isEmpty = StringUtils.isEmpty("" );boolean isTrim = StringUtils.isEmpty("" );boolean isSpace = StringUtils.isSpace("" );
空转0
1 2 String nul = null ; String zeroLen = StringUtils.null2Length0(nul);
判等
1 2 boolean isEqual = StringUtils.equals(s1, s2);boolean isEqual = StringUtils.equalsIgnoreCase(s1, s2);
文件 读写
1 2 String file2String = FileIOUtils.readFile2String("filepath" ); List<String> file2List = FileIOUtils.readFile2List("filepath" );
相关操作
1 2 public static File getFileByPath (final String filePath) ;public static boolean isFileExists (final String filePath) ;
URI 1 2 Uri uri = UriUtils.file2Uri(file); File file = UriUtils.uri2File(uri);
路径 1 String esp = PathUtils.getExternalStoragePath();
时间 1 String time = TimeUtils.millis2String(System.currentTimeMillis());
图片 1 Bitmap des = ImageUtils.toRound(bitmapSrc);
总线 注册
1 2 public static void register (final Object bus) ;public static void unregister (final Object bus) ;
发送
1 public static void post (final String tag) ;