編輯:關於 Android 開發
本文彙整了一批不常見卻非常實用的 Android 程式碼片段,涵蓋螢幕尺寸計算、狀態切換、檔案處理、通知、網路判斷等常見需求,可作為日常開發的速查工具集。
1. 精確獲取螢幕尺寸(例如 3.5、4.0、5.0 吋螢幕)
public static double getScreenPhysicalSize(Activity ctx) {
DisplayMetrics dm = new DisplayMetrics();
ctx.getWindowManager().getDefaultDisplay().getMetrics(dm);
double diagonalPixels = Math.sqrt(Math.pow(dm.widthPixels, 2) + Math.pow(dm.heightPixels, 2));
return diagonalPixels / (160 * dm.density);
}
2. 判斷是否為平板(官方用法)
public static boolean isTablet(Context context) {
return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK)
>= Configuration.SCREENLAYOUT_SIZE_LARGE;
}
3. 文字根據狀態更改顏色 android:textColor
<selector xmlns:android="https://schemas.android.com/apk/res/android">
<item android:color="#53c1bd" android:state_selected="true"/>
<item android:color="#53c1bd" android:state_focused="true"/>
<item android:color="#53c1bd" android:state_pressed="true"/>
<item android:color="#777777"/>
</selector>
4. 背景色根據狀態更改(直接給 color 會報錯,需用 shape 包裹)
<selector xmlns:android="https://schemas.android.com/apk/res/android">
<item android:state_selected="true">
<shape><gradient android:angle="0" android:centerColor="#00a59f" android:endColor="#00a59f" android:startColor="#00a59f" /></shape>
</item>
<item android:state_focused="true">
<shape><gradient android:angle="0" android:centerColor="#00a59f" android:endColor="#00a59f" android:startColor="#00a59f" /></shape>
</item>
<item android:state_pressed="true">
<shape><gradient android:angle="0" android:centerColor="#00a59f" android:endColor="#00a59f" android:startColor="#00a59f" /></shape>
</item>
<item>
<shape><gradient android:angle="0" android:centerColor="#00ff00" android:endColor="#00ff00" android:startColor="#00ff00" /></shape>
</item>
</selector>
5. 啟動 APK 的預設 Activity
public static void startApkActivity(final Context ctx, String packageName) {
PackageManager pm = ctx.getPackageManager();
PackageInfo pi;
try {
pi = pm.getPackageInfo(packageName, 0);
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setPackage(pi.packageName);
List<ResolveInfo> apps = pm.queryIntentActivities(intent, 0);
ResolveInfo ri = apps.iterator().next();
if (ri != null) {
String className = ri.activityInfo.name;
intent.setComponent(new ComponentName(packageName, className));
ctx.startActivity(intent);
}
} catch (NameNotFoundException e) {
Log.e("startActivity", e);
}
}
6. 計算文字寬度(若設定了 textStyle,還需進一步設定 TextPaint)
public static float GetTextWidth(String text, float Size) {
TextPaint FontPaint = new TextPaint();
FontPaint.setTextSize(Size);
return FontPaint.measureText(text);
}
7. 獲取應用程式下所有 Activity
public static ArrayList<String> getActivities(Context ctx) {
ArrayList<String> result = new ArrayList<String>();
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.setPackage(ctx.getPackageName());
for (ResolveInfo info : ctx.getPackageManager().queryIntentActivities(intent, 0)) {
result.add(info.activityInfo.name);
}
return result;
}
8. 檢測字串中是否包含漢字
public static boolean checkChinese(String sequence) {
final String format = "[\\u4E00-\\u9FA5\\uF900-\\uFA2D]";
boolean result = false;
Pattern pattern = Pattern.compile(format);
Matcher matcher = pattern.matcher(sequence);
result = matcher.find();
return result;
}
9. 檢測字串只能包含:中文、數字、下劃線(_)、橫線(-)
public static boolean checkNickname(String sequence) {
final String format = "[^\\u4E00-\\u9FA5\\uF900-\\uFA2D\\w-_]";
Pattern pattern = Pattern.compile(format);
Matcher matcher = pattern.matcher(sequence);
return !matcher.find();
}
10. 檢查有沒有應用程式來接受處理你發出的 intent
public static boolean isIntentAvailable(Context context, String action) {
final PackageManager packageManager = context.getPackageManager();
final Intent intent = new Intent(action);
List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
11. 使用 TransitionDrawable 實現漸變效果(比 AlphaAnimation 更好,可避免閃爍)
private void setImageBitmap(ImageView imageView, Bitmap bitmap) {
final TransitionDrawable td = new TransitionDrawable(new Drawable[] {
new ColorDrawable(android.R.color.transparent),
new BitmapDrawable(mContext.getResources(), bitmap)
});
imageView.setBackgroundDrawable(imageView.getDrawable());
imageView.setImageDrawable(td);
td.startTransition(200);
}
12. 掃描指定的檔案(從本軟體新增、修改、刪除圖片或音視頻時更新系統媒體庫,不必掃描整個 SD 卡)
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
13. Dip 轉 px(在程式碼中設定位置、大小時很有用)
public static int dipToPX(final Context ctx, float dip) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, ctx.getResources().getDisplayMetrics());
}
14. 獲取已安裝 APK 的路徑
PackageManager pm = getPackageManager();
for (ApplicationInfo app : pm.getInstalledApplications(0)) {
Log.d("PackageList", "package: " + app.packageName + ", sourceDir: " + app.sourceDir);
}
15. 多進程 Preferences 資料共享
public static void putStringProcess(Context ctx, String key, String value) {
SharedPreferences sharedPreferences = ctx.getSharedPreferences("preference_mu", Context.MODE_MULTI_PROCESS);
Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
public static String getStringProcess(Context ctx, String key, String defValue) {
SharedPreferences sharedPreferences = ctx.getSharedPreferences("preference_mu", Context.MODE_MULTI_PROCESS);
return sharedPreferences.getString(key, defValue);
}
16. 泛型 ArrayList 轉陣列
@SuppressWarnings("unchecked")
public static <T> T[] toArray(Class<?> cls, ArrayList<T> items) {
if (items == null || items.size() == 0) {
return (T[]) Array.newInstance(cls, 0);
}
return items.toArray((T[]) Array.newInstance(cls, items.size()));
}
17. 保存恢復 ListView 當前位置(可保存在 Preference 或資料庫,資料載入後再設定)
private void saveCurrentPosition() {
if (mListView != null) {
int position = mListView.getFirstVisiblePosition();
View v = mListView.getChildAt(0);
int top = (v == null) ? 0 : v.getTop();
// 保存 position 和 top
}
}
private void restorePosition() {
if (mFolder != null && mListView != null) {
int position = 0;// 取出保存的數據
int top = 0;// 取出保存的數據
mListView.setSelectionFromTop(position, top);
}
}
18. 調用便攜式熱點和數據共享設定
public static Intent getHotspotSetting() {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_MAIN);
ComponentName com = new ComponentName("com.android.settings", "com.android.settings.TetherSettings");
intent.setComponent(com);
return intent;
}
19. 格式化輸出 IP 地址
public static String getIp(Context ctx) {
return Formatter.formatIpAddress((WifiManager) ctx.getSystemService(Context.WIFI_SERVICE).getConnectionInfo().getIpAddress());
}
20. 文件夾排序(先文件夾,後文件)
public static void sortFiles(File[] files) {
Arrays.sort(files, new Comparator<File>() {
@Override
public int compare(File lhs, File rhs) {
boolean l1 = lhs.isDirectory();
boolean l2 = rhs.isDirectory();
if (l1 && !l2) return -1;
else if (!l1 && l2) return 1;
else return lhs.getName().compareTo(rhs.getName());
}
});
}
21. 發送不重複的通知 Notification(關鍵在 requestCode,此處用系統時間保證每次都是新的)
public static void sendNotification(Context context, String title, String message, Bundle extras) {
Intent mIntent = new Intent(context, FragmentTabsActivity.class);
mIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
mIntent.putExtras(extras);
int requestCode = (int) System.currentTimeMillis();
PendingIntent mContentIntent = PendingIntent.getActivity(context, requestCode, mIntent, 0);
Notification mNotification = new NotificationCompat.Builder(context)
.setContentTitle(title).setSmallIcon(R.drawable.app_icon)
.setContentIntent(mContentIntent).setContentText(message).build();
mNotification.flags |= Notification.FLAG_AUTO_CANCEL;
mNotification.defaults = Notification.DEFAULT_ALL;
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(requestCode, mNotification);
}
22. 程式碼設定 TextView 的樣式
new TextView(new ContextThemeWrapper(this, R.style.text_style))
23. IP 地址轉 8 位十六進位串
/** ip 轉 16 進制 */
public static String ipToHex(String ips) {
StringBuffer result = new StringBuffer();
if (ips != null) {
StringTokenizer st = new StringTokenizer(ips, ".");
while (st.hasMoreTokens()) {
String token = Integer.toHexString(Integer.parseInt(st.nextToken()));
if (token.length() == 1) token = "0" + token;
result.append(token);
}
}
return result.toString();
}
/** 16 進制轉 ip */
public static String texToIp(String ips) {
try {
StringBuffer result = new StringBuffer();
if (ips != null && ips.length() == 8) {
for (int i = 0; i < 8; i += 2) {
if (i != 0) result.append('.');
result.append(Integer.parseInt(ips.substring(i, i + 2), 16));
}
}
return result.toString();
} catch (NumberFormatException ex) {
Logger.e(ex);
}
return "";
}
24. WebView 保留縮放功能但隱藏縮放控件
mWebView.getSettings().setSupportZoom(true);
mWebView.getSettings().setBuiltInZoomControls(true);
if (DeviceUtils.hasHoneycomb())
mWebView.getSettings().setDisplayZoomControls(false);
25. 獲取網路類型名稱
public static String getNetworkTypeName(Context context) {
if (context != null) {
ConnectivityManager connectMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectMgr != null) {
NetworkInfo info = connectMgr.getActiveNetworkInfo();
if (info != null) {
switch (info.getType()) {
case ConnectivityManager.TYPE_WIFI:
return "WIFI";
case ConnectivityManager.TYPE_MOBILE:
return getNetworkTypeName(info.getSubtype());
}
}
}
}
return getNetworkTypeName(TelephonyManager.NETWORK_TYPE_UNKNOWN);
}
26. Android 解壓 Zip 包
public static void UnZipFolder(String zipFileString, String outPathString) throws Exception {
java.util.zip.ZipInputStream inZip = new java.util.zip.ZipInputStream(new java.io.FileInputStream(zipFileString));
java.util.zip.ZipEntry zipEntry;
String szName = "";
while ((zipEntry = inZip.getNextEntry()) != null) {
szName = zipEntry.getName();
if (zipEntry.isDirectory()) {
szName = szName.substring(0, szName.length() - 1);
java.io.File folder = new java.io.File(outPathString + java.io.File.separator + szName);
folder.mkdirs();
} else {
java.io.File file = new java.io.File(outPathString + java.io.File.separator + szName);
file.createNewFile();
java.io.FileOutputStream out = new java.io.FileOutputStream(file);
int len;
byte[] buffer = new byte[1024];
while ((len = inZip.read(buffer)) != -1) {
out.write(buffer, 0, len);
out.flush();
}
out.close();
}
}
inZip.close();
}
27. 從 assets 中讀取文字和圖片資源
/** 從 assets 文件夾中讀取文本數據 */
public static String getTextFromAssets(final Context context, String fileName) {
String result = "";
try {
InputStream in = context.getResources().getAssets().open(fileName);
int lenght = in.available();
byte[] buffer = new byte[lenght];
in.read(buffer);
result = EncodingUtils.getString(buffer, "UTF-8");
in.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/** 從 assets 文件夾中讀取圖片 */
public static Drawable loadImageFromAsserts(final Context ctx, String fileName) {
try {
InputStream is = ctx.getResources().getAssets().open(fileName);
return Drawable.createFromStream(is, null);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
28. 展開、收起狀態欄(可用於點擊 Notification 之後收起狀態欄)
public static final void collapseStatusBar(Context ctx) {
Object sbservice = ctx.getSystemService("statusbar");
try {
Class<?> statusBarManager = Class.forName("android.app.StatusBarManager");
Method collapse;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
collapse = statusBarManager.getMethod("collapsePanels");
} else {
collapse = statusBarManager.getMethod("collapse");
}
collapse.invoke(sbservice);
} catch (Exception e) {
e.printStackTrace();
}
}
29. 獲取狀態欄高度
public static int getStatusBarHeight(Context context) {
Class<?> c = null;
Object obj = null;
Field field = null;
int x = 0, statusBarHeight = 0;
try {
c = Class.forName("com.android.internal.R$dimen");
obj = c.newInstance();
field = c.getField("status_bar_height");
x = Integer.parseInt(field.get(obj).toString());
statusBarHeight = context.getResources().getDimensionPixelSize(x);
} catch (Exception e1) {
e1.printStackTrace();
}
return statusBarHeight;
}
30. ListView 使用 ViewHolder 極簡寫法
public static <T extends View> T getAdapterView(View convertView, int id) {
SparseArray<View> viewHolder = (SparseArray<View>) convertView.getTag();
if (viewHolder == null) {
viewHolder = new SparseArray<View>();
convertView.setTag(viewHolder);
}
View childView = viewHolder.get(id);
if (childView == null) {
childView = convertView.findViewById(id);
viewHolder.put(id, childView);
}
return (T) childView;
}
31. 設定 Activity 透明(用於模擬 Dialog 效果)
<style name="TransparentActivity" parent="AppBaseTheme">
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:colorBackgroundCacheHint">@null</item>
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowContentOverlay">@null</item>
</style>
32. 程式碼切換全屏(播放器界面常用)
// 切換到全屏 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); // 切換到非全屏 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
33. 調用開發者選項中顯示觸摸位置(1 顯示,0 不顯示)
android.provider.Settings.System.putInt(getContentResolver(), "show_touches", 1);
34. 獲取設備上已安裝且可啟動的應用列表
Intent intent = new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_LAUNCHER); List<ResolveInfo> activities = getPackageManager().queryIntentActivities(intent, 0);
轉載自 農民伯伯:https://over140.cnblogs.com
Linux TCP 發送過程源碼分析——Socket 層
Linux TCP 發送過程源碼分析——Socket 層 作者:lvyilong316 | 內核版本:3.15.2 Socket 數據結構關係 發送流程圖 下圖給出了
Android Studio 下 NDK 开发(一):从配置环境到 JNI 调用
Android Studio 下 NDK 开发(一):从配置环境到 JNI 调用 捣鼓了一天的 NDK,总结一下。在 Eclipse 下开发 NDK 似乎挺麻烦,书上的做
FFmpeg 使用手冊:Windows、Linux 與 macOS 平台編譯安裝
為什麼需要自行編譯 FFmpeg FFmpeg 官方提供了可執行文件,許多 Linux 發行版源中也包含 FFmpeg 包。但系統源中的版本往往較舊,可能不支持新的編碼格
Android 博客園客戶端實作:查看評論與搜尋博主
Android 博客園客戶端實作:查看評論與搜尋博主 本系列以博客園為例,示範如何打造 Android 客戶端。這一篇聚焦在兩個常見功能:查看文章或新聞評論,以及搜尋博主