Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 開發入門

Android 開發常用程式碼片段整理(14 個實用範例)

編輯:開發入門

把日常開發常翻ermined實用的小片段整理在一起,方便查閱。以下每段都附上簡短說明,可直接複製後依專案調整。

1. 判斷 SD 卡是否已掛載

String status = Environment.getExternalStorageState();
if (status.equals(Environment.MEDIA_MOUNTED)) {
    // 有外部儲存空間可用
}

2. 讓 Activity 背景透明

在 onCreate() 中不設定 Layout,改套用自訂主題:

this.setTheme(R.style.Theme_Transparent);

對應的 style 定義放在 res/values/styles.xml,背景指向一張透明圖片即可。

3. 取得畫面元件的參照

TextView msgTextView = (TextView) findViewById(R.id.msg);
msgTextView.setText(R.string.push_me);

findViewById() 傳回元件參照後,就能讀寫該物件對外開放的所有屬性。

4. 傳送簡訊

String body = "this is mms demo";
Intent mmsintent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("smsto", number, null));
mmsintent.putExtra(Messaging.KEY_ACTION_SENDTO_MESSAGE_BODY, body);
mmsintent.putExtra(Messaging.KEY_ACTION_SENDTO_COMPOSE_MODE, true);
mmsintent.putExtra(Messaging.KEY_ACTION_SENDTO_EXIT_ON_SENT, true);
startActivity(mmsintent);

5. 傳送多媒體簡報(MMS)

StringBuilder sb = new StringBuilder();
sb.append("file://");
sb.append(fd.getAbsolutePath());

Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mmsto", number, null));
// 以下皆為選擇性欄位
intent.putExtra(Messaging.KEY_ACTION_SENDTO_MESSAGE_SUBJECT, subject);
intent.putExtra(Messaging.KEY_ACTION_SENDTO_MESSAGE_BODY, body);
intent.putExtra(Messaging.KEY_ACTION_SENDTO_CONTENT_URI, sb.toString());
intent.putExtra(Messaging.KEY_ACTION_SENDTO_COMPOSE_MODE, composeMode);
intent.putExtra(Messaging.KEY_ACTION_SENDTO_EXIT_ON_SENT, exitOnSent);
startActivity(intent);

6. 分享檔案(例如透過 Email)

String mime = "image/jpg";
shareIntent.setDataAndType(Uri.fromFile(fd), mime);
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(fd));
shareIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
shareIntent.putExtra(Intent.EXTRA_TEXT, body);

7. 註冊 BroadcastReceiver

registerReceiver(mMasterResetReceiver,
        new IntentFilter("oms.action.MASTERRESET"));

private BroadcastReceiver mMasterResetReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if ("oms.action.MASTERRESET".equals(action)) {
            RecoverDefaultConfig();
        }
    }
};

8. 用 ContentObserver 監聽資料表變化

private ContentObserver mDownloadsObserver =
        new DownloadsChangeObserver(Downloads.CONTENT_URI);

private class DownloadsChangeObserver extends ContentObserver {
    public DownloadsChangeObserver(Uri uri) {
        super(new Handler());
    }

    @Override
    public void onChange(boolean selfChange) {
        // 資料有變動時在這裡處理
    }
}

9. 取得裝置 User-Agent

private String getUserAgent() {
    return ProductProperties.get(ProductProperties.USER_AGENT_KEY, null);
}

10. 清除 Cookie

CookieSyncManager.createInstance(getApplicationContext());
CookieManager.getInstance().removeAllCookie();

11. 建立 GPRS 資料連線

private boolean openDataConnection() {
    DataConnection conn = DataConnection.getInstance();
    boolean ret;
    if (connectMode == 0) {
        ret = conn.openConnection(mContext, "cmwap", "cmwap", "cmwap");
    } else {
        ret = conn.openConnection(mContext, "cmnet", "", "");
    }
    return ret;
}

12. PreferenceActivity 的基本用法

public class Setting extends PreferenceActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.settings);
    }
}

對應的 res/xml/settings.xml 裡放各項 Preference 定義:

<PreferenceScreen xmlns:android="https://schemas.android.com/apk/res/android">
    <CheckBoxPreference
        android:key="seting1"
        android:title="@string/seting1"
        android:summaryOn="@string/seting1summaryOn"
        android:summaryOff="@string/seting1summaryOff" />
    <EditTextPreference
        android:key="seting2"
        android:title="@string/seting2"
        android:summary="@string/seting2" />
</PreferenceScreen>

13. 用 HttpClient 抓取遠端資料

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet method = new HttpGet("https://www.example.com/1.html");
Reader reader = null;

try {
    HttpParams params = new BasicHttpParams();
    params.setIntParameter(AllClientPNames.CONNECTION_TIMEOUT, 10000);
    httpClient.setParams(params);

    HttpResponse resp = httpClient.execute(method);
    int status = resp.getStatusLine().getStatusCode();
    if (status != HttpStatus.SC_OK) {
        return false;
    }
    return true;
} catch (ClientProtocolException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (reader != null) {
        try {
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

注意這裡設定了連線逾時。少了逾時設定,網路異常時執行緒可能會無限期卡住。

14. 顯示 Toast 提示

Toast.makeText(getApplicationContext(), R.string._item, Toast.LENGTH_SHORT).show();

以上片段多為早期 Android 版本寫法,其中 GPRS 手動連線、ProductProperties 取得 UA、以及直接操作 Messaging 內部常數等做法,在新版平台上多半已有更適當的官方 API 取代,實作時請對照目前版本的文件確認。

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