OnLocationChanged不更新

时间:2018-07-17 17:17:37

标签: java android android-gps

我正在尝试学习在Android应用程序中获取GPS坐标。我正在尝试OnLocationChanged()方法,但在1000毫秒后未更新。我正在Android模拟器上运行此代码。请查看以下代码,并告诉我我在做什么错。谢谢。

public class MainActivity extends AppCompatActivity {

private int i = 0;
private LocationManager mLocationManager;
private TextView main_tv;
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;

private final LocationListener mLocationListener = new LocationListener() {
    @Override
    public void onLocationChanged(final Location location) {
        i++;
        Log.w("MyApp", Integer.toString(i)+"ITERATION CHANGED!!");
        main_tv.setText(Integer.toString(i)+" "+location.getLatitude()+location.getLongitude());
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {
        main_tv.setText("PROVIDER DISABLED");
    }

    @Override
    public void onProviderDisabled(String provider) {
        main_tv.setText("PROVIDER ENABLED");

    }
};


public boolean checkLocationPermission() {
    if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !=
            PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS_REQUEST_LOCATION);
        }
        return true;
}


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    main_tv = findViewById(R.id.textView);
    checkLocationPermission();
    mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000,
            2, mLocationListener);
}

}

0 个答案:

没有答案