在Android Java中没有调用onLocationChanged

时间:2017-01-23 23:04:55

标签: java android marker

三个月前我的代码工作正常,但现在它没有用。完全onLocationChanged没有被调用,我不知道为什么。我没有改变任何东西3个月。此外,当我想在地图上显示标记时,它并不存在。我得到了我所需要的一切许可。下面是Java(Android)中的代码:

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

        new DecimalFormat("#.#", new DecimalFormatSymbols(Locale.US));

        OnClickListener();

        mapFragment = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map));
        if (mapFragment != null) {
            mapFragment.getMapAsync(new OnMapReadyCallback() {
                @Override
                public void onMapReady(GoogleMap map) {
                    loadMap(map);
                }
            });
        } else {
            Toast.makeText(this, "Error - Map Fragment was null!!", Toast.LENGTH_SHORT).show();
        }

        Marker("50.06465", "19.94498", "Example");

    }


    public void onLocationChanged(Location location) {

    mLAT = Double.toString(location.getLatitude());
    mLON = Double.toString(location.getLongitude());

    new DoIt().execute();

}

    public void Marker(String LAT, String LON, String tit) {

    double dLAT = Double.parseDouble(LAT);
    double dLON = Double.parseDouble(LON);

    LatLng pos = new LatLng(dLAT, dLON);

    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        return;
    }

    map.setMyLocationEnabled(true);

    singleMarker = map.addMarker(new MarkerOptions()
            .title(tit)
            .position(pos)
            .icon(BitmapDescriptorFactory.fromResource(R.mipmap.icon));

}

1 个答案:

答案 0 :(得分:0)

您缺少几个重要的代码行:

  1. 您的活动必须实施LocationListener

    class MyActivity implements LocationListener
    
  2. 您应该使用@Override上的onLocationChanged()注释:

    @Override
    public void onLocationChanged(Location location) {
    
  3. 您需要致电requestLocationUpdates()注册您的听众:

    LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
    

    此步骤对于告诉Android系统调用您的onLocationChanged()方法至关重要。

  4. 有关详情,请参阅Android开发者指南中的Location Strategies