package com.tsgame.tsgame_niuniu.receiver;


import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.tagmae.tsgame_erwang.webviewActivity;

public class PhoneStateBroadCastReceiver extends BroadcastReceiver {

	private static    String TAG = "PhoneStateBroadCastReceiver";
	private static boolean mIncomingFlag = false;//
	private static String mIncomingNumber = null;//手机号码
	
	
	
	
	
	private static final int CALL_STATE_IDLE=0;//无任何状态时 
	private static final int CALL_STATE_OFFHOOK=1;//接起电话时
	private static final int CALL_STATE_RINGING=2;//电话进来时
	private static final int ACTION_NEW_OUTGOING_CALL=3;//去电
	
	/**
	 * 返回电话状态
	 * 
	 * CALL_STATE_IDLE 无任何状态时 
	 * CALL_STATE_OFFHOOK 接起电话时 
	 * CALL_STATE_RINGING 电话进来时
	 * 
	 */
	
	@Override
	public void onReceive(Context context, Intent intent) {
		int state=0;
		
		// 如果是拨打电话
		if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)) {
			
			state=ACTION_NEW_OUTGOING_CALL;
			
			mIncomingFlag = false;
			String phoneNumber = intent
					.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
			Log.i(TAG, "call OUT:" + phoneNumber);

		} else {
			// 如果是来电
			TelephonyManager tManager = (TelephonyManager) context
					.getSystemService(Service.TELEPHONY_SERVICE);
			switch (tManager.getCallState()) {
			case TelephonyManager.CALL_STATE_RINGING:
				
				state=CALL_STATE_RINGING;//响铃
				
				mIncomingNumber = intent.getStringExtra("incoming_number");
				
				Log.i(TAG, "RINGING :" + mIncomingNumber);
				break;
			case TelephonyManager.CALL_STATE_OFFHOOK://接电话
				
				 state=CALL_STATE_OFFHOOK;//
				 
				if (mIncomingFlag) {
					Log.i(TAG, "incoming ACCEPT :" + mIncomingNumber);
				}
				break;
			case TelephonyManager.CALL_STATE_IDLE:
				state=CALL_STATE_IDLE;//挂断
				
				if (mIncomingFlag) {
					Log.i(TAG, "incoming IDLE");
				}
				break;
			}

		}
		
		Intent mIntent=new Intent(webviewActivity.ACTION_INTENT_RECEIVER);
        mIntent.putExtra("message", state);
        
        context.sendBroadcast(mIntent);
		
	}
	
	
}
