一些平时可能会用到的,不定期更新
-
判断sdk版本大于6.0
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){}
-
请求运行时权限
private void requestPermission() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1001); } else { //已经拥有权限 } }
-
根据包名打开相关的app
Intent intentForPackage = getPackageManager().getLaunchIntentForPackage("yourAppPackageName"); startActivity(intentForPackage);
-
根据包名和Activity名称打开对应的Activity
Intent intent = new Intent(); intent.setClassName("com.rk_itvui.settings", "com.rk_itvui.settings.network_settingnew");
-
获取定位城市
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); Location location = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); double latitude = location.getLatitude(); double longitude = location.getLongitude(); Geocoder ge = new Geocoder(this); addList = ge.getFromLocation(latitude, longitude, 1); Address ad = addList.get(i); //国家和城市 String s = ad.getCountryName() + ";" + ad.getLocality() +";" + ad.getSubLocality();
-
模拟键盘输入
instrumentation = new Instrumentation(); int keycode = 7; instrumentation.sendKeyDownUpSync(keycode);
-
隐藏底部NavigationBar
private void hideNavicationView() { WindowManager.LayoutParams params = getWindow().getAttributes(); params.systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE; getWindow().setAttributes(params); }
-
获取屏幕相关信息
private void getDisplayMetrics() { DisplayMetrics metric = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metric); // 屏幕宽度(像素) int width = metric.widthPixels; // 屏幕高度(像素) int height = metric.heightPixels; // 屏幕密度比(1.0 / 1.5 / 2.0) float density = metric.density; // 屏幕密度DPI(160 / 240 / 320) int densityDpi = metric.densityDpi; String info = "机顶盒型号: " + android.os.Build.MODEL + "," + "\nSDK版本:" + android.os.Build.VERSION.SDK + "," + "\n系统版本:"+ android.os.Build.VERSION.RELEASE + "\n屏幕宽度(像素): " + width + "\n屏幕高度(像素): " + height + "\n屏幕密度比: " + density + "\n屏幕密度DPI: " + densityDpi; Log.d("System INFO", info); }
-
获取所有存储卡和u盘的目录
private void getStroage(){ String[] result = null; StorageManager storageManager = (StorageManager)getSystemService(Context.STORAGE_SERVICE); try { Method method = StorageManager.class.getMethod("getVolumePaths"); method.setAccessible(true); try { result =(String[])method.invoke(storageManager); } catch (InvocationTargetException e) { e.printStackTrace(); } for (int i = 0; i < result.length; i++) { Log.d(this.getClass().getSimpleName(), "getStroage: " + result[i] + "\n"); System.out.println("path----> " + result[i]+"\n"); } } catch (Exception e) { e.printStackTrace(); } }
-
Android查询指定后缀名的文件
/** * 查询SD卡里所有pdf文件pdf可以替换 */ private void queryFiles() { String[] projection = new String[]{MediaStore.Files.FileColumns._ID, MediaStore.Files.FileColumns.DATA, MediaStore.Files.FileColumns.SIZE }; Cursor cursor = getContentResolver().query( Uri.parse("content://media/external/file"), projection, MediaStore.Files.FileColumns.DATA + " like ?", new String[]{"%.pdf"},//数组里边更改想要查询的后缀名 null); if (cursor != null) { while (cursor.moveToNext()) { int idindex = cursor .getColumnIndex(MediaStore.Files.FileColumns._ID); int dataindex = cursor .getColumnIndex(MediaStore.Files.FileColumns.DATA); int sizeindex = cursor .getColumnIndex(MediaStore.Files.FileColumns.SIZE); String id = cursor.getString(idindex); String path = cursor.getString(dataindex); String size = cursor.getString(sizeindex); Log.d(TAG, "id = " + id + "\n" + "路径 = " + path + "\n" + "size = " + size); } cursor.close(); }
-
将view保存为bitmap
private Bitmap createBitmapFromView(View view) { Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.RGB_565); Canvas canvas = new Canvas(bitmap); view.layout(view.getLeft(), view.getTop(), view.getRight(), view.getBottom()); // Draw background Drawable bgDrawable = view.getBackground(); if (bgDrawable != null) { bgDrawable.draw(canvas); } else { canvas.drawColor(Color.WHITE); } // Draw view to canvas view.draw(canvas); return bitmap; }
-
静默安装,需要root权限
/** * 静默安装,通过PM命令 * * @param apkFilePath apk文件路径 * @return true表示安装成功,否则返回false */ public static boolean silentInstall(String apkFilePath) { boolean isInstallOk = false; if (isSupportSilentInstall()) { DataOutputStream dataOutputStream = null; BufferedReader bufferedReader = null; try { Process process = Runtime.getRuntime().exec("su"); dataOutputStream = new DataOutputStream(process.getOutputStream()); String command = "pm install -r " + apkFilePath + "\n"; dataOutputStream.write(command.getBytes(Charset.forName("utf-8"))); dataOutputStream.flush(); dataOutputStream.writeBytes("exit\n"); dataOutputStream.flush(); process.waitFor(); bufferedReader = new BufferedReader(new InputStreamReader(process.getErrorStream())); StringBuilder msg = new StringBuilder(); String line; while ((line = bufferedReader.readLine()) != null) { msg.append(line); } if (msg.toString().contains("Success")) { isInstallOk = true; } } catch (Exception e) { e.printStackTrace(); } finally { if (dataOutputStream != null) { try { dataOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (bufferedReader != null) { try { bufferedReader.close(); } catch (IOException e) { e.printStackTrace(); } } } } return isInstallOk; }
-
连续点击五次出现当前版本号
能够实现n此事件的点击,只需将数组长度定义为n个长度。long[] mHits = new long[5]; private View.OnClickListener mShowVersionCodeListener = new View.OnClickListener() { @Override public void onClick(View v) { //每点击一次 实现左移一格数据 System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1); //给数组的最后赋当前时钟值 mHits[mHits.length - 1] = SystemClock.uptimeMillis(); //当0出的值大于当前时间-500时 证明在500秒内点击了2次 if(mHits[0] > SystemClock.uptimeMillis() - 2000){ ToastUtils.showLong("当前版本:"+AppUtils.getAppVersionCode()); } } };
-
发送广播让Android系统将新加的图片加入图片库
private void sendImageAddBroadcast() { //imageFileList 文件的集合 if (imageFileList != null) { for (int i = 0; i < imageFileList.size(); i++) { // 其次把文件插入到系统图库 File file = imageFileList.get(i); try { MediaStore.Images.Media.insertImage(mContext.getContentResolver(), file.getAbsolutePath(), file.getName(), null); } catch (FileNotFoundException e) { e.printStackTrace(); } // 最后通知图库更新 mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getPath()))); } } }
-
将drawable转换为bitmap
public static Bitmap drawable2Bitmap(Drawable drawable) { if (drawable instanceof BitmapDrawable) { return ((BitmapDrawable) drawable).getBitmap(); } else if (drawable instanceof NinePatchDrawable) { Bitmap bitmap = Bitmap .createBitmap( drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()); drawable.draw(canvas); return bitmap; } else { return null; } }
或者drawable是个资源文件
Resources res = getResources();
Bitmap bmp = BitmapFactory.decodeResource(res, R.drawable.pic);
-
将bitmap转换为drawable
public static Drawable bitmap2Drawable(Bitmap bitmap) { return new BitmapDrawable(bitmap); }
-
获取apk文件的icon
public static Drawable getApkIcon(Context context, String apkPath) { PackageManager pm = context.getPackageManager(); PackageInfo info = pm.getPackageArchiveInfo(apkPath, PackageManager.GET_ACTIVITIES); if (info != null) { ApplicationInfo appInfo = info.applicationInfo; appInfo.sourceDir = apkPath; appInfo.publicSourceDir = apkPath; try { return appInfo.loadIcon(pm); } catch (OutOfMemoryError e) { Log.e("ApkIconLoader", e.toString()); } } return null; }
-
动态用代码改变图片的颜色(图片必须为单一颜色,不需要改变的地方为透明色)
private Drawable getTintDrawable(Context context, @DrawableRes int image, int color) { Drawable drawable = ContextCompat.getDrawable(context, image); Drawable.ConstantState constantState = drawable.getConstantState(); Drawable newDrawable = DrawableCompat.wrap(constantState == null ? drawable : constantState.newDrawable()).mutate(); DrawableCompat.setTint(newDrawable, color); return newDrawable; }
保留float 后两位小数
DecimalFormat decimalFormat=new DecimalFormat(".00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
String format = decimalFormat.format(rate);
Android 7.0(Nougat,牛轧糖)开始,Android更改了对用户安装证书的默认信任行为,应用程序「只信任系统级别的CA」。
对此,如果是自己写的APP想抓HTTPS的包,可以在 res/xml目录下新建一个network_security_config.xml 文件,复制粘贴如下内容:
<base-config cleartextTrafficPermitted="true">
<trust-anchors>
<certificates src="system" overridePins="true" /> <!--信任系统证书-->
<certificates src="user" overridePins="true" /> <!--信任用户证书-->
</trust-anchors>
</base-config>
</network-security-config>
复制代码接着AndroidManifest.xml文件中新增networkSecurityConfig属性引用xml文件,如下:
<?xml version="1.0" encoding="utf-8"?>
<manifest ... >
<application android:networkSecurityConfig="@xml/network_security_config"
... >
...
</application>
</manifest>
复制代码调试期为了方便自己抓包可以加上,发版本的时候,记得删掉哦!!!
调取相机拍照,并获取照片路径
SPUtils.getInstance().put("path",mFilePath);
File outFile = new File(mFilePath);
Uri uri = FileProvider.getUriForFile(
SavePunchAvatarActivity.this,
"com.jy.feng.fileProvider",
outFile);
//拍照
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(intent, REQUEST_CODE);