public class PhoneBroadcast extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Log.e("onReceive", "onReceive action" + intent.getAction()); if (intent.getAction().equals("test")) { Log.e("test", "test"); TelephonyManager tm = (TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE); PhoneStateListener listener = new PhoneStateListener() { @Override public void onCallStateChanged(int state, String incomingNumber) { if (state != TelephonyManager.CALL_STATE_IDLE) { Log.e("pause", "pause"); } else { Log.e("start", "start"); } super.onCallStateChanged(state, incomingNumber); } }; // 监听电话的状态 tm.listen(listener, PhoneStateListener.LISTEN_CALL_STATE); } } }
MainActivity
public class MainActivity extends Activity {
private PhoneBroadcast phone = new PhoneBroadcast();
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public void onResume(){
super.onResume();
IntentFilter filter = new IntentFilter();
filter.addAction("test");
registerReceiver(phone, filter);
Intent intent1 = new Intent("test");
sendBroadcast(intent1);
}
@Override
public void onPause(){
super.onPause();
unregisterReceiver(phone);
}
}
AndroidMenifest.xml
<receiver android:name="com.example.broadcasttest.PhoneBroadcast" > </receiver>
权限
<uses-permission android:name="android.permission.READ_PHONE_STATE" >
</uses-permission>
<uses-permission android:name="android.permission.CALL_PHONE" >
</uses-permission>