创建一个新类,比如说MyPhoneReceiver,从 BroadcastReceiver 扩展它,并实现 onReceive 方法。
public class MyPhoneReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent){
String phoneNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
}
}
在另一个类中,假设是onCreate 方法中的MainActivity.class 。例如。
IntentFilter filter = new IntentFilter("android.intent.action.NEW_OUTGOING_CALL");
MyPhoneReceiver myPhoneReceiver = new MyPhoneReceiver();
registerReceiver(myPhoneReceiver,filter);
在AndroidManifest.xml
<receiver
android:name=".MyPhoneReceiver">
<intent-filter>
<action android:name="android.intent.action.NEW_OUTGOING_CALL" />
</intent-filter>
</receiver>
并且还在 AndroidManifest.xml 中添加:
<uses-permission
android:name="android.permission.PROCESS_OUTGOING_CALLS">
</uses-permission>