編輯:關於 Android 程式設計
日常開發中有些小功能,寫過一次之後往往還要再寫一次。本文把一批實用度極高的程式碼片段整理在一起,涵蓋圖片處理、系統服務、Intent 呼叫與裝置資訊取得等常見需求,方便隨時翻查。
Bitmap bitmapOrg = BitmapFactory.decodeResource(this.getContext().getResources(), R.drawable.moon); Matrix matrix = new Matrix(); matrix.postRotate(-90);// 旋轉角度 Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0, bitmapOrg.getWidth(), bitmapOrg.getHeight(), matrix, true); BitmapDrawable bmd = new BitmapDrawable(resizedBitmap);
// 建立電話管理 TelephonyManager tm = (TelephonyManager) activity.getSystemService(Context.TELEPHONY_SERVICE); // 取得手機號碼 String phoneId = tm.getLine1Number();
需在 manifest 中加入 <uses-permission android:name="android.permission.READ_PHONE_STATE" />。注意此段在模擬器上無法正常運作,且較新版本 Android 需要執行期授權。
<!-- strings.xml --> <string name="my_text">Thanks for visiting %s. You age is %d!</string> // Java 端 String.format(getString(R.string.my_text), "oschina", 33);
方法 A,在 Java 程式碼中設定:
/** 全螢幕設定,隱藏視窗所有裝飾 */ requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
方法 B,在 AndroidManifest.xml 中透過 theme 指定:
<activity android:name=".Login.NetEdit" android:label="@string/label_net_Edit" android:screenOrientation="portrait" android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen"> <intent-filter> <action android:name="android.intent.Net_Edit" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity>
android:theme="@android:style/Theme.Dialog"
ConnectivityManager con = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE); boolean wifi = con.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting(); boolean internet = con.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting();
記得補上權限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
直接發 Intent 而裝置上沒有對應 App 會導致崩潰,先檢查再呼叫才是安全做法。
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; }
try { Intent intent = new Intent(Intent.ACTION_CALL); intent.setData(Uri.parse("tel:+110")); startActivity(intent); } catch (Exception e) { Log.e("SampleApp", "Failed to invoke call", e); }
Intent i = new Intent(Intent.ACTION_SEND); //i.setType("text/plain"); // 模擬器請使用這行 i.setType("message/rfc822") ; // 真機上使用這行 i.putExtra(Intent.EXTRA_EMAIL, new String[]{"test@gmail.com","test@163.com}); i.putExtra(Intent.EXTRA_SUBJECT,"subject goes here"); i.putExtra(Intent.EXTRA_TEXT,"body goes here"); startActivity(Intent.createChooser(i, "Select email application."));
Intent viewIntent = new Intent("android.intent.action.VIEW", Uri.parse("https://vaiyanzi.cnblogs.com")); startActivity(viewIntent);
String android_id = Secure.getString(getContext().getContentResolver(), Secure.ANDROID_ID);
public String getLocalIpAddress() { try { for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) { NetworkInterface intf = en.nextElement(); for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) { InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress()) { return inetAddress.getHostAddress().toString(); } } } } catch (SocketException ex) { Log.e(LOG_TAG, ex.toString()); } return null; }
/** 取得記憶卡路徑 */ File sdcardDir = Environment.getExternalStorageDirectory(); /** StatFs 檢視檔案系統空間使用情況 */ StatFs statFs = new StatFs(sdcardDir.getPath()); /** 每個 Block 的大小 */ Long blockSize = statFs.getBlockSize(); /** Block 總數 */ Long totalBlocks = statFs.getBlockCount(); /** 可用的 Block 數 */ Long availableBlocks = statFs.getAvailableBlocks();
private Uri insertContact(Context context, String name, String phone) { ContentValues values = new ContentValues(); values.put(People.NAME, name); Uri uri = getContentResolver().insert(People.CONTENT_URI, values); Uri numberUri = Uri.withAppendedPath(uri, People.Phones.CONTENT_DIRECTORY); values.clear(); values.put(Contacts.Phones.TYPE, People.Phones.TYPE_MOBILE); values.put(People.NUMBER, phone); getContentResolver().insert(numberUri, values); return uri; }
Intent intentBatteryUsage = new Intent(Intent.ACTION_POWER_USAGE_SUMMARY); startActivity(intentBatteryUsage);
ActivityManager mActivityManager = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE); List<ActivityManager.RunningAppProcessInfo> mRunningProcess = mActivityManager.getRunningAppProcesses(); int i = 1; for (ActivityManager.RunningAppProcessInfo amProcess : mRunningProcess) { Log.e("homer Application", (i++) + " PID = " + amProcess.pid + "; processName = " + amProcess.processName); }
這些片段多數寫於 Android 早期版本,直接複製到新專案時要留意兩件事:一是權限模型已改為執行期動態授權,READ_PHONE_STATE、READ_CONTACTS 這類敏感權限都必須在執行時向使用者請求;二是部分 API 已被標記為不建議使用,例如 getRunningAppProcesses() 在後續版本回傳的資訊大幅受限,getLine1Number() 也需要權限與讀取限制。理解原理之後,再對照目前版本的官方文件調整,才能用得安心。
如何開啟手機 USB 偵錯來連接刷機精靈
插上電腦,刷機精靈卻一直提示要開啟 USB 介面——問題是這個開關到底藏在哪?由於各版本的 Android 放的位置差異不小,以下依系統版本分三種情況說明。 開啟手機 U
Android 事件分發機制全解析:從 dispatchTouchEvent 到 requestDisallowIntercept
一、概述 說到 Android 的事件分發機制,真是既熟悉又陌生。每次需要時翻翻源碼,總能若有所得;可要憑自己的理解從頭到尾講一遍,卻又一句也說不上來。歸根究底,大概是自
java/android 設計模式學習筆記(15)——責任鏈模式
這篇博客我們來介紹責任鏈模式(Chain-of-responsibility Pattern),它又稱職責鏈模式,是行為型設計模式之一。顧名思義,責任鏈模式中存在一個鏈式
微信電腦版視頻存在哪裡 文件夾路徑一次找到
微信有了電腦版後,在電腦上收到的視頻究竟保存在哪個文件夾?下面小編就帶你把它找出來。 1、先在手機微信中把視頻發給自己,搜索自己的微信即可發送(發給好友或文件傳輸助手也行