Android 开发常用工具合集

在 Android 开发中经常使用到的小功能,用于记录开发的那些事^_^

1. 获取 release 和 debug 版本的 SHA1

public static String getSHA1(Context context) {
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), PackageManager.GET_SIGNATURES);
            byte[] cert = info.signatures[0].toByteArray();
            MessageDigest md = MessageDigest.getInstance("SHA1");
            byte[] publicKey = md.digest(cert);
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < publicKey.length; i++) {
                String appendString = Integer.toHexString(0xFF & publicKey[i])
                        .toUpperCase(Locale.US);
                if (appendString.length() == 1)
                    hexString.append("0");
                hexString.append(appendString);
                hexString.append(":");
            }
            String result = hexString.toString();
            return result.substring(0, result.length()-1);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

2. 打开 APP 华为手机提示全屏显示

  在 AndroidManifest.xml 中的 Application 节点下添加如下代码:

<meta-data android:name="android.max_aspect" android:value="2.4" />

3. 保持屏幕常亮

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

通常会在一个 Activity 的 onResume() 和 onPause() 方法中分别调用这两个方法。

 

4. ListView 动态设置数据时高度自适应

package com.custom.ui.view;

import android.content.Context;
import android.widget.ListView;

public class MyListView extends ListView {

    public MyListView(Context context) {
        super(context);
    }

    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int mExpandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, mExpandSpec);
    }

}
<com.custom.ui.view.MyListView
     android:id="@+id/lv_data"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:scrollbars="none"
     android:divider="@null"
     android:listSelector="@color/transparent"/>

 

5. 防止 ListView 动态设置数据时数据过长自动滑动至 ListView 底部

android:descendantFocusability="blocksDescendants"

该属性是当一个为view获取焦点时,定义 ViewGroup 和其子控件两者之间的关系。
属性的值有三种:
beforeDescendants:ViewGroup 会优先其子类控件而获取到焦点
afterDescendants:ViewGroup 只有当其子类控件不需要获取焦点时才获取焦点
blocksDescendants:ViewGroup 会覆盖子类控件而直接获得焦点

 

6. Android 强大的工具类推荐

https://blankj.com/2016/07/31/android-utils-code/

 

posted @ 2019-05-09 11:01  走在一线的码农  阅读(1020)  评论(0编辑  收藏  举报