各种手机状态分化

时间:2017-07-04 10:59:43

标签: java android phone-call

如何区分来电和去电? 对于这两种情况,移动设备处于摘机状态,但是对于来电,它处于振铃状态,然后进入摘机状态,

我尝试了这段代码,但它没有有效工作,因为振铃变量总是假的。 还有另一个问题,我怎样才能得到拨出的电话号码..提前感谢

public class states extends BroadcastReceiver {
boolean Ringing = false;

public void onReceive(Context context, Intent intent) {
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);

if (state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_RINGING)) {
 Toast.makeText(context, "Ringing", Toast.LENGTH_SHORT).show();
        Ringing = true ;
 }
    else if (state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
        if (Ringing) {
            // do nothing
        }else{
           // do something
}
 else if (state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_IDLE)) {
        Ringing = false ;
    }
}
}

这些是我的权限

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />


  <receiver android:name=".states">
        <intent-filter>
            <action android:name="android.intent.action.PHONE_STATE" />
            <action android:name="android.intent.action.NEW_OUTGOING_CALL" />
        </intent-filter>
    </receiver>

1 个答案:

答案 0 :(得分:0)

为了区分传入和传出呼叫,您可以使用广播接收器: 在接收器中添加<receiver android:name=".IncomingCallReceiver" > <intent-filter > <action android:name="android.intent.action.PHONE_STATE" /> <action android:name="android.intent.action.NEW_OUTGOING_CALL" /> </intent-filter> </receiver> 并在onReceive()方法中处理它。

public void onReceive(Context context, Intent intent)
{
    String state=intent.getStringExtra(TelephonyManager.EXTRA_STATE);

    if(state==null)
    {
        //Outgoing call
        String number=intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
        Log.i("tag","Outgoing number : "+number);
    }
    else if (state.equals(TelephonyManager.EXTRA_STATE_RINGING))
    {
        //Incoming call
        String number = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
        Log.i("tag","Incoming number : "+number);
    }
}

获取传出号码

{{1}}