android怎么实现自动接听
添加权限
<uses-permission android:name="android.permission.CALL_PHONE"/>
<uses-permission android:name="android.permission.MODIFY_PHONE_STATE"/>
package com.xiawenquan.pic.demo.utils;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.TextView;
public class Auto_accept_callActivity extends Activity {
TelephonyManager manager;
String result = "监听电话状态:/n";
TextView textView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
manager = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE);
// 获取电话服务
manager.listen(new MyPhoneStateListener(),
PhoneStateListener.LISTEN_CALL_STATE);
// 手动注册对PhoneStateListener中的listen_call_state状态进行监听
}
public void auto_accept_call() {
Intent localIntent1 = new Intent(Intent.ACTION_HEADSET_PLUG);
localIntent1.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
localIntent1.putExtra("state", 1);
localIntent1.putExtra("microphone", 1);
localIntent1.putExtra("name", "Headset");
this.sendOrderedBroadcast(localIntent1,
"android.permission.CALL_PRIVILEGED");
Intent localIntent2 = new Intent(Intent.ACTION_MEDIA_BUTTON);
KeyEvent localKeyEvent1 = new KeyEvent(KeyEvent.ACTION_DOWN,
KeyEvent.KEYCODE_HEADSETHOOK);
localIntent2.putExtra("android.intent.extra.KEY_EVENT", localKeyEvent1);
this.sendOrderedBroadcast(localIntent2,
"android.permission.CALL_PRIVILEGED");
Intent localIntent3 = new Intent(Intent.ACTION_MEDIA_BUTTON);
KeyEvent localKeyEvent2 = new KeyEvent(KeyEvent.ACTION_UP,
KeyEvent.KEYCODE_HEADSETHOOK);
localIntent3.putExtra("android.intent.extra.KEY_EVENT", localKeyEvent2);
this.sendOrderedBroadcast(localIntent3,
"android.permission.CALL_PRIVILEGED");
Intent localIntent4 = new Intent(Intent.ACTION_HEADSET_PLUG);
localIntent4.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
localIntent4.putExtra("state", 0);
localIntent4.putExtra("microphone", 1);
localIntent4.putExtra("name", "Headset");
this.sendOrderedBroadcast(localIntent4,
"android.permission.CALL_PRIVILEGED");
}
/***
* 继承PhoneStateListener类,我们可以重新其内部的各种监听方法 然后通过手机状态改变时,系统自动触发这些方法来实现我们想要的功能
*/
class MyPhoneStateListener extends PhoneStateListener {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
Log.v("log", "oncall state changed");
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
result += " 手机空闲 ";
break;
case TelephonyManager.CALL_STATE_RINGING:
result += " 手机铃响:" + incomingNumber;
Log.v("log", result);
Auto_accept_callActivity.this.auto_accept_call();
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
result += " 电话挂起 ";
default:
break;
}
super.onCallStateChanged(state, incomingNumber);
}
}
}