簡訊攔截的實現主要是使用了廣播接收者來實現。 BroadcastReceiver 廣播接收者 必須指定要接收的廣播類型。必須明確的指定action 廣播:事件。普通廣播: 是非同步。會廣播接收者同時接收,不能被中斷sendBroadcast()有序廣播: 是同步的。會根據廣播接收的優先順序進行接收,是可以中斷 簡訊到來廣播 sendOrderBroadcast()priority的範圍是:-1000 ~ 1000如果有序廣播明確的指定了廣播接收者,他是無法被中斷的。 代碼實現如下: 1、MainActivity [java] package com.njupt.t4; import android.os.Bundle; import android.app.Activity; import android.content.IntentFilter; import android.view.Menu; public class MainActivity extends Activity { private SmsReceiver receiver = new SmsReceiver(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); IntentFilter filter = new IntentFilter(); filter.setPriority(997); filter.addAction("android.provider.Telephony.SMS_RECEIVED"); registerReceiver(receiver,filter); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(receiver); } } 2、SmsReceiver [java] package com.njupt.t4; import java.text.SimpleDateFormat; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.telephony.SmsManager; import android.telephony.SmsMessage; public class SmsReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { System.out.println("章澤天是我老婆,老婆我成功了...."); Bundle bundle = intent.getExtras(); Object[] objects = (Object[]) bundle.get("pdus"); for(Object obj : objects){ SmsMessage smsMessage = SmsMessage.createFromPdu((byte[])obj); String body = smsMessage.getDisplayMessageBody(); String address = smsMessage.getDisplayOriginatingAddress(); long date = smsMessage.getTimestampMillis(); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); String dateStr = format.format(date); System.out.println(address +" 於 " + dateStr + "給你發了以下內容: " + body); if(address.equals("5558")){ abortBroadcast(); SmsManager smsManager = SmsManager.getDefault(); smsManager.sendTextMessage("5556",null,address +" 於 " + dateStr + "給你發了以下內容: " + body,null,null); } } } } 3、AndroidManifest.xml 需要在資訊清單檔中註冊上一下許可權。(如果不註冊是不會成功地攔截到簡訊的,在logcat中會以Warn的 層級告訴你你沒有相應的許可權...) [html] <uses-permission android:name="android.permission.RECEIVE_SMS"/> <uses-permission android:name="android.permission.SEND_SMS"/> <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/> -----------------------------------------------------其實上面就是使用了代碼的方式來註冊BroadcastReceiver------------- 其實還可以在AndroidManifest.xml註冊receiver這個組件(但是我採用這個方式總是會出現記憶體泄露的錯誤,所以下面的代碼僅供參考) [html] <receiver android:name=".SmsReceiver"> <intent-filter android:priority="1000"> <action android:name="android.provider.Telephony.SMS_RECEIVED"/> </intent-filter> </receiver>