[Android] Android development tips collection

1. Get the maximum memory that can be occupied when the phone is running

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

2. Change the dialog to display different sizes in different windows

//在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);
    }

3. Monitor whether Activity is displayed in front of the user

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

When Activity is displayed in front of the user, hasFocus is true;

4. The difference between a member variable and a local variable (abbreviated: Cheng, bureau)
1), the position in the class is different: Cheng: inside the class: method inside the lad method;
2), the memory position is different: Cheng: stack memory bureau: Heap memory;
3). Different life cycle: Cheng: coexist with the object and die: coexist with the method;
4). Different initialization value: Cheng: with default value. Bureau: no default value and must be assigned.

5. Java obtains variable uuid
uuid is similar to timestamp and never repeats.

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

6. Android gets the ssid of WiFi
1), add permissions in the AndroidManifest.xml file

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

2) Add the following code to the location that needs to be obtained

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

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

3) If you do not want to get the current connection, but want to get the connection in the WIFI settings

WifiManager.getConfiguredNetworks()

4) If you get more information, please check the blog of this brother: Android continuously obtains the current connected WiFi and surrounding hotspot list information.
7. Android opens the WiFi setting interface
1), judge whether the phone is connected to WiFi

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

code show as below:

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);

or

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.
Before Android 8.0 obtains the ssid of the wifi, the above method 6 can be used to obtain the ssid of the wifif device perfectly, but the ssid, which is the user name, cannot be displayed.

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. Determine whether the string is a pure number string

//判断字符串是不是纯数字
String str = "1234567a";

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

10. Get random numbers in any interval

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

11. Calculate forward to a certain day based on the current date

//以当天时间为基准向前推几日到某天
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. About the conversion of 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. Determine whether the Service is alive and running

/**
     * 判断 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. Open an Activity in any position

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 positioning method The
system will create a file traces.txt in the /data/anr directory

Author: Wu Nai Han Xiao Dai
link: https: //www.jianshu.com/p/3f4a38eca3e3
Source: Jane books
are copyrighted by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.

Guess you like

Origin blog.csdn.net/qq_30885821/article/details/109097174