android 拨打电话、 监听来电、监听呼出电话的功能实现

时间:2022-11-10 13:11:07

拨打电话:

1>创建隐式意图

2>启动Activity
3>添加拨打电话的权限

    android.permission.CALL_PHONE

监听来电:

1> 编写一个类,扩展自PhoneStateListener。
2>获取系统服务:TelephonyManager
3>调用manager.listen()方法开始监听电话状态。
4>添加权限:
    android.permission.READ_PHONE_STATE

监听呼出电话:

1>创建广播接收器接收系统广播:
   Intent.ACTION_NEW_OUTGING_CALL
2>在onReceive方法中处理广播
3>把广播接收器在清单文件中注册。
4>添加权限
  <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/>

public class MainActivity extends Activity {

private EditText edittext;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 管理监听电话
TelephonyManager manager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
manager.listen(new MyListener(), PhoneStateListener.LISTEN_CALL_STATE);// 监听来电状态
// 注册呼出电话广播
BroadcastReceiver receiver = new CallReceiver();
IntentFilter filter = new IntentFilter(Intent.ACTION_NEW_OUTGOING_CALL);
registerReceiver(receiver, filter);
}

public void doClick(View view ){
edittext = (EditText)findViewById(R.id.editText1);
// 拨打电话
Intent intent = new Intent();
intent.setAction(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:"+edittext.getText().toString()));
startActivity(intent);
}
// 此监听器用于监听电话号码状态
class MyListener extends PhoneStateListener{
public void onCallStateChanged(int state, String incomingNumber) {
super.onCallStateChanged(state, incomingNumber);
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:// 空闲时, 电话挂断时 No activity.
Log.i("tag", "CALL_STATE_IDLE");
break;
case TelephonyManager.CALL_STATE_OFFHOOK: // 接通时 At least one call exists that is dialing, active, or on hold, and no calls are ringing or waiting.
Log.i("tag", "CALL_STATE_OFFHOOK");
break;
case TelephonyManager.CALL_STATE_RINGING:// 响铃时 A new call arrived and is ringing or waiting. In the latter case, another call is already active.
Log.i("tag", "CALL_STATE_RINGING");
break;
}
}

}
// 利用系统发出的广播监听呼出电话
class CallReceiver extends BroadcastReceiver{
public void onReceive(Context context, Intent intent) {
// 获取电话号码
String number = getResultData();
if(number.equals("13888888888")){
// 使播出的电话号码为空
setResultData(null);
}
}

}


}