Android 開發小知識點收集(隨時更新)

1、獲取手機運行時最大可占用內存

int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
Log.d("TAG", "Max memory is " + maxMemory + "KB");

2、改變dialog 在不同窗口內顯示不同的大小

//在dialog.show()之后調用
public static void setDialogWindowAttr(Dialog dlg,Context ctx){
        Window window = dlg.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.gravity = Gravity.CENTER;
        lp.width = LayoutParams.MATH_PARENT;//寬高可設置具體大小
        lp.height = LayoutParams.MATH_PARENT;
        dlg.getWindow().setAttributes(lp);
    }

摘抄自:簡書——MrRock

3、監聽Activity是否顯示在用戶面前

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    // TODO Auto-generated method stub
    super.onWindowFocusChanged(hasFocus);
}

當Activity展示咋用戶面前則 hasFocus 為 true;

4、成員變量與局部變量的區別(簡寫:成、局)

1)、類中位置不同:成:類內 局: 方法內伙子方法上;
2)、內存中位置不同:成:棧內存 局:堆內存;
3)、生命周期不同:成:與對象共存亡 局:與方法共存亡;
4)、初始化值不同:成:有默認值 局:無默認值,必須賦值。

5、Java 獲取可變的 uuid

uuid 類似于時間戳 永遠不可重復。

  String uuid = UUID.randomUUID().toString().replaceAll("-", "");

6、Android 獲取 WiFi 的 ssid

1)、在 AndroidManifest.xml 文件內添加權限

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>

2)、需要獲取的位置添加如下代碼

WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();

Logger.d("wifiInfo"+wifiInfo.toString());
Logger.d("SSID"+wifiInfo.getSSID());

3)、若不是想獲取當前連接,而是想獲取WIFI設置中的連接

WifiManager.getConfiguredNetworks()

4)、若獲取更多的信息請查看這位兄嘚的博客:Android連續獲取當前所連接WiFi及周圍熱點列表信息的解決方案 .

7、Android 打開 WiFi 設置界面

1)、判斷手機是否連接wifi


        if (ConnectionDetector.getConnectionType(this) != ConnectionDetector.WIFI) {
             //跳轉wifi配置界面
            goToWifSetting();
        } else {
                //wifi已經連接
        }

代碼如下:

Intent intent = new Intent();
if(android.os.Build.VERSION.SDK_INT >= 11){
    //Honeycomb
    intent .setClassName("com.android.settings", "com.android.settings.Settings$WifiSettingsActivity");
 }else{
    //other versions
     intent .setClassName("com.android.settings", "com.android.settings.wifi.WifiSettings");
 }
 startActivity(intent);

或者

  if (android.os.Build.VERSION.SDK_INT > 10) {
          // 3.0以上打開設置界面,也可以直接用ACTION_WIRELESS_SETTINGS打開到wifi界面
             startActivity(new Intent(android.provider.Settings.ACTION_SETTINGS));
} else {
             startActivity(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS));
}

8、Android 8.0 獲取 wifi 的 ssid

之前用上面6的方法可以完美的獲取wifif設備的 ssid 但是不能顯示 ssid 即用戶名

ConnectivityManager manager = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
assert manager != null;
NetworkInfo info = manager.getActiveNetworkInfo();
if (info != null && info.isConnected()) {
    String  wifiSsid = info.getExtraInfo().substring(1, info.getExtraInfo().length() - 1).trim();
}

9、判斷字符串是否為純數字串

  //判斷字符串是不是純數字
        String str = "1234567a";

        char[] a = str.toCharArray();
        for (char c : a) {
            if (Character.isDigit(c)) {
                ToastUtils.showToast(mContext, "輸入的內容包含非法字符");
            }
        }

10、獲取任意區間的隨機數

    int nom = (int) (Math.random() * (endNum - startNum + 1) + startNum);

11、以當前日期為基準向前推算到某天

 //以當天時間為基準向前推幾日到某天
    public static String getPastDate(int past) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - past);
        Date today = calendar.getTime();
        @SuppressLint("SimpleDateFormat") SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(today);
    }

12、關于 Android 的 Uri、path、file 的轉換

Uri--->file

 File file = null;
            try {
                file = new File(new URI(uri.toString()));
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }

file--->Uri

URI uri = file.toURI();

file--->path

String path = file.getPath()

path--->file

Uri uri = Uri.parse(path);

path--->file

File file = new File(path)

