1. 程式人生 > >Android-實現對指定電話的簡訊攔截和來電攔截

Android-實現對指定電話的簡訊攔截和來電攔截

/**
 * 用TelSmsBlackService來控制廣播監聽(電話,sms)。
 * 
 * @author lmk
 * 
 */
public class TelSmsBlackService extends Service {

	private SmsBroadcastReceiver smsBroadcastReceiver;
	private BlackDao blackDao;
	private TelephonyManager tm;
	private PhoneStateListener listener;

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	// 簡訊廣播
	private class SmsBroadcastReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// 簡訊廣播監聽要乾的事情
			//__①__
		}
	}

	@Override
	public void onCreate() {
		blackDao = new BlackDao(getApplicationContext());
		// 建立簡訊的廣播監聽物件
		smsBroadcastReceiver = new SmsBroadcastReceiver();
		// 簡訊廣播意圖
		IntentFilter filter = new IntentFilter(
				"android.provider.Telephony.SMS_RECEIVED");
		// 設定最高級別
		filter.setPriority(Integer.MAX_VALUE);
		registerReceiver(smsBroadcastReceiver, filter);

		// 開啟電話的監聽

		tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
		listener = new PhoneStateListener() {

			@Override
			public void onCallStateChanged(int state,
					final String incomingNumber) {
				// state 電話的狀態 incomingNumber 打進來的號碼
				switch (state) {
				case TelephonyManager.CALL_STATE_IDLE:// 結束通話的狀態,空閒的狀態
					System.out.println("CALL_STATE_IDLE");
					break;
				case TelephonyManager.CALL_STATE_RINGING:// 響鈴狀態
					System.out.println("CALL_STATE_RINGING");
					// 判斷是否是黑名單號碼
					//__②__
					break;
				case TelephonyManager.CALL_STATE_OFFHOOK:// 通話的狀態
					System.out.println("CALL_STATE_OFFHOOK");
					break;

				default:
					break;
				}
				super.onCallStateChanged(state, incomingNumber);
			}

		};
		// 註冊電話的監聽
		tm.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
		super.onCreate();
	}

	@Override
	public void onDestroy() {
		// 關閉簡訊的廣播監聽
		unregisterReceiver(smsBroadcastReceiver);
		// 關閉電話的監聽
		tm.listen(listener, PhoneStateListener.LISTEN_NONE);
		super.onDestroy();
	}
}

當然了,service是要在清單中配置的,如下: