編輯:關於 Android 程式設計
本文彙整了 Android 開發中經常使用的程式碼片段,涵蓋圖片處理、電話與網路狀態、意圖啟動等常見操作,方便隨時查閱。
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" />,且此功能在模擬器上無法實現,必須連接真機。
// in strings.xml.. <string name="my_text">Thanks for visiting %s. You age is %d!</string> // and in the java code: String.format(getString(R.string.my_text), "oschina", 33);
方式一,於 Java 中設定:
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
方式二,於 AndroidManifest.xml 中為 Activity 設定 Theme:
android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen"
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" />。
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("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=new StatFs(sdcardDir.getPath()); Long blockSize=statFs.getBlockSize(); Long totalBlocks=statFs.getBlockCount(); 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 入門第二天:Toast、Menu 與顯式/隱式 Intent 全解
1. Toast 提醒 為昨天寫的按鈕程式加上一個提醒,在 MainActivity 中加入如下程式碼: Button bt1 = (Button) findViewB
Android 心跳動畫效果實作
最近在做一個教育類專案,做學習工具時美工丟來這樣一個需求: 看起來有點意思,但原理並不複雜:給一個控制項加上圓形背景,然後讓它循環做「放大伴隨透明度降低、縮小伴隨透明度
Android 專案自定義頂部標題欄
自定義標題欄的目的在 Android 專案中,頂部標題欄經常需要顯示返回按鈕、標題文字與提交按鈕。若每個頁面都重複撰寫標題欄邏輯,維護成本會很高。因此,可以將標題欄抽成獨
Android Activity 建立、跳轉與資料傳遞完整教學
Activity 的角色 Activity 是 Android 四大元件之一,可理解為應用程式中的一個畫面。使用者看到的每一頁,通常都對應一個 Activity。它負責使