简体   繁体   中英

Method works in OnResume() but not in OnCreate()

I have a little app to get the Location and then show it on the map.

In onCreate() I start the LocationService and the map. I then want to call my setLocation() method to determine my location and show it on the map.

If i call the setLocation() method from onCreate() it does not work and the toast gets shown. If i call setLocation() from onResume() it works. What could be the reason for that?

Source here: Github

Thanks for any help. If you need a certain part of the rest of the code just tell me.

Never create service instances yourself via the constructor. There is no reason at all for GPSService to exist, let alone be a Service . That being said, getPos() will return null until such time as you get a location fix. Exactly when that will occur is indeterminate.

Similarly, never create activity instances yourself via a constructor. There is no reason at all for MapsActivity to exist, let alone to be an actual subclass of Activity . That being said, the mapActivity field in MainActivity will be null until onMapAsync() is called. Exactly when that will occur is also indeterminate.

Hence, you cannot reliably call setLocation() from either onCreate() or onResume() . After all, you may not be able to actually get a location ever.

Moreover, your application will crash on Android 6.0+ devices, if your targetSdkVersion is 23 or higher, as you are attempting to get locations before you even ask for the runtime permission, let alone have it be granted.

Your mapActivity.moveCamera(location) call cannot be made until you have a location and you have a map. You will need to arrange to see, in onMapReady() and onLocationChanged() , whether you have both pieces of data, and then call mapActivity.moveCamera(location) .

Also, FWIW, your WRITE_EXTERNAL_STORAGE <uses-permission> element is in the wrong place in the manifest. <uses-permission> elements have to be the immediate children of the root <manifest> element, not children of <application> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM