gauravmehra
gauravmehra

Reputation: 169

context in broadcast receiver android

I am trying to listen incoming call in my application, so I created a broadcast receiver for the same, but when I pass context in toast it shows an error. Can anybody figure what I am doing wrong? Here is my code:

public class MainActivity extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        TelephonyManager tmngr= (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
        MyPhoneStateListener PhoneListener = new MyPhoneStateListener();
        tmngr.listen(PhoneListener,PhoneStateListener.LISTEN_CALL_STATE);
    }

    private class MyPhoneStateListener extends PhoneStateListener {
        public void onCallStateChanged(int state,String incoming)
        {
            if (state == 1) {

                String msg = "New Phone Call Event. Incomming Number : "+incoming;
                int duration = Toast.LENGTH_LONG;
               //i am getting error here( context )
                Toast toast = Toast.makeText(context, msg, duration);
                toast.show();
        }
    }}}

Upvotes: 1

Views: 1374

Answers (2)

gauravmehra
gauravmehra

Reputation: 169

Here's what I did (well thanks to @egor) though it took some time to understand. Here is the code:

  public class MainActivity extends BroadcastReceiver {

        Context pcontext;
        @Override
        public void onReceive(Context context, Intent intent) {

       TelephonyManager tmngr= (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
       //referencing the context           
       pcontext=context;
       //passing it to phonelistener           
       MyPhoneStateListener PhoneListener = new 
       MyPhoneStateListener(pcontext);
            tmngr.listen(PhoneListener,PhoneStateListener.LISTEN_CALL_STATE);


        }

        private class MyPhoneStateListener extends PhoneStateListener {


            public MyPhoneStateListener(Context pcontext) {

            }

            public void onCallStateChanged(int state,String incoming)
            {
                if (state == 1) {

                    String msg = "New Phone Call Event. Incomming Number : "+incoming;
                    int duration = Toast.LENGTH_LONG;
                   // Context pcontext;
                    Toast toast;
                    toast = Toast.makeText(pcontext, msg, duration);
                    toast.show();
            }
        }
    }
    }

Upvotes: 2

joao2fast4u
joao2fast4u

Reputation: 6892

You can use your MainActivity Context instance. Because Activity class extends (indirectly) Context. Replace your Toast line with this:

Toast toast = Toast.makeText(MainActivity.this, msg, duration);

Upvotes: 0

Related Questions