Android toast.makeText上下文错误

时间:2011-05-03 08:59:16

标签: android android-context

我无法在位置监听器内调用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 个答案:

答案 0 :(得分:7)

如果此LocationListener声明位于活动类内(例如: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
    }
}

答案 1 :(得分:4)

确保使用Activity类的上下文。如果您在Activity中使用此toast,请使用Classname.this代替上下文

答案 2 :(得分:2)

由于上下文不可用,您可以在构造函数

中传递它