開發過程中有些片段實在太常寫,與其每次翻舊專案,不如集中收錄。以下依功能分類整理,都是可以直接複製去改的骨架。
String status = Environment.getExternalStorageState();
if (status.equals(Environment.MEDIA_MOUNTED)) {
// 有 SD 卡
}
注意常數拼字是 Environment,寫成 Enviroment 是常見的手誤。
在 onCreate() 中不要設定 Layout,改套用自訂主題:
this.setTheme(R.style.Theme_Transparent);
主題定義中需搭配一張全透明的背景圖作為 transparent_bg。
用 Activity.findViewById() 取得元件實例,之後即可讀寫該物件對外開放的屬性:
TextView msgTextView = (TextView) findViewById(R.id.msg); msgTextView.setText(R.string.push_me);
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);
StringBuilder sb = new StringBuilder();
sb.append("file://");
sb.append(fd.getAbsoluteFile());
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);
mime = "img/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);
registerReceiver(mMasterResetReciever, new IntentFilter("oms.action.MASTERRESET"));
private BroadcastReceiver mMasterResetReciever = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if ("oms.action.MASTERRESET".equals(action)) {
RecoverDefaultConfig();
}
}
};
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) { }
}
public String getUserAgent() {
String user_agent = ProductProperties.get(ProductProperties.USER_AGENT_KEY, null);
return user_agent;
}
CookieSyncManager.createInstance(getApplicationContext()); CookieManager.getInstance().removeAllCookie();
這些片段多為早期 API 的寫法,實際套用時請留意兩件事:一是 registerReceiver 註冊後必須在適當時機 unregister,否則會洩漏;二是傳送簡訊與彩信這類片段多半只是叫起系統的編輯界面,若要背景直接送達,需要 SMSManager 與相應權限,而高版本 Android 對背景簡訊的限制也更嚴格。