在调试下面的代码时,BroadcastReceiverCustom正在进行中 调用,但PhoneStateListenerCustom不是。
现在我只在BroadcastReceiverCustom中执行必要的操作, 但也许不是最好的去处。 有什么建议为什么没有调用PhoneStateListener? 已经花了很多时间可能的原因,不知道? 具有正确权限的清单文件都是正确的。 我没有看到运行时异常。
BroadcastReceiverCustom.java
public class BroadcastReceiverCustom extends BroadcastReceiver {
private static final String TAG = "BroadcastReceiverCustom";
@Override
public void onReceive(Context context, Intent intent) {
Log.v(TAG, "WE ARE INSIDE!!!!!!!!!!!");
TelephonyManager telephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
PhoneStateListenerCustom phoneStateListenerCustom = new PhoneStateListenerCustom();
telephony.listen(phoneStateListenerCustom, PhoneStateListener.LISTEN_CALL_STATE);
}
}
PhoneStateListenerCustom.java
public class PhoneStateListenerCustom extends PhoneStateListener {
private static final String TAG = "PhoneStateListenerCustom";
public void onCallStateChange(int state, String incomingNumber){
Log.v(TAG, "WE ARE INSIDE!!!!!!!!!!!");
switch(state){
case TelephonyManager.CALL_STATE_RINGING:
Log.d(TAG, "RINGING");
break;
}
super.onCallStateChanged(state, incomingNumber);
}
}
清单文件
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<receiver android:name=".BroadcastReceiverCustom">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
答案 0 :(得分:4)
您不应在BroadcastReceiver中实例化TelephonyManager和PhoneStateListener。这是一些示例代码:
在活动中:
EndCallListener callListener = new EndCallListener;
TelephonyManager mTM = (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
mTM.listen(callListener, PhoneStateListener.LISTEN_CALL_STATE);
private class EndCallListener extends PhoneStateListener {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
if(TelephonyManager.CALL_STATE_RINGING == state) {
Log.i(LOG_TAG + "Listener", "RINGING, number: " + incomingNumber);
}
if(TelephonyManager.CALL_STATE_OFFHOOK == state) {
Log.i(LOG_TAG + "Listener", "OFFHOOK, number: " + incomingNumber);
}
if(TelephonyManager.CALL_STATE_IDLE == state) {
Log.i(LOG_TAG + "Listener", "IDLE, number: " + incomingNumber);
}
}
}
答案 1 :(得分:1)
尝试在@Override
方法之前添加onCallStateChange
答案 2 :(得分:0)
我只想补充一下this答案中提到的Vairavan,在引用PhoneStateListener的方式方面发生了内部变化。现在,它保存在一个弱引用中,这意味着一旦该方法返回,PhoneStateListener实例就可以进行垃圾回收。因此,您应该将引用保存在一个类中,该类将在您希望侦听回调的生命周期中持续存在,例如Service
,Application
或{{1}}类。