一些平時(shí)可能會(huì)用到的部宿,不定期更新
-
判斷sdk版本大于6.0
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){}
-
請(qǐng)求運(yùn)行時(shí)權(quán)限
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 { //已經(jīng)擁有權(quán)限 } }
-
根據(jù)包名打開相關(guān)的app
Intent intentForPackage = getPackageManager().getLaunchIntentForPackage("yourAppPackageName"); startActivity(intentForPackage);
-
根據(jù)包名和Activity名稱打開對(duì)應(yīng)的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); }
-
獲取屏幕相關(guān)信息
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 = "機(jī)頂盒型號(hào): " + android.os.Build.MODEL + "," + "\nSDK版本:" + android.os.Build.VERSION.SDK + "," + "\n系統(tǒng)版本:"+ android.os.Build.VERSION.RELEASE + "\n屏幕寬度(像素): " + width + "\n屏幕高度(像素): " + height + "\n屏幕密度比: " + density + "\n屏幕密度DPI: " + densityDpi; Log.d("System INFO", info); }
-
獲取所有存儲(chǔ)卡和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"},//數(shù)組里邊更改想要查詢的后綴名 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權(quán)限
/** * 靜默安裝,通過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; }
-
連續(xù)點(diǎn)擊五次出現(xiàn)當(dāng)前版本號(hào)
能夠?qū)崿F(xiàn)n此事件的點(diǎn)擊,只需將數(shù)組長度定義為n個(gè)長度村怪。long[] mHits = new long[5]; private View.OnClickListener mShowVersionCodeListener = new View.OnClickListener() { @Override public void onClick(View v) { //每點(diǎn)擊一次 實(shí)現(xiàn)左移一格數(shù)據(jù) System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1); //給數(shù)組的最后賦當(dāng)前時(shí)鐘值 mHits[mHits.length - 1] = SystemClock.uptimeMillis(); //當(dāng)0出的值大于當(dāng)前時(shí)間-500時(shí) 證明在500秒內(nèi)點(diǎn)擊了2次 if(mHits[0] > SystemClock.uptimeMillis() - 2000){ ToastUtils.showLong("當(dāng)前版本:"+AppUtils.getAppVersionCode()); } } };
-
發(fā)送廣播讓Android系統(tǒng)將新加的圖片加入圖片庫
private void sendImageAddBroadcast() { //imageFileList 文件的集合 if (imageFileList != null) { for (int i = 0; i < imageFileList.size(); i++) { // 其次把文件插入到系統(tǒng)圖庫 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轉(zhuǎn)換為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是個(gè)資源文件
Resources res = getResources();
Bitmap bmp = BitmapFactory.decodeResource(res, R.drawable.pic);
-
將bitmap轉(zhuǎn)換為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; }
-
動(dòng)態(tài)用代碼改變圖片的顏色(圖片必須為單一顏色,不需要改變的地方為透明色)
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 后兩位小數(shù)
DecimalFormat decimalFormat=new DecimalFormat(".00");//構(gòu)造方法的字符格式這里如果小數(shù)不足2位,會(huì)以0補(bǔ)足.
String format = decimalFormat.format(rate);
Android 7.0(Nougat,牛軋?zhí)牵╅_始浮庐,Android更改了對(duì)用戶安裝證書的默認(rèn)信任行為甚负,應(yīng)用程序「只信任系統(tǒng)級(jí)別的CA」。
對(duì)此兔辅,如果是自己寫的APP想抓HTTPS的包腊敲,可以在 res/xml目錄下新建一個(gè)network_security_config.xml 文件,復(fù)制粘貼如下內(nèi)容:
<base-config cleartextTrafficPermitted="true">
<trust-anchors>
<certificates src="system" overridePins="true" /> <!--信任系統(tǒng)證書-->
<certificates src="user" overridePins="true" /> <!--信任用戶證書-->
</trust-anchors>
</base-config>
</network-security-config>
復(fù)制代碼接著AndroidManifest.xml文件中新增networkSecurityConfig屬性引用xml文件维苔,如下:
<?xml version="1.0" encoding="utf-8"?>
<manifest ... >
<application android:networkSecurityConfig="@xml/network_security_config"
... >
...
</application>
</manifest>
復(fù)制代碼調(diào)試期為了方便自己抓包可以加上碰辅,發(fā)版本的時(shí)候,記得刪掉哦=槭薄C槐觥!
調(diào)取相機(jī)拍照,并獲取照片路徑
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);