android - 广播接收器android中的上下文

标签 android broadcastreceiver android-context

我试图在我的应用程序中监听传入调用,因此我为此创建了一个广播接收器,但是当我在 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();
        }
    }}}

最佳答案

这是我所做的(非常感谢@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();
            }
        }
    }
    }

关于android - 广播接收器android中的上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29440487/

相关文章:

android - 如何使用 MediaCodec 将位图编码为视频?

android - 使用 LocalBroadcastManager 注册 BroadcastReceiver 时未调用 onReceive

android - 充气 View 的差异

android - 这两个上下文代码有什么不同?

android - API Level 21之前如何在代码中获取主题drawable?

Android 内置相机编码器 VS FFMPEG --- 速度

android - 是否可以将两个(正在积极开发的)Android 应用程序模块合并到同一个 Android Studio 项目中?

java - 如何一次响应多个广播? Jelly Bean LG 为一项 Activity 发送两次广播

android - 从 web View 中获取 ID 值作为字符串

android - 从服务到 Activity 的 sendBroadcast() 处出现 NullPointerException