问题
I am having trouble calling toast.Maketext inside of a location listener. The context is not available, what am I doing wrong?
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
}
};
回答1:
If this LocationListener
declaration is inside an activity class (say: MyActivity
), you should create the Toast
as:
Toast.makeText(MyActivity.this, s, Toast.LENGTH_SHORT).show();
In case the LocationListener
is declared in a contextless class, like in your case a BroadcastReceiver
, you can pass the context to its constructor:
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
}
}
回答2:
Make sure that you use the context of the Activity class.If you are using this toast in an Activity, write, Classname.this in place of context
回答3:
Since context is not available,you can pass it in constructor
来源:https://stackoverflow.com/questions/5867274/android-toast-maketext-context-error