2011-05-03 78 views
4

我無法在位置偵聽器中調用toast.Maketext。上下文不可用,我做錯了什麼?Android toast.makeText上下文錯誤

private LocationListener ll = new LocationListener() { 

    public void onLocationChanged(Location l) { 
     // SMSReceiver.l = l; 
     String s = ""; 
     s += "\tTime: " + l.getTime() + "\n"; 
     s += "\tLatitude: " + l.getLatitude() + "°\n"; 
     s += "\tLongitude: " + l.getLongitude() + "°\n"; 
     s += "\tAccuracy: " + l.getAccuracy() + " metres\n"; 
     s += "\tAltitude: " + l.getAltitude() + " metres\n"; 
     s += "\tSpeed: " + l.getSpeed() + " metres\n"; 

     // TODO Auto-generated method stub 
     if (l.hasSpeed()) { 
      mySpeed = l.getSpeed(); 
     } 

     Log.i(DEBUG_TAG, "On Location Changed: (" + s + ")"); 
ERROR HERE-->  Toast.makeText(context, s, Toast.LENGTH_SHORT).show(); 
    } 

    public void onProviderDisabled(String arg0) { 
     // TODO Auto-generated method stub 

    } 

    public void onProviderEnabled(String arg0) { 
     // TODO Auto-generated method stub 

    } 

    public void onStatusChanged(String arg0, int arg1, Bundle arg2) { 
     // TODO Auto-generated method stub 

    } 

}; 
+3

試試這個Toast.makeText (getApplicationContext(),s,Toast.LENGTH_SHORT).show(); – 2011-05-03 09:00:22

+0

我試過,我得到: **方法getApplicationContext()是未定義的類型newLocationListener(){} ** – ProNeticas 2011-05-03 09:04:01

+0

我應該注意,這在** BroadcastReceiver **而不是** Activity ** – ProNeticas 2011-05-03 09:05:35

回答

7

如果LocationListener聲明是活動類(比如:MyActivity)裏面,你應該創建Toast爲:

Toast.makeText(MyActivity.this, s, Toast.LENGTH_SHORT).show(); 

萬一LocationListener是在無上下文類中聲明,就像在你案例a BroadcastReceiver,您可以將上下文傳遞給其構造函數:

private final class MyReceiver extends BroadcastReceiver 
{ 
    private MyLocationListener listener; 
    public MyReceiver(final Context context) 
    { 
     this.listener = new MyLocationListener(context); 
    } 

    private final class MyLocationListener implements LocationListener 
    { 
     private Context context; 
     public MyLocationListener(final Context context) 
     { 
      this.context = context; 
     } 

     @Override 
     public void onLocationChanged(Location location) 
     { 
      // ... 
      Toast.makeText(context, "Toast message here", Toast.LENGTH_SHORT).show(); 
     } 

     // implement the rest of the methods 
    } 

    @Override 
    public void onReceive(Context context, Intent intent) 
    { 
     // Note that you have a context here, which you can use when receiving an broadcast message 
    } 
} 
+0

這個答案怎麼回事在BroadcastReceiver中沒有活動 – 2015-08-26 12:17:40

+0

@RikudoPain請詳細說明您的問題,因爲它不清楚。什麼讓你認爲LocationListener的匿名實例沒有在一個上下文組件中聲明(這是一個常見的設計選擇)? – rekaszeru 2015-08-26 13:10:15

+1

請閱讀他的評論「我應該注意到這是在BroadcastReceiver而不是活動」,可能他忘了編輯這個問題。因爲我對他有同樣的問題 – 2015-08-26 13:19:00

4

確保您使用class.If你在活動中使用這種烤麪包活動的背景下,寫Classname.this到位情況下

2

由於上下文是不可用的,你可以通過它在構造函數中