2

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

主要的:

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

1 回答 1

1

正如 Selvin 所说,使用应该registerReceiver(Receiver, Filter);在您的活动中使用来初始化您的 BroadCastReceiver,仅此而已。

于 2014-11-17T16:19:35.333 回答