广播接收器中的上下文 android

context in broadcast receiver android

我试图在我的应用程序中监听传入呼叫,因此我为此创建了一个广播接收器,但是当我在 toast 中传递上下文时它显示错误。谁能弄清楚我做错了什么? 这是我的代码:

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

您可以使用您的 MainActivity Context 实例。因为 Activity class 扩展(间接)Context。用这个替换你的 Toast 行:

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

这是我所做的(非常感谢@egor),尽管我花了一些时间才理解。这是代码:

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