一些平時(shí)可能會(huì)用到的

一些平時(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);

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末沸柔,一起剝皮案震驚了整個(gè)濱河市循衰,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌褐澎,老刑警劉巖会钝,帶你破解...
    沈念sama閱讀 218,122評(píng)論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異工三,居然都是意外死亡迁酸,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,070評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門俭正,熙熙樓的掌柜王于貴愁眉苦臉地迎上來奸鬓,“玉大人,你說我怎么就攤上這事掸读〈叮” “怎么了?”我有些...
    開封第一講書人閱讀 164,491評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵儿惫,是天一觀的道長澡罚。 經(jīng)常有香客問我,道長肾请,這世上最難降的妖魔是什么始苇? 我笑而不...
    開封第一講書人閱讀 58,636評(píng)論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮筐喳,結(jié)果婚禮上催式,老公的妹妹穿的比我還像新娘。我一直安慰自己避归,他們只是感情好荣月,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,676評(píng)論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著梳毙,像睡著了一般哺窄。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上账锹,一...
    開封第一講書人閱讀 51,541評(píng)論 1 305
  • 那天萌业,我揣著相機(jī)與錄音,去河邊找鬼奸柬。 笑死生年,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的廓奕。 我是一名探鬼主播抱婉,決...
    沈念sama閱讀 40,292評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼桌粉!你這毒婦竟也來了蒸绩?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,211評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤铃肯,失蹤者是張志新(化名)和其女友劉穎患亿,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體押逼,經(jīng)...
    沈念sama閱讀 45,655評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡步藕,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,846評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了宴胧。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片漱抓。...
    茶點(diǎn)故事閱讀 39,965評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖恕齐,靈堂內(nèi)的尸體忽然破棺而出乞娄,到底是詐尸還是另有隱情,我是刑警寧澤显歧,帶...
    沈念sama閱讀 35,684評(píng)論 5 347
  • 正文 年R本政府宣布仪或,位于F島的核電站,受9級(jí)特大地震影響士骤,放射性物質(zhì)發(fā)生泄漏范删。R本人自食惡果不足惜到旦,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,295評(píng)論 3 329
  • 文/蒙蒙 一旨巷、第九天 我趴在偏房一處隱蔽的房頂上張望添忘。 院中可真熱鬧采呐,春花似錦、人聲如沸搁骑。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,894評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽鹃彻。三九已至蛛株,卻和暖如春欢摄,著一層夾襖步出監(jiān)牢的瞬間绿淋,已是汗流浹背殿漠。 一陣腳步聲響...
    開封第一講書人閱讀 33,012評(píng)論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留掀潮,地道東北人薯鼠。 一個(gè)月前我還...
    沈念sama閱讀 48,126評(píng)論 3 370
  • 正文 我出身青樓械蹋,卻偏偏與公主長得像出皇,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子哗戈,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,914評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容

  • ¥開啟¥ 【iAPP實(shí)現(xiàn)進(jìn)入界面執(zhí)行逐一顯】 〖2017-08-25 15:22:14〗 《//首先開一個(gè)線程郊艘,因...
    小菜c閱讀 6,419評(píng)論 0 17
  • 一、Java語言規(guī)范 詳見:Android開發(fā)java編寫規(guī)范 二唯咬、Android資源文件命名與使用 1. 【推薦...
    王朋6閱讀 963評(píng)論 0 0
  • 2017年5月17日 Kylin_Wu 標(biāo)注(★☆)為考綱明確給出考點(diǎn)(必考) 常見手機(jī)系統(tǒng)(★☆) And...
    Azur_wxj閱讀 1,813評(píng)論 0 10
  • 最近逛論壇的時(shí)候纱注,發(fā)現(xiàn)一篇很不錯(cuò)的總結(jié)博客,里面總結(jié)了不少實(shí)用的代碼語法胆胰,摘抄一部分記錄下來狞贱,以備不時(shí)之需。1蜀涨、禁...
    華楠閱讀 527評(píng)論 0 0
  • 本人初學(xué)Android瞎嬉,最近做了一個(gè)實(shí)現(xiàn)安卓簡單音樂播放功能的播放器,收獲不少勉盅,于是便記錄下來自己的思路與知識(shí)總結(jié)...
    落日柳風(fēng)閱讀 19,133評(píng)論 2 41