Search code examples
androidtelephonymanager

Android: IncomingCallInterceptor TelephonyManager.EXTRA_STATE Toast and Vibration


I would like to bring up a Toast and vibrate when call status is Idle. I added this in the manifest file:

<receiver android:name="IncomingCallInterceptor"> 
      <intent-filter> 
         <action android:name="android.intent.action.PHONE_STATE"/> 
      </intent-filter> 
    </receiver>

And this is IncomingCallInterceptor

import android.content.BroadcastReceiver; 
import android.content.Context;
import android.content.Intent;
import android.os.Vibrator;
import android.telephony.TelephonyManager;
 import android.widget.Toast;
 import android.app.Activity;



public class IncomingCallInterceptor extends BroadcastReceiver { 
     @Override
    public void onReceive(Context context, Intent intent)
    {                                        
        String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);                        
        String msg = "Phone state changed to " + state;

        if (TelephonyManager.EXTRA_STATE_RINGING.equals(state))
       {                                  
            String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
            msg += ". Incoming number is " + incomingNumber;


        }

        Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
        if(msg == "IDLE")
        {
          ok() ;
    }

    }
    public void ok() 
    { 


        Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        v.vibrate(3000);
    }
     }
}

And I received this error:

Description Resource    Path    Location    Type
The method getSystemService(String) is undefined for the type IncomingCallInterceptor   IncomingCallInterceptor.java        line 39 Java Problem

Solution

  • Make Sure You Have Added VIBRATE permission in manifest as:

    <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="...">
        <uses-permission android:name="android.permission.VIBRATE"/>
        <application android:label="...">
            ...
        </application>
    </manifest>
    

    change Your Code as:

    public class IncomingCallInterceptor extends BroadcastReceiver { 
    private Context contextc;
     @Override
    public void onReceive(Context context, Intent intent)
    {                             
    this.contextc=context;
    //YOUR CODE HERE
    
    public void ok() 
    { 
        Vibrator v = (Vibrator)contextc.getSystemService(Context.VIBRATOR_SERVICE);
        v.vibrate(3000);
    }