我遇到了一个奇怪的问题。我无法使用广播接收器接听来电。我已经双重和三次检查我的 list 文件以获得必要的权限。一切似乎都很好,但不知道为什么,接收器不工作。有人可以提出这个的原因吗?任何帮助,将不胜感激! 这是我的框架代码:
主要内容:
package com.calllistener;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
public class MainActivity extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
MyPhoneStateListener phoneListener=new MyPhoneStateListener(context);
TelephonyManager telephony = (TelephonyManager)
context.getSystemService(Context.TELEPHONY_SERVICE);
telephony.listen(phoneListener,PhoneStateListener.LISTEN_CALL_STATE);
}
}
MyPhoneStateListener
类:
package com.calllistener;
import android.content.Context;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;
public class MyPhoneStateListener extends PhoneStateListener {
Context ctx;
public MyPhoneStateListener (Context ctx) {
super();
this.ctx=ctx;
}
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
Log.d("DEBUG", "IDLE");
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
Log.d("DEBUG", "OFFHOOK");
break;
case TelephonyManager.CALL_STATE_RINGING:
Toast.makeText(ctx, "Ringing", Toast.LENGTH_LONG).show();
Log.d("DEBUG", "RINGING");
break;
}
}
}
list :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.calllistener"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="Call listener" >
<receiver android:name="MainActivity" >
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
</application>
</manifest>
最佳答案
正如 Selvin 所说,在您的 Activity 中使用应该使用 registerReceiver(Receiver, Filter);
来初始化您的 BroadCastReceiver,仅此而已。
关于android - 来电广播接收器不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26976188/