Incoming call broadcast receiver not working

2.6k views Asked by At

I'm facing a weird problem. I'm unable to catch incoming calls using broadcast receiver. I've double and triple checked my manifest file for necessary permissions. Everything seems okay but don't know why, the receiver is not working. Can anybody please suggest the reason for this? Any help would be appreciated! Here is my skeleton code:

Main:

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 Class:

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

Manifest:

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

There are 1 answers

1
M. Erfan Mowlaei On

Use should use registerReceiver(Receiver, Filter); in your activity as Selvin said to init your BroadCastReceiver and that's all there's to it.