2015-04-03 20 views
1

我想在我的應用程序中偵聽傳入呼叫,所以我創建了一個相同的廣播接收器,但是當我在傳遞中傳遞上下文時,它顯示一個錯誤。任何人都可以判斷我做錯了什麼? 這裏是我的代碼:在廣播接收機中的上下文android

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

你在哪裏初始化pcontext?你會得到什麼錯誤? – Egor 2015-04-03 22:33:00

+0

多數民衆贊成多數民衆黨我想知道我應該使一個本地上下文名稱作爲pcontext – user3570390 2015-04-03 22:35:31

+0

你有onReceive()中的上下文的引用,只是通過它的構造函數傳遞給MyPhoneStateListener並使用它。 – Egor 2015-04-03 22:36:49

回答

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

你可以「接受」你自己的答案將問題標記爲已解決。 – 2015-05-30 09:48:13

+0

事實上,使用「全局變量」來放置上下文並將其返回onCallStateChanged保存我的一天!非常感謝! – Peter 2016-08-25 02:00:09

0

您可以使用MainActivityContext實例。因爲Activity類延伸(間接)Context。這種替換您Toast行:

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

無法解析方法maketext(MainActivity.this ...............) – user3570390 2015-04-03 23:00:49

+0

我得到這個錯誤,當我用你的土司行 – user3570390 2015-04-04 00:08:39