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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 176,752评论 25 709
  • 用两张图告诉你,为什么你的 App 会卡顿? - Android - 掘金 Cover 有什么料? 从这篇文章中你...
    hw1212阅读 14,539评论 2 59
  • ¥开启¥ 【iAPP实现进入界面执行逐一显】 〖2017-08-25 15:22:14〗 《//首先开一个线程,因...
    小菜c阅读 11,923评论 0 17
  • “谁知道未来会怎么样呢!大不了,就只能去搬砖了呀!” “我们国家十几亿人口,光是在校大学生就有十四多万,全...
    阿嚏三二三阅读 2,383评论 0 1
  • 图文/浅草 妈妈 ,月光之下静静地我想你啦! 突然,耳边传来熟悉的歌声,听着听着不由自主泪流满面……我的心被带入歌...
    浅草拾光阅读 5,166评论 3 6

友情链接更多精彩内容