我知道这是一个被问到的问题。通过使用广播接收器和使用 android.intent.action.PHONE_STATE
在接收器标签中,您可以了解手机的操作。但是如何识别是来电还是去电呢?
这是我的代码
@Override
public void onReceive(Context context, Intent intent)
{
this.context = context ;
System.out.println(":::called onReceiver:::");
TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
telephony.listen(phoneCallListener, PhoneStateListener.LISTEN_CALL_STATE);
}
private final PhoneStateListener phoneCallListener = new PhoneStateListener()
{
@Override
public void onCallStateChanged(int state, String incomingNumber)
{
switch(state)
{
case TelephonyManager.CALL_STATE_RINGING:
isRinging = true;
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
if (isRinging)
{
hasAttended = true ;
isRinging = false;
}
break;
case TelephonyManager.CALL_STATE_IDLE:
if (hasAttended)
{
isCallEnded = true ;
hasAttended = false;
}
break;
}
if(isCallEnded)
{
isCallEnded=false;
Intent callIntent = new Intent(context.getApplicationContext(),MyActivity.class);
callIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(callIntent);
}
super.onCallStateChanged(state, incomingNumber);
}
};
这里每次创建一个phoneCallListener对象,每次将onCallStateChanged的调用率增加一..