Uri--->path

  /**
     * 根據Uri獲取圖片的絕對路徑
     *
     * @param context 上下文對象
     * @param uri     圖片的Uri
     * @return 如果Uri對應的圖片存在, 那么返回該圖片的絕對路徑, 否則返回null
     */
    public static String getRealPathFromUri(Context context, Uri uri) {
        int sdkVersion = Build.VERSION.SDK_INT;
        if (sdkVersion >= 19) { // api >= 19
            return getRealPathFromUriAboveApi19(context, uri);
        } else { // api < 19
            return getRealPathFromUriBelowAPI19(context, uri);
        }
    }

    /**
     * 適配api19以下(不包括api19),根據uri獲取圖片的絕對路徑
     *
     * @param context 上下文對象
     * @param uri     圖片的Uri
     * @return 如果Uri對應的圖片存在, 那么返回該圖片的絕對路徑, 否則返回null
     */
    private static String getRealPathFromUriBelowAPI19(Context context, Uri uri) {
        return getDataColumn(context, uri, null, null);
    }

    /**
     * 適配api19及以上,根據uri獲取圖片的絕對路徑
     *
     * @param context 上下文對象
     * @param uri     圖片的Uri
     * @return 如果Uri對應的圖片存在, 那么返回該圖片的絕對路徑, 否則返回null
     */
    @SuppressLint("NewApi")
    private static String getRealPathFromUriAboveApi19(Context context, Uri uri) {
        String filePath = null;
        if (DocumentsContract.isDocumentUri(context, uri)) {
            // 如果是document類型的 uri, 則通過document id來進行處理
            String documentId = DocumentsContract.getDocumentId(uri);
            if (isMediaDocument(uri)) { // MediaProvider
                // 使用':'分割
                String id = documentId.split(":")[1];

                String selection = MediaStore.Images.Media._ID + "=?";
                String[] selectionArgs = {id};
                filePath = getDataColumn(context, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection, selectionArgs);
            } else if (isDownloadsDocument(uri)) { // DownloadsProvider
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(documentId));
                filePath = getDataColumn(context, contentUri, null, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            // 如果是 content 類型的 Uri
            filePath = getDataColumn(context, uri, null, null);
        } else if ("file".equals(uri.getScheme())) {
            // 如果是 file 類型的 Uri,直接獲取圖片對應的路徑
            filePath = uri.getPath();
        }
        return filePath;
    }

    /**
     * 獲取數據庫表中的 _data 列,即返回Uri對應的文件路徑
     *
     */
    private static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        String path = null;

        String[] projection = new String[]{MediaStore.Images.Media.DATA};
        Cursor cursor = null;
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                int columnIndex = cursor.getColumnIndexOrThrow(projection[0]);
                path = cursor.getString(columnIndex);
            }
        } catch (Exception e) {
            if (cursor != null) {
                cursor.close();
            }
        }
        return path;
    }

    /**
     * @param uri the Uri to check
     * @return Whether the Uri authority is MediaProvider
     */
    private static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri the Uri to check
     * @return Whether the Uri authority is DownloadsProvider
     */
    private static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

13、判斷 Service 是否存活,是否在運行

 /**
     * 判斷 Service 是否處于存活狀態
     * @param context 上下文
     * @param serviceName Service 的名稱,帶有包名的完整名稱 ,例子:“com.hxd.test.service.FunctionService”
     * @return true 表示存活,false 表示不再存活
     */
    public static boolean isServiceWorked(Context context, String serviceName) {
        ActivityManager myManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        ArrayList<ActivityManager.RunningServiceInfo> runningService =
                (ArrayList<ActivityManager.RunningServiceInfo>) Objects.requireNonNull(myManager)
                        .getRunningServices(Integer.MAX_VALUE);
        for (int i = 0; i < runningService.size(); i++) {
            if (runningService.get(i).service.getClassName().equals(serviceName)) {
                return true;
            }
        }
        return false;
    }

14、在任何位置打開一個Activity

Intent intent = new Intent(Intent.ACTION_MAIN);  
intent.addCategory(Intent.CATEGORY_LAUNCHER);              
ComponentName cn = new ComponentName(packageName, className);              
intent.setComponent(cn);  
startActivity(intent);

15 、ANR 定位方法

系統會在/data/anr目錄下創建一個文件traces.txt


歡迎關注.jpg
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,461評論 6 532
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,538評論 3 417
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,423評論 0 375
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,991評論 1 312
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,761評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,207評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,268評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,419評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,959評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,782評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,983評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,528評論 5 359
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,222評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,653評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,901評論 1 286
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,678評論 3 392
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,978評論 2 374

推薦閱讀更多精彩內容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,660評論 25 708
  • 用兩張圖告訴你,為什么你的 App 會卡頓? - Android - 掘金 Cover 有什么料? 從這篇文章中你...
    hw1212閱讀 12,786評論 2 59
  • ¥開啟¥ 【iAPP實現進入界面執行逐一顯】 〖2017-08-25 15:22:14〗 《//首先開一個線程,因...
    小菜c閱讀 6,483評論 0 17
  • “誰知道未來會怎么樣呢!大不了,就只能去搬磚了呀!” “我們國家十幾億人口,光是在校大學生就有十四多萬,全...
    阿嚏三二三閱讀 283評論 0 1
  • 圖文/淺草 媽媽 ,月光之下靜靜地我想你啦! 突然,耳邊傳來熟悉的歌聲,聽著聽著不由自主淚流滿面……我的心被帶入歌...
    淺草拾光閱讀 1,365評論 3 6