Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 開發常用程式碼片段整理

編輯:關於 Android 程式設計

本文彙整了 Android 開發中經常使用的程式碼片段,涵蓋圖片處理、電話與網路狀態、意圖啟動等常見操作,方便隨時查閱。

1. 圖片旋轉

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);

2. 獲取手機號碼

//創建電話管理
TelephonyManager tm = (TelephonyManager)
//與手機建立連接
activity.getSystemService(Context.TELEPHONY_SERVICE);
//獲取手機號碼
String phoneId = tm.getLine1Number();

需於 manifest 中加入 <uses-permission android:name="android.permission.READ_PHONE_STATE" />,且此功能在模擬器上無法實現,必須連接真機。

3. 格式化 string.xml 中的字串

// 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);

4. 設定全螢幕

方式一,於 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"

5. 將 Activity 設為 Dialog 形式

android:theme="@android:style/Theme.Dialog"

6. 檢查網路是否連上

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" />。

7. 檢測 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;
}

8. 撥打電話

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);
}

9. 發送 Email

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."));

10. 打開瀏覽器

Intent viewIntent = new Intent("android.intent.action.VIEW",Uri.parse("https://vaiyanzi.cnblogs.com"));
startActivity(viewIntent);

11. 獲取設備唯一標識碼

String android_id = Secure.getString(getContext().getContentResolver(), Secure.ANDROID_ID);

12. 獲取本機 IP 位址

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;
}

13. 獲取存儲卡路徑與使用情況

File sdcardDir=Environment.getExternalStorageDirectory();
StatFs statFs=new StatFs(sdcardDir.getPath());
Long blockSize=statFs.getBlockSize();
Long totalBlocks=statFs.getBlockCount();
Long availableBlocks=statFs.getAvailableBlocks();

14. 新增聯繫人

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;
}

15. 查看電池使用情況

Intent intentBatteryUsage = new Intent(Intent.ACTION_POWER_USAGE_SUMMARY);
startActivity(intentBatteryUsage);

16. 獲取進程號

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);
}

以上片段可依實際需求靈活組合,作為日常開發的參考工具箱。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved