編輯:Android 開發實例
本文整理了十餘個 Android 開發中經常用到的代碼片段,涵蓋存儲檢測、界面控制、短信彩信、廣播注冊、網絡請求等常見場景,方便大家隨取隨用。
1:查看是否有存儲卡插入
代碼如下:
String status=Environment.getExternalStorageState();
if(status.equals(Enviroment.MEDIA_MOUNTED))
{
說明有SD卡插入
}
2:讓某個 Activity 透明
在 OnCreate 中不設 Layout,改為 this.setTheme(R.style.Theme_Transparent);。以下是 Theme_Transparent 的定義(注意 transparent_bg 是一張透明圖片)。
3:在屏幕元素中設置句柄
使用 Activity.findViewById 取得屏幕上元素的句柄,透過該句柄即可設置或獲取該對象暴露的值。
代碼如下:
TextView msgTextView = (TextView)findViewById(R.id.msg);
msgTextView.setText(R.string.push_me);
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:發送彩信
代碼如下:
StringBuilder sb = new StringBuilder();
sb.append("file://");
sb.append(fd.getAbsoluteFile());
Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mmsto", number, null));
// Below extra datas are all optional.
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:發送 Mail
代碼如下:
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);
7:注冊一個 BroadcastReceiver
代碼如下:
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();
}
}
}
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:獲得手機 UA
代碼如下:
public String getUserAgent()
{
String user_agent = ProductProperties.get(ProductProperties.USER_AGENT_KEY, null);
return user_agent;
}
10:清空手機上 Cookie
代碼如下:
CookieSyncManager.createInstance(getApplicationContext());
CookieManager.getInstance().removeAllCookie();
11:建立 GPRS 連接
代碼如下:
//Dial the GPRS link.
private boolean openDataConnection() {
// Set up data connection.
DataConnection conn = DataConnection.getInstance();
if (connectMode == 0) {
ret = conn.openConnection(mContext, "cmwap", "cmwap", "cmwap");
} else {
ret = conn.openConnection(mContext, "cmnet", "", "");
}
}
12:PreferenceActivity 用法
代碼如下:
public class Setting extends PreferenceActivity
{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
}
}
Setting.xml:
android:key="seting2″
android:title="@string/seting2″
android:summary="@string/seting2″/>
android:key="seting1″
android:title="@string/seting1″
android:summaryOff="@string/seting1summaryOff"
android:summaryOn="@stringseting1summaryOff"/>
13:透過 HttpClient 從指定 server 獲取數據
代碼如下:
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet method = new HttpGet("https://www.baidu.com/1.html");
HttpResponse resp;
Reader reader = null;
try {
// AllClientPNames.TIMEOUT
HttpParams params = new BasicHttpParams();
params.setIntParameter(AllClientPNames.CONNECTION_TIMEOUT, 10000);
httpClient.setParams(params);
resp = httpClient.execute(method);
int status = resp.getStatusLine().getStatusCode();
if (status != HttpStatus.SC_OK) return false;
// HttpStatus.SC_OK;
return true;
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (reader != null) try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
以上代碼片段均為日常開發中的高頻操作,讀者可根據實際項目需求靈活取用。需要注意的是,部分接口(如 HttpClient、openDataConnection 等)在較新的 Android 版本中已被替換或限制,實際使用時請結合當前 API Level 調整。
Android WebView 支持 HTML5 Video 全屏播放的關鍵配置與代碼
讓 WebView 裡的 video 標籤能正常播放,需要硬件加速;讓它能全屏,需要攔截 WebChromeClient 的兩個回調。這兩步聽起來簡單,但中間有幾個容易讓
Android 登入畫面從零實作:完整程式碼與流程驗證
登入畫面是所有需要帳號的 App 的第一道門。它要處理的事情比看起來多:輸入欄的型別設定、點擊事件的綁定、字串比對、錯誤提示,還有一個常被省略的安全設計——限制連續嘗試次
Android 計時器實作:用秒數自行換算時分秒格式
需求很簡單:介面預設顯示「00:00:00」,按下開始鍵後先歸零再重新計時,讓數字像 10:28:34 這樣持續遞增,按下停止鍵則暫停計時。然而實作過程卻意外棘手。若採用
Android手機衛士(十七):用自訂屬性擴充設定項
前面已完成設定中心第一欄,接下來要讓其他設定欄也能重複使用。做法是為自訂 SettingItemView 宣告可配置屬性。宣告自訂屬性在 res/values/attrs