Android4 自动接电话,急求Android5和Android6 接电话的Demo

开发工具:eclipse

MainActivity.java

自动生成后不做操作。

AutoAnswerReceiver.java

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.telephony.TelephonyManager;

public class AutoAnswerReceiver extends BroadcastReceiver {
	
	@Override
	public void onReceive(Context context, Intent intent) {

		String phone_state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);

		if (phone_state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
			AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
			if (am.getMode() == AudioManager.MODE_IN_CALL) {
				return;
			}
			context.startService(new Intent(context, AutoAnswerIntentService.class));
		}		
	}
}

AutoAnswerIntentService,java

public class AutoAnswerIntentService extends IntentService {

	public AutoAnswerIntentService() {
		super("AutoAnswerIntentService");
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		Context context = getBaseContext();

		 try {
		 Thread.sleep(5000);   //answer the ringing call after 5 seconds
		 } catch (InterruptedException e) {
		
		 }

		TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
		if (tm.getCallState() != TelephonyManager.CALL_STATE_RINGING) {
			return;
		}

		try {
			answerPhoneAidl(context);
		} catch (Exception e) {
			e.printStackTrace();
			Log.d("AutoAnswer", "Error trying to answer using telephony service.  Falling back to headset.");
			answerPhoneHeadsethook(context);
		}
		
		return;
	}

	private void answerPhoneHeadsethook(Context context) {

		Intent buttonDown = new Intent(Intent.ACTION_MEDIA_BUTTON);
		buttonDown.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_HEADSETHOOK));
		context.sendOrderedBroadcast(buttonDown, "android.permission.CALL_PRIVILEGED");

		Intent buttonUp = new Intent(Intent.ACTION_MEDIA_BUTTON);
		buttonUp.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_HEADSETHOOK));
		context.sendOrderedBroadcast(buttonUp, "android.permission.CALL_PRIVILEGED");
	}

	@SuppressWarnings("unchecked")
	private void answerPhoneAidl(Context context) throws Exception {

		TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
		Class c = Class.forName(tm.getClass().getName());
		Method m = c.getDeclaredMethod("getITelephony");
		m.setAccessible(true);
		ITelephony telephonyService;
		telephonyService = (ITelephony) m.invoke(tm);
		telephonyService.answerRingingCall();
	}
}

AndroidManifest.xml

权限:


 
receiver:

	android:name=".AutoAnswerReceiver"
	android:enabled="true" >
	
		
	

Service

 


给个下载链接:http://download.csdn.net/detail/kylsen/9674393

这个Demo打开后就能在响铃后5秒自动接电话,目前实测能在Android 4.3和Android 4.4机上实现,但是Android 5以上的都不行,希望有Android 5或Android 6接电话的Demo,能和大家一起分享,我邮箱[email protected]


你可能感兴趣的:(Android4 自动接电话,急求Android5和Android6 接电话的Demo)