广播接收器android中的上下文

时间:2015-04-03 22:25:09

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

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

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

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