广播员被称为,但不称呼
-
11-10-2019 - |
题
在下面的代码调试时,broadcaseivercustom被称为,但phonEstateListEnercustom却不是。
就目前而言,我和仅在Broadcastreceivercustom中采取的行动,但Maynot不是最好的场所。有什么建议为什么不称呼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>
解决方案
您不应在广播员中实例化电话管理器和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);
}
}
}
其他提示
尝试添加 @Override
之前 onCallStateChange
方法
我只是想补充一下Vairavan 这个 答案是,引用phonEstateListener的内部变化。它现在以弱参考来持有,这意味着一旦方法返回,phonEstateListener实例将用于垃圾收集。因此,您应该将参考文献保留在课程中,该课程将在您期望收听回调的一生中坚持下去,例如 Activity
, Service
, , 或者 Application
课程。
不隶属于 StackOverflow