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

Android 常用代碼片段整理:撥打電話、短信、SD 卡、網絡請求與 Service

編輯:關於 Android 程式設計

本文彙整了一批 Android 開發中經常用到的代碼片段,涵蓋撥打電話、短信收发、SD 卡讀寫與容量判斷、XML 序列化與解析、ListView 優化、網絡請求以及 Service 的基礎用法,方便日常查閱。

1. 撥打電話

  Intent intent = new Intent(); intent.setAction(Intent.ACTION_CALL); intent.setData(Uri.parse("tel:"+number)); startActivity(intent); 

2. 發送短信

短信過長時需要拆分發送。一條短信的最大文本長度:中文約 70 個漢字,英文約 160 個字符。

  SmsManager smsmanager = SmsManager.getDefault(); /* sentIntent 發送報告, deliveryIntent 送達報告 */ ArrayList messages = smsmanager.divideMessage(content); for(String message : messages){ smsmanager.sendTextMessage(number, null, message, null, null); } 

3. 檢測 SD 卡狀態並寫入數據

  //MEDIA_MOUNTED:sd卡已經掛載,可用 if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { File file = new File(Environment.getExternalStorageDirectory(), "info.txt"); FileOutputStream fos; try { fos = new FileOutputStream(file); fos.write((name + "##" + pass).getBytes()); fos.close(); } catch (Exception e) { e.printStackTrace(); } } else { Toast.makeText(this, "sd卡不可用", 0).show(); } 

4. 判斷 SD 卡剩餘容量

  File path = Environment.getExternalStorageDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize; long totalBlocks; long availableBlocks; if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2){ blockSize = stat.getBlockSizeLong(); totalBlocks = stat.getBlockCountLong(); availableBlocks = stat.getAvailableBlocksLong(); } else{ blockSize = stat.getBlockSize(); totalBlocks = stat.getBlockCount(); availableBlocks = stat.getAvailableBlocks(); } TextView tv = (TextView) findViewById(R.id.tv); tv.setText(formatSize(availableBlocks * blockSize)); 

5. 使用 XML 序列化器生成 XML 文件

  XmlSerializer xs = Xml.newSerializer(); File file = new File("sdcard/sms2.xml"); try { FileOutputStream fos = new FileOutputStream(file); xs.setOutput(fos, "utf-8"); xs.startDocument("utf-8", true); xs.startTag(null, "message"); for (Message sms : smsList) { xs.startTag(null, "sms"); xs.startTag(null, "body"); xs.text(sms.getBody()); xs.endTag(null, "body"); xs.endTag(null, "sms"); } xs.endTag(null, "message"); xs.endDocument(); } catch (Exception e) { e.printStackTrace(); } 

6. 解析 XML 文件

  InputStream is = getClassLoader().getResourceAsStream("weather.xml"); XmlPullParser xp = Xml.newPullParser(); try { xp.setInput(is, "gbk"); int type = xp.getEventType(); while(type != XmlPullParser.END_DOCUMENT){ switch (type) { case XmlPullParser.START_TAG: if("city".equals(xp.getName())){ city = new City(); } else if("name".equals(xp.getName())){ String name = xp.nextText(); city.setName(name); } break; case XmlPullParser.END_TAG: break; } type = xp.next(); } } catch (Exception e) { e.printStackTrace(); } 

7. ListView 優化

核心思路是復用 convertView,並借助 ViewHolder 緩存子 View,避免重複的 findViewById:

  public View getView(int position, View convertView, ViewGroup parent) { News news = newsList.get(position); View v = null; ViewHolder mHolder; if(convertView == null){ v = View.inflate(MainActivity.this, R.layout.item_listview, null); mHolder = new ViewHolder(); mHolder.tv_title = (TextView) v.findViewById(R.id.tv_title); mHolder.tv_detail = (TextView) v.findViewById(R.id.tv_detail); mHolder.tv_comment = (TextView) v.findViewById(R.id.tv_comment); v.setTag(mHolder); }else{ v = convertView; mHolder = (ViewHolder) v.getTag(); } mHolder.tv_title.setText(news.getTitle()); mHolder.tv_detail.setText(news.getDetail()); mHolder.tv_comment.setText(news.getComment() + "條評論"); return v; } class ViewHolder{ TextView tv_title; TextView tv_detail; TextView tv_comment; } 

8. JUnit 測試框架的使用

在 manifest 中加入 InstrumentationTestRunner,在 application 下加入 uses-library,讓測試類繼承 AndroidTestCase,最後編寫測試方法即可。

9. GET 方式提交數據

原理是拼接 URL:

  String param1 = URLEncoder.encode(name); String param2 = URLEncoder.encode(password); URL url = new URL(path + "?name=" + param1 + "&password=" + param2); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setReadTimeout(5000); InputStream is = conn.getInputStream(); 

10. 中文亂碼問題

服務端(Tomcat 默認 iso8859-1)可將參數重新編碼:name = new String(name.getBytes("iso8859-1"), "utf-8");;安卓端則在提交前對中文做 URLEncoder.encode 編碼。

11. POST 方式提交數據

相較於 GET 只能提交較小的數據量(約 4K),POST 以表單或流的方式寫入服務器,可提交更大的數據:

  conn.setRequestMethod("POST"); conn.setConnectTimeout(5000); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); OutputStream os = conn.getOutputStream(); os.write(data.getBytes()); int code = conn.getResponseCode(); if (code == 200) { InputStream is = conn.getInputStream(); byte[] result = StreamTool.getBytes(is); return new String(result); } 

12. HttpClient 提交數據

HttpClient 相當於對瀏覽器的簡單封裝,GET 與 POST 兩種方式 respectively 使用 HttpGet 與 HttpPost 對象,透過 client.execute() 發送並解析返回流。

13. 短信監聽

在短信監聽器的 onReceive 方法中,通過 get("pdus") 拿到 PDU 數組,再用 SmsMessage.createFromPdu() 解析出正文與發送者地址。

14. Service 的使用

Service 運行在主線程中,需在 AndroidManifest 中配置。可通過 startService() 啟動,或通過 bindService() 綁定。服務的生命周期包含 onCreate、onStart(onStartCommand)與 onDestroy,適合用於後台的音訊監聽、文件上傳等場景。

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