来电广播接收器不工作

时间:2014-11-17 15:35:34

标签: android broadcastreceiver telephonymanager phone-state-listener incoming-call

我面临一个奇怪的问题。我无法使用广播接收器接听来电。我已经对我的清单文件进行了两次和三次检查以获得必要的权限一切似乎都没问题,但不知道为什么,接收器不工作。请问有人可以说明原因吗?任何帮助,将不胜感激! 这是我的骨架代码:

主:

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;
        }
    }
}

清单:

 <?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>

1 个答案:

答案 0 :(得分:1)

使用时应该在您的活动中使用registerReceiver(Receiver, Filter);,因为Selvin说要启动您的BroadCastReceiver以及它的所有内容。