gpt4 book ai didi

Android toast.makeText 上下文错误

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:44:13 27 4
gpt4 key购买 nike

我在位置监听器中调用 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

}

};

最佳答案

如果此 LocationListener 声明在 Activity 类中(例如:MyActivity),您应该将 Toast 创建为:

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

如果 LocationListener 是在无上下文类中声明的,例如在您的情况下是 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
}
}

关于Android toast.makeText 上下文错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5867274/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com