在 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/