GPS coordinates (using location manager) get printed as null

后端 未结 1 1987
生来不讨喜
生来不讨喜 2020-12-12 06:04

OnCreateMethod,

LocationManager manager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);


LocationListener listener = new LocationListen         


        
相关标签:
1条回答
  • 2020-12-12 06:22

    Here is my approach:

    Always use a Asynch Task for getting Coordinates etc.

    This is because GPS locking etc takes time and you don't want to bog down your main UI thread. Using a asynch task will enable you to throw a process in the background and auto update the UI field once the method has effectively executed.

    Here is a code snippet: For the do in background part of the Asynch task

    protected String doInBackground(Location... params) {
            /*
             * Get a new geocoding service instance, set for localized addresses.
             * This example uses android.location.Geocoder, but other geocoders that
             * conform to address standards can also be used.
             */
            // Show user progress bar
            pd.show();      
            Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());
            
            // Get the current location from the input parameter list
            Location location = params[0];
    
            // Create a list to contain the result address
            List<Address> addresses = null;
    
            // Try to get an address for the current location. Catch IO or network
            // problems.
            try {
    
                /*
                 * Call the synchronous getFromLocation() method with the latitude
                 * and longitude of the current location. Return at most 1 address.
                 */
                addresses = geocoder.getFromLocation(location.getLatitude(),
                        location.getLongitude(), 1);
    
                // Catch network or other I/O problems.
            } catch (IOException exception1) {
    
                // Log an error and return an error message
                Log.e(LocationUtils.APPTAG,
                        mContext.getString(R.string.IO_Exception_getFromLocation));
    
                // print the stack trace
                exception1.printStackTrace();
    
                // Return an error message
                return (mContext.getString(R.string.IO_Exception_getFromLocation));
    
                // Catch incorrect latitude or longitude values
            } catch (IllegalArgumentException exception2) {
    
                // Construct a message containing the invalid arguments
                String errorString = mContext.getString(
                        R.string.illegal_argument_exception,
                        location.getLatitude(), location.getLongitude());
                // Log the error and print the stack trace
                Log.e(LocationUtils.APPTAG, errorString);
                exception2.printStackTrace();
    
                //
                return errorString;
            }
            // If the reverse geocode returned an address
            if (addresses != null && addresses.size() > 0) {
    
                // Get the first address
                Address address = addresses.get(0);
    
                // Format the first line of address
                addressText = mContext.getString(
                        R.string.address_output_string,
    
                        // If there's a street address, add it
                        address.getMaxAddressLineIndex() > 0 ? address
                                .getAddressLine(0) : "",
    
                        // Locality is usually a city
                        address.getLocality(),
    
                        // The country of the address
                        address.getCountryName());
    
                // Return the text
                return addressText;
    
                // If there aren't any addresses, post a message
            } else {
                return mContext.getString(R.string.no_address_found);
            }
        }
    

    After the background task has finished executing you can run a onPostExecute method.

    protected void onPostExecute(String  result) {
            delegate.processFinished(result);
            // Update the EditText on the UI Thread.
            ed.setText(result);
            // Hide progress bar    
            pd.hide();
        }
    

    In your relevant Main Class you can then call the Aysch Task and ask it to display the results.

    public void getAddress(View v) {
            // In Gingerbread and later, use Geocoder.isPresent() to see if a
            // geocoder is available.
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD
                    && !Geocoder.isPresent()) {
                // No geocoder is present. Issue an error message
                Toast.makeText(getActivity(), R.string.no_geocoder_available,
                        Toast.LENGTH_LONG).show();
                return;
            }
    
            if (servicesConnected()) {
                // Get the current location
                Location currentLocation = mLocationClient.getLastLocation();
                Lat = currentLocation.getLatitude();
                Lng = currentLocation.getLongitude();
                LatLng = Double.toString(Lat) + "," + Double.toString(Lng);
                // Message to show results 
                Toast.makeText(getActivity(), LatLng, 0).show();
    
                // Turn the indefinite activity indicator on
                // Start the background task
                GetAddressTask getAddressTask = new GetAddressTask(getActivity(),
                        locationAddress, pd);
                getAddressTask.delegate = this;
                getAddressTask.execute(currentLocation);
    
            } else {
                Toast.makeText(getActivity(), "servicesConnected() == false",
                        Toast.LENGTH_SHORT).show();
            }
        }
    

    Note: this is only the relevant code snippets you need. Refer to my github if you require more detailed approach. Don't forget to upvote and accept answer!enter image description hereenter image description here

    Ps:

    I included a couple of pictures of an app I made to illustrate what the code can do don't worry about the map and stuff. It just shows events I have added and shared with friends who have the same app on their phone via a Google Cloud Server.

    0 讨论(0)
提交回复
热议问题