編輯:關於 Android 程式設計
TelephonyManager 是 Android 用來管理通話狀態與網路資訊的系統服務類別。透過它能取得裝置識別碼、電信業者、網路類型、SIM 卡狀態、基站位置等一手資訊,是開發通訊類應用時最基礎的一塊拼圖。
第一步永遠是權限宣告,少了這幾行,後續的 API 呼叫會直接丟出安全性例外:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
取得服務的入口是 getSystemService(Context.TELEPHONY_SERVICE)。以下範例把各項狀態彙整成清單,用 SimpleAdapter 綁定到 ListView,同時註冊 PhoneStateListener 監聽來電並將號碼寫入本機檔案:
package com.example.telephonystatus;
import java.io.FileNotFoundException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.view.Menu;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class MainActivity extends Activity {
private ListView list1;
// 代表各項狀態名稱的字串陣列
private String[] statusName;
// 存放實際狀態值的集合
private ArrayList<String> statusValues = new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list1 = (ListView) findViewById(R.id.list1);
// 取得系統的 TelephonyManager
TelephonyManager tele =
(TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
// 狀態名稱、SIM 卡狀態、網路類型的文字對照表
statusName = getResources().getStringArray(R.array.statusNames);
String[] simType = getResources().getStringArray(R.array.simState);
String[] phoneType = getResources().getStringArray(R.array.phoneType);
statusValues.add(tele.getDeviceId()); // 裝置識別碼
statusValues.add(tele.getDeviceSoftwareVersion() != null
? tele.getDeviceSoftwareVersion() : "未知"); // 平台版本
statusValues.add(tele.getNetworkOperator()); // 網路營運代碼
statusValues.add(tele.getNetworkOperatorName()); // 網路營運商名稱
statusValues.add(phoneType[tele.getPhoneType()]); // 網路類型
statusValues.add(tele.getCellLocation() != null
? tele.getCellLocation().toString() : "未知"); // 所在基站位置
statusValues.add(tele.getSimCountryIso()); // SIM 卡國別
statusValues.add(tele.getSimSerialNumber()); // SIM 卡序號
statusValues.add(simType[tele.getSimState()]); // SIM 卡狀態
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
for (int i = 0; i < statusValues.size(); i++) {
HashMap<String, Object> hasp = new HashMap<String, Object>();
hasp.put("name", statusName[i]);
hasp.put("values", statusValues.get(i));
list.add(hasp);
}
SimpleAdapter simple = new SimpleAdapter(this, list, R.layout.items,
new String[] { "name", "values" },
new int[] { R.id.text1, R.id.text2 });
list1.setAdapter(simple);
// 建立來電狀態監聽器
PhoneStateListener listener = new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_IDLE: // 無任何狀態
break;
case TelephonyManager.CALL_STATE_OFFHOOK: // 通話中
break;
case TelephonyManager.CALL_STATE_RINGING: // 來電響鈴
OutputStream os = null;
try {
os = openFileOutput("phoneList", MODE_APPEND);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
PrintStream ps = new PrintStream(os);
// 把來電號碼連同時間記錄到檔案
ps.println(new Date() + "來電:" + incomingNumber);
ps.close();
break;
default:
break;
}
super.onCallStateChanged(state, incomingNumber);
}
};
tele.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
實作時有幾個容易踩到的細節值得留意:getCellLocation() 在部分機型與模擬器上會回傳 null,所以一定要做防呆;getDeviceSoftwareVersion() 並非每家廠商都有實作;而 simState、phoneType 這類回傳的是整數索引,必須與 string-array 的宣告順序完全對齊,否則很容易拿到錯誤文字甚至引發陣列越界。另外 READ_PHONE_STATE 屬於敏感權限,Android 6.0 以後需要在執行期動態向使用者請求,不能只寫在 Manifest 裡就算完成。
要讓應用具備讀取聯絡人與寄送簡訊的能力,權限宣告如下:
<uses-permission android:name="android.permission.READ_CONTACTS"/> <uses-permission android:name="android.permission.SEND_SMS"/>
群發的整體流程是:先從系統聯絡人取出號碼清單讓使用者勾選,再把勾選結果放進集合,按下發送鈕後逐一呼叫 sendTextMessage。完整程式碼:
package com.android.xiong.groupsend;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.telephony.SmsManager;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
private Button bt1, bt2;
private EditText ed1, ed2;
private SmsManager sManger;
List<String> sendList = new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt1 = (Button) findViewById(R.id.bt1);
bt2 = (Button) findViewById(R.id.bt2);
ed1 = (EditText) findViewById(R.id.ed1);
ed2 = (EditText) findViewById(R.id.ed2);
// 取得 SmsManager 單例
sManger = SmsManager.getDefault();
// 發送簡訊
bt1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
for (String send : sendList) {
PendingIntent ped = PendingIntent.getActivity(
MainActivity.this, 0, new Intent(), 0);
sManger.sendTextMessage(send, null,
ed2.getText().toString(), ped, null);
}
Toast.makeText(MainActivity.this, "短信群發完",
Toast.LENGTH_LONG).show();
}
});
// 選擇聯絡人
bt2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
final Cursor cursor = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, null, null, null);
BaseAdapter adapter = new BaseAdapter() {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
cursor.moveToPosition(position);
CheckBox rb = new CheckBox(MainActivity.this);
// 取出號碼並去掉中間的連字號與空白
String number = cursor.getString(cursor.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER))
.replace("-", "");
rb.setText(number);
// 已在發送名單中的號碼預設勾選
if (sendList.contains(number)) {
rb.setChecked(true);
}
return rb;
}
@Override
public long getItemId(int position) { return position; }
@Override
public Object getItem(int position) { return position; }
@Override
public int getCount() { return cursor.getCount(); }
};
View selectView = getLayoutInflater().inflate(R.layout.item, null);
final ListView listView =
(ListView) selectView.findViewById(R.id.list1);
listView.setAdapter(adapter);
new AlertDialog.Builder(MainActivity.this)
.setView(selectView)
.setPositiveButton("確定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
sendList.clear();
// 走訪每一個列表項,收集被勾選的號碼
for (int i = 0; i < listView.getCount(); i++) {
CheckBox checkBox = (CheckBox) listView.getChildAt(i);
if (checkBox.isChecked()) {
sendList.add(checkBox.getText().toString());
ed1.append(checkBox.getText().toString() + ",");
}
}
}
}).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
主要版面配置,上方兩個輸入框分別放收件人清單與簡訊內容,下方兩顆按鈕負責取聯絡人與送出:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<EditText android:id="@+id/ed1"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<EditText android:id="@+id/ed2"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button android:id="@+id/bt2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="獲取聯系人"/>
<Button android:id="@+id/bt1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="發送信息"/>
</LinearLayout>
聯絡人選擇用的彈窗,內部就是一個 ListView:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView android:id="@+id/list1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
最後提醒兩件事:一是 sendTextMessage 只回傳 PendingIntent,真正的成功或失敗結果要靠廣播接收器取得,正式專案中建議補上狀態監聽;二是大量群發容易觸發電信業者的反垃圾簡訊機制, 실務上更常改走行動簡訊平台或第三方推播服務。
用 JNI 打造 Android 守護進程:fork 兩次才能逃過 5.0 的進程組清理
要開發一個必須長期待在後台的 App,說是惡夢一點也不誇張。你不只要應付各家廠商深度客製的 ROM,還得跟市面上琳瑯滿目的安全管家周旋。方法試了一圈,效果始終不理想:任務
用 ListView 輕鬆實作 Android 時間軸
昨天群裡有人討論到時間軸效果,我一開始還沒碰過,心想應該很講究,研究之後才發現表面看似花俏,其實用 ListView 就能搞定,並沒有什麼新鮮的技術。 廢話不多說,直接看
應用內更換用戶頭像的完整流程:相機、相冊、裁剪與圓形呈現
「點一下頭像換照片」看起來是個小功能,實際卻串起了五個環節:彈出選擇視窗、區分相機與相冊兩條取圖路徑、把兩條路徑的結果統一導向裁剪、接收裁剪後的 Bitmap、最後用圓形
用 UEventObserver 監聽 Android 設備的 USB 插拔事件
一、問題的由來 最近參與的一個專案需要通過 USB 完成 PC 端與 Android 端之間的數據傳輸。按照常規思路,我本想直接用官方 API 監聽 USB 的插拔狀態,