Android拨打接听电话自动免提

时间:2021-10-31 18:51:17
权限:
  <uses-permission android:name="android.permission.READ_PHONE_STATE"/>  
    <uses-permission android:name="android.permission.MODIFY_PHONE_STATE" />  
    <uses-permission android:name="android.permission.CALL_PHONE" />  
    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />  

public
class MainActivity extends AppCompatActivity { AudioManager audioManager; int currVolume;//当前音量 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TelephonyManager telManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); TelListner listener = new TelListner(); telManager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE); audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); } public void click(View v) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (MainActivity.this.checkSelfPermission(Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) { callPhone(); } else { // Toast.makeText(this, "没有权限", Toast.LENGTH_LONG).show(); } } else { callPhone(); } } void callPhone() { Intent callIntent = new Intent(Intent.ACTION_CALL); callIntent.setData(Uri.parse("tel:10086")); callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(callIntent); } private class TelListner extends PhoneStateListener { boolean comingPhone = false;//标识 @Override public void onCallStateChanged(int state, String incomingNumber) { switch (state) { case TelephonyManager.CALL_STATE_IDLE:/* 无任何状态 */ if (this.comingPhone) { this.comingPhone = false; setSpeekModle(false); } break; case TelephonyManager.CALL_STATE_OFFHOOK:/* 接起电话 */ this.comingPhone = true; setSpeekModle(true); break; case TelephonyManager.CALL_STATE_RINGING:/* 电话进来 */ this.comingPhone = true; setSpeekModle(true); break; } } } void setSpeekModle(boolean open) { audioManager.setMode(AudioManager.ROUTE_SPEAKER); currVolume = audioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL); //5.0以上 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION); } else { audioManager.setMode(AudioManager.MODE_IN_CALL); } if (!audioManager.isSpeakerphoneOn() && open) { Toast.makeText(MainActivity.this, "免提模式", Toast.LENGTH_LONG).show(); audioManager.setSpeakerphoneOn(true);//开启免提 audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL, audioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL), AudioManager.STREAM_VOICE_CALL); } else if (audioManager.isSpeakerphoneOn() && open) { audioManager.setSpeakerphoneOn(false); audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL, currVolume, AudioManager.STREAM_VOICE_CALL); } } }

ps:此方式在华为手机上不兼容