OnLocationChanged问题

时间:2017-07-10 23:03:13

标签: android listener on-location-changed

我正在开发一款可以找到用户位置并位于接入点和信号区域附近的应用。

当我通过按钮手动请求位置更新时,它不会调用回调函数。

这是我的活动:

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener, OnMapReadyCallback, LocationListener{

//LOG tag
private static final String LOG = MainActivity.class.getSimpleName();
private static final String DEBUG = "Debugging MainActivity:";
private static final String TEST = "Test";
private static final float ZOOM_LEVEL = 15.5f;
//The map
private GoogleMap mGmap;
private LocationManager mLocationManager;
private Location mLocation;
private WifiManager mWifiManager;
private BroadcastReceiver mBroadcastReceiver;
private List<ScanResult> mResultList;
private String mProvider;
private Criteria mCriteria;
//Controller
private AccessPointController mController;

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

    //Toolbar
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    mController = new AccessPointController();

    startReceivingLocationUpdates();
    mCriteria = new Criteria();
    mCriteria.setAccuracy(Criteria.ACCURACY_COARSE);
    mCriteria.setPowerRequirement(Criteria.POWER_MEDIUM);
    mProvider = mLocationManager.getBestProvider(mCriteria, false);
    Log.i(DEBUG, mProvider);
    mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context c, Intent intent) {
            if(intent.getAction() == WifiManager.SCAN_RESULTS_AVAILABLE_ACTION) {
                mResultList = mWifiManager.getScanResults();
                mController.setApList(mResultList);
            }
        }
    };

    mWifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    registerReceiver(mBroadcastReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
    mWifiManager.startScan();

    //Map handling
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
}

private void startReceivingLocationUpdates() {
    if(mLocationManager == null) {
        mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    }
}

@Override
public void onLocationChanged(Location location) {
    Log.i(DEBUG, "onLocationChanged");
    mLocation = new Location(location);
    mController.setCurrentPosition(mLocation);
    Log.i(DEBUG, "setted new position");
    mController.showOnMap(mGmap);
    mGmap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mLocation.getLatitude(), mLocation.getLongitude()), ZOOM_LEVEL));
}

@Override
protected void onResume() {
    super.onResume();
    try {
        mLocationManager.requestSingleUpdate(mProvider, this, null);
    } catch(SecurityException e) {
        System.out.println("OnResume Error: " + e.getMessage());
    }
}

@Override
protected void onPause() {
    super.onPause();
    mLocationManager.removeUpdates(this);
}

@Override
public void onMapReady(GoogleMap googleMap) {
    Log.i(DEBUG, "onMapReady");
    mGmap = googleMap;
    try {
        mLocation = mLocationManager.getLastKnownLocation(mProvider);
        mController.setCurrentPosition(mLocation);
    } catch(SecurityException e) {
        e.printStackTrace();
    }
    mGmap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mLocation.getLatitude(), mLocation.getLongitude()), ZOOM_LEVEL));
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_explore) {
        try {
            if(mLocationManager != null) {
                try {
                    Log.i(DEBUG, "manual update request");
                    mLocationManager.requestSingleUpdate(mProvider, this, null);
                } catch (SecurityException e) {
                    Toast.makeText(this, "Failed to request location updates, ignore: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                } catch (IllegalArgumentException e) {
                    Toast.makeText(this, "Provider does not exist: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        } catch (SecurityException e) {
            e.printStackTrace();
        }
    } else if (id == R.id.nav_open_networks) {
        Toast.makeText(this, "Open network pressed", Toast.LENGTH_SHORT).show();

    } else if (id == R.id.nav_closed_networks) {
        Toast.makeText(this, "Closed network pressed", Toast.LENGTH_SHORT).show();
    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

}

基本上,当用户按下探索按钮时,应用程序应该找到用户并在地图上显示他。

这是logcat:

/调试MainActivity :: network

/调试MainActivity :: onMapReady

/调试控制器::设置位置

/调试MainActivity ::手动更新请求

并且/ Debugging MainActivity :: onLocationChanged永远不会显示。

我还尝试将变量用作LocationListener,但它不起作用。 是的,我在清单中的权限很好。

我真的不明白我做错了什么。

1 个答案:

答案 0 :(得分:0)

由于地图是异步加载的,因此要求在onMapReady()方法中执行操作还为时过早。

使用FusedLocation方法替换LocationManager方法允许我等到建立连接然后计算。