2011-05-03 65 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

由于上下文是不可用的,你可以通过它在构造函数中