我补充说,这是我的清单文件 –
<receiver android:name=".ServiceReceiver"> <intent-filter> <action android:name="android.intent.action.PHONE_STATE" /> </intent-filter> </receiver> </application> <uses-permission android:name="android.permission.READ_PHONE_STATE"> </uses-permission>
那么我的服务类就是这样 –
public class ServiceReceiver extends BroadcastReceiver { @Override public void onReceive(Context context,Intent intent) { MyPhoneStateListener phoneListener = new MyPhoneStateListener(); TelephonyManager telephony = (TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE); telephony.listen(phoneListener,PhoneStateListener.LISTEN_CALL_STATE); }
}
我的PhoneStateListener是 –
public class MyPhoneStateListener extends PhoneStateListener { public void onCallStateChanged(int state,String incomingNumber) { Log.i("telephony-example","State changed: " + stateName(state)); } String stateName(int state) { switch (state) { case TelephonyManager.CALL_STATE_IDLE: Log.d("DEBUG","***********IDLE********"); return "Idle"; case TelephonyManager.CALL_STATE_OFFHOOK: Log.d("DEBUG","***********OFFHOOK********"); return "Off hook"; case TelephonyManager.CALL_STATE_RINGING: Log.d("DEBUG","***********RINGING********"); return "Ringing"; } return Integer.toString(state); }
}
我可以看到IDLE状态.
但是当我打电话给我没有铃声状态.为什么?
解决方法
我想你正在混合两种方法来获取电话状态.如果您使用意向过滤器和广播接收器,则在接收器中不需要调用TelephonyManager的listen().只需检查收到的意图如下:
public void onReceive(Context context,Intent intent) { String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE); String number = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER); if (TelephonyManager.EXTRA_STATE_RINGING.equals(state)) { Log.d("MPR","Its Ringing [" + number + "]"); } if (TelephonyManager.EXTRA_STATE_IDLE.equals(state)) { Log.d("MPR","Its Idle"); } if (TelephonyManager.EXTRA_STATE_OFFHOOK.equals(state)) { Log.d("MPR","Its OffHook"); } }