在我的应用程序中,我想为有人接听电话时的状态记录日志。 switch语句上的getState()必须返回正确的调用状态,但始终返回零。这是我的onRecieve()方法:
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)){
incomingFlag = false;
String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
Log.i(TAG, "call OUT:"+phoneNumber);
TelephonyManager tm =
(TelephonyManager)context.getSystemService(Service.TELEPHONY_SERVICE);
Log.e("log state", String.valueOf(tm.getCallState()));
switch (tm.getCallState()) {
case TelephonyManager.CALL_STATE_RINGING:
incomingFlag = true;
incoming_number = intent.getStringExtra("incoming_number");
Log.i(TAG, "RINGING :"+ incoming_number);
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
if(incomingFlag){
Log.i(TAG, "incoming ACCEPT :"+ incoming_number);
}
break;
case TelephonyManager.CALL_STATE_IDLE:
if(incomingFlag){
Log.i(TAG, "incoming IDLE");
}
break;
default:
Log.e("ds","Error");
}
}
清单文件:
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".BroadCast" >
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.NEW_OUTGOING_CALL"/>
</intent-filter>
</receiver>
权限:
<uses-permission android:name="android.permission.CALL_PHONE"/>
<uses-permission android:name = "android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/>
上面提到的onCreate()方法位于一个我创建的名为BroadCast的单独类中,我通过创建它的新实例来调用它。
如果需要更多详细信息,请告诉我。
答案 0 :(得分:0)
尝试使用BroadcastReceiver处理来电。 在您的onResume中,设置接收器
IntentFilter filter2 = new IntentFilter(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
filter2.setPriority(99999);
this.registerReceiver(incomingCallReceiver, filter2);
和处理它,例如
BroadcastReceiver incomingCallReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final Bundle bundle = intent.getExtras();
if (bundle == null) return;
// Incoming call
// Get the state
String state = bundle.getString(TelephonyManager.EXTRA_STATE);
// Process the states
if ((state != null) && (state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_RINGING))) {
// Ringing State
}
if ((state != null) && (state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_IDLE))) {
// Idle State
}
if ((state != null) && (state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_OFFHOOK))) {
// Offhook State
}
}
};