片段中的LocationListener

Bis*_*sma 6 android location android-fragments

我可以在片段中使用LocationListener和LocationManager吗?实际上当我使用它时,它在这一行给出了错误:

lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0, (android.location.LocationListener) this);

当我没有把第四个参数强制转换给android.location.LocationListener它时给我错误...

import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;


public class Speedometer extends Fragment implements LocationListener {

    TextView txt;
    public Speedometer(){}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.speedometer, container, false);

        txt=(TextView)rootView.findViewById(R.id.speedometer);

        LocationManager lm= (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0, (android.location.LocationListener) this);

        return rootView;
    }

    @Override
    public void onLocationChanged(Location location) {

        if(location==null){
           txt.setText("-.- m/s");
        } else {
            float nCurrentSpeed=location.getSpeed();
            txt.setText(nCurrentSpeed+"m/s");
        }   
    }
}
Run Code Online (Sandbox Code Playgroud)

ran*_*dom 14

我认为你错误地实现com.google.android.gms.location.LocationListener了只有一个抽象方法的接口onLocationChanged

你应该实现android.location.LocationListener有4种抽象方法

onLocationChanged(Location location),

onProviderDisabled(String provider),

onProviderEnabled(String provider),

onStatusChanged(String provider, int status, Bundle extras)