2016-09-23 2 views
-3

Это мой проект андроида. Приложение показывает информацию о текущем местоположении.
Однако приложение всегда показывает, что местоположение равно null. Я много искал, но до сих пор не смог найти решение или не смог реализовать решение.Местоположение всегда null

Вот мой MainActivity код,

package com.learning.pranavjain.hikerswatch; 

import android.Manifest; 
import android.app.Activity; 
import android.content.Context; 
import android.content.pm.PackageManager; 
import android.location.Address; 
import android.location.Criteria; 
import android.location.Geocoder; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.support.v4.app.ActivityCompat; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.WindowManager; 
import android.widget.TextView; 

import java.io.IOException; 
import java.util.List; 
import java.util.Locale; 

public class MainActivity extends Activity implements LocationListener { 

LocationManager locationManager; 
String provider; 
String sLatitude; 
String sLongitude; 
String sAccuracy; 
String sSpeed; 
String sAltitude; 
TextView addressTV; 


@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    //Hiding the status bar 
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
      WindowManager.LayoutParams.FLAG_FULLSCREEN); 
    setContentView(R.layout.activity_main); 

    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
    provider = locationManager.getBestProvider(new Criteria(),false); 

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
     // TODO: Consider calling 
     // ActivityCompat#requestPermissions 
     // here to request the missing permissions, and then overriding 
     // public void onRequestPermissionsResult(int requestCode, String[] permissions, 
     //           int[] grantResults) 
     // to handle the case where the user grants the permission. See the documentation 
     // for ActivityCompat#requestPermissions for more details. 
     return; 
    } 
    locationManager.requestLocationUpdates(provider,400,1,this); 
    location = locationManager.getLastKnownLocation(provider); 

    if(location==null){ 
     Log.i("Location1","NULL1"); 
     Toast.makeText(this,"Location not found",Toast.LENGTH_SHORT).show(); 
    } 

    if(location!=null) { 
     onLocationChanged(location); 
     Log.i("Location1","Reached here"); 
    } 

} 

@Override 
protected void onResume() { 
    super.onResume(); 


    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
     // TODO: Consider calling 
     // ActivityCompat#requestPermissions 
     // here to request the missing permissions, and then overriding 
     // public void onRequestPermissionsResult(int requestCode, String[] permissions, 
     //           int[] grantResults) 
     // to handle the case where the user grants the permission. See the documentation 
     // for ActivityCompat#requestPermissions for more details. 
     return; 
    } 
    locationManager.requestLocationUpdates(provider, 400, 1, this); 
} 

@Override 
public void onLocationChanged(Location location) { 



    Double lat = location.getLatitude(); 
    Double lng = location.getLongitude(); 
    Float acc = location.getAccuracy(); 
    Float spe = location.getSpeed(); 
    Double alt = location.getAltitude(); 

    Log.i("Location","reached here"); 

    TextView latitude = (TextView) findViewById(R.id.latitude); 
    TextView longitude = (TextView) findViewById(R.id.longitude); 
    TextView accuracy = (TextView) findViewById(R.id.accuracy); 
    TextView speed = (TextView) findViewById(R.id.speed); 
    TextView altitude = (TextView) findViewById(R.id.altitude); 
    addressTV = (TextView) findViewById(R.id.address); 

    sLatitude = latitude.getText().toString(); 
    sLongitude = longitude.getText().toString(); 
    sAccuracy = accuracy.getText().toString(); 
    sSpeed = speed.getText().toString(); 
    sAltitude = altitude.getText().toString(); 

    sLatitude += Double.toString(lat); 
    sLongitude += Double.toString(lng); 
    sAccuracy += Double.toString(acc); 
    sSpeed += Double.toString(spe); 
    sAltitude += Double.toString(alt); 

    latitude.setText(sLatitude); 
    longitude.setText(sLongitude); 
    accuracy.setText(sAccuracy); 
    speed.setText(sSpeed); 
    altitude.setText(sAltitude); 

    Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault()); 

    try { 
     List<Address> listAddresses = geocoder.getFromLocation(lat, lng, 1); 

     if (listAddresses != null && listAddresses.size() > 0) { 

      Log.i("PlaceInfo", listAddresses.get(0).toString()); 

      String addressHolder = ""; 

      for (int i = 0; i <= listAddresses.get(0).getMaxAddressLineIndex(); i++) { 

       addressHolder += listAddresses.get(0).getAddressLine(i) + "\n"; 

      } 

      addressTV.setText("Address:\n" + addressHolder); 

     } 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    Log.i("Location:", String.valueOf(lat)); 
    Log.i("Location:", lng.toString()); 

} 

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

} 

@Override 
public void onProviderEnabled(String provider) { 

} 

@Override 
public void onProviderDisabled(String provider) { 

} 

@Override 
protected void onPause() { 
    super.onPause(); 

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
     // TODO: Consider calling 
     // ActivityCompat#requestPermissions 
     // here to request the missing permissions, and then overriding 
     // public void onRequestPermissionsResult(int requestCode, String[] permissions, 
     //           int[] grantResults) 
     // to handle the case where the user grants the permission. See the documentation 
     // for ActivityCompat#requestPermissions for more details. 
     return; 
    } 
    locationManager.removeUpdates(this); 

} 
} 

Вот мой код манифеста,

<?xml version="1.0" encoding="utf-8"?> 

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> 
<uses-permission android:name="android.permission.INTERNET" /> 
<uses-feature android:name="android.hardware.location.network" /> 
<uses-feature android:name="android.hardware.location.gps" /> 

<application 
    android:allowBackup="true" 
    android:icon="@mipmap/ic_launcher" 
    android:label="@string/app_name" 
    android:supportsRtl="true" 
    android:theme="@style/AppTheme"> 
    <activity android:name=".MainActivity"> 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 

      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 
</application> 

Весь проект можно найти на here (GitHub)

+0

getLastKnownLocation может возвращать null, вы должны запросить обновление местоположения, если это так. – Raghunandan

+0

'Рассмотрение вызова ActivityCompat # requestPermations' На самом деле у вас есть *, чтобы сделать это, если вы работаете на android M и выше – njzk2

+0

@Raghunandan Я уже сделал это –

ответ

-1

привет, почему пытается использовать getLastKnownLocation .Это вернуть предыдущую широту и долготу, и это может занять некоторое время, чтобы обновить lastknown расположения. Скорее всего, вы получите нулевое значение после вашего местоположения.

Я просто обращаюсь к вам google Fused api для определения местоположения любого вида обновления или текущего. Он очень точный.

Как вы можете спланировать api в своем проекте. Посмотрите, я дам вам небольшой пример.

Шаг 1. Сделайте этот класс GoogleLocationService.java

public class GoogleLocationService { 
private GoogleServicesCallbacks callbacks = new GoogleServicesCallbacks(); 
LocationUpdateListener locationUpdateListener; 
Context activity; 
protected GoogleApiClient mGoogleApiClient; 
protected LocationRequest mLocationRequest; 

public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 30000; 


public GoogleLocationService(Context activity, LocationUpdateListener locationUpdateListener) { 
    this.locationUpdateListener = locationUpdateListener; 
    this.activity = activity; 
    buildGoogleApiClient(); 
} 

protected synchronized void buildGoogleApiClient() { 
    //Log.i(TAG, "Building GoogleApiClient"); 
    mGoogleApiClient = new GoogleApiClient.Builder(activity) 
      .addConnectionCallbacks(callbacks) 
      .addOnConnectionFailedListener(callbacks) 
      .addApi(LocationServices.API) 
      .build(); 
    createLocationRequest(); 
    mGoogleApiClient.connect(); 
} 

protected void createLocationRequest() { 
    mLocationRequest = new LocationRequest(); 
    mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS); 
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 

} 

private class GoogleServicesCallbacks implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener { 

    @Override 
    public void onConnected(Bundle bundle) { 
     startLocationUpdates(); 
    } 

    @Override 
    public void onConnectionSuspended(int i) { 
     mGoogleApiClient.connect(); 
    } 

    @Override 
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { 

     if (connectionResult.getErrorCode() == ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED) { 
      Toast.makeText(activity, "Google play service not updated", Toast.LENGTH_LONG).show(); 

     } 
     locationUpdateListener.cannotReceiveLocationUpdates(); 
    } 

    @Override 
    public void onLocationChanged(Location location) { 
     if (location.hasAccuracy()) { 
      if (location.getAccuracy() < 30) { 
       locationUpdateListener.updateLocation(location); 
      } 
     } 
    } 
} 

private static boolean locationEnabled(Context context) { 
    boolean gps_enabled = false; 
    LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); 
    try { 
     gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER); 
    } catch (Exception ex) { 
     ex.printStackTrace(); 
    } 
    return gps_enabled; 
} 

private boolean servicesConnected(Context context) { 
    return isPackageInstalled(GooglePlayServicesUtil.GOOGLE_PLAY_STORE_PACKAGE, context); 
} 

private boolean isPackageInstalled(String packagename, Context context) { 
    PackageManager pm = context.getPackageManager(); 
    try { 
     pm.getPackageInfo(packagename, PackageManager.GET_ACTIVITIES); 
     return true; 
    } catch (PackageManager.NameNotFoundException e) { 
     e.printStackTrace(); 
     return false; 
    } 
} 


public void startUpdates() { 
    /* 
    * Connect the client. Don't re-start any requests here; instead, wait 
    * for onResume() 
    */ 
    if (servicesConnected(activity)) { 
     if (locationEnabled(activity)) { 
      locationUpdateListener.canReceiveLocationUpdates(); 
      startLocationUpdates(); 
     } else { 
      locationUpdateListener.cannotReceiveLocationUpdates(); 
      Toast.makeText(activity, "Unable to get your location.Please turn on your device Gps", Toast.LENGTH_LONG).show(); 
     } 
    } else { 
     locationUpdateListener.cannotReceiveLocationUpdates(); 
     Toast.makeText(activity, "Google play service not available", Toast.LENGTH_LONG).show(); 
    } 
} 

//stop location updates 
public void stopUpdates() { 
    stopLocationUpdates(); 
} 

//start location updates 
private void startLocationUpdates() { 

    if (checkSelfPermission(activity, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(activity, ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
     return; 
    } 
    if (mGoogleApiClient.isConnected()) { 
     LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, callbacks); 
    } 
} 

public void stopLocationUpdates() { 
    if (mGoogleApiClient.isConnected()) { 
     LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, callbacks); 
    } 
} 

public void startGoogleApi() { 
    mGoogleApiClient.connect(); 
} 

public void closeGoogleApi() { 
    mGoogleApiClient.disconnect(); 
} 

} 

Step2. Сделайте этот интерфейс LocationUpdateListener.java

public interface LocationUpdateListener { 

/** 
* Called immediately the service starts if the service can obtain location 
*/ 
void canReceiveLocationUpdates(); 

/** 
* Called immediately the service tries to start if it cannot obtain location - eg the user has disabled wireless and 
*/ 
void cannotReceiveLocationUpdates(); 

/** 
* Called whenever the location has changed (at least non-trivially) 
* @param location 
*/ 
void updateLocation(Location location); 

/** 
* Called when GoogleLocationServices detects that the device has moved to a new location. 
* @param localityName The name of the locality (somewhere below street but above area). 
*/ 
void updateLocationName(String localityName, Location location); 
} 

Шаг 3. Используйте этот кусок кода, где вы хотите, чтобы получить место,

public class MainActivity extends ActionBarActivity { 

private GoogleLocationService googleLocationService; 

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

    googleLocationService = new GoogleLocationService(context, new LocationUpdateListener() { 
    @Override 
    public void canReceiveLocationUpdates() { 
    } 

    @Override 
    public void cannotReceiveLocationUpdates() { 
    } 

    //update location to our servers for tracking purpose 
    @Override 
    public void updateLocation(Location location) { 
     if (location != null) { 
      Timber.e("updated location %1$s %2$s", location.getLatitude(), location.getLongitude()); 

     } 
    } 

    @Override 
    public void updateLocationName(String localityName, Location location) { 

     googleLocationService.stopLocationUpdates(); 
    } 
}); 
googleLocationService.startUpdates(); 


} 

@Override 
public void onDestroy() { 
    super.onDestroy(); 
if (googleLocationService != null) { 
    googleLocationService.stopLocationUpdates(); 
} 

} 
} 

Надеется, что это поможет вам.

+0

уверен, его работа прекрасна, не волнуйся – Saveen

+0

благодарит меня за то, что представил меня в FusedLocationProviderApi –

-1

Вы можете использовать этот код

MainActivity.java

import android.Manifest; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.content.IntentSender; 
import android.content.pm.PackageManager; 
import android.location.Location; 
import android.net.Uri; 
import android.provider.Settings; 
import android.support.annotation.NonNull; 
import android.support.annotation.Nullable; 
import android.support.v4.app.ActivityCompat; 
import android.support.v4.content.ContextCompat; 
import android.support.v7.app.AlertDialog; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.widget.TextView; 
import android.widget.Toast; 

import com.google.android.gms.common.ConnectionResult; 
import com.google.android.gms.common.api.GoogleApiClient; 
import com.google.android.gms.common.api.PendingResult; 
import com.google.android.gms.common.api.ResultCallback; 
import com.google.android.gms.common.api.Status; 
import com.google.android.gms.location.LocationListener; 
import com.google.android.gms.location.LocationRequest; 
import com.google.android.gms.location.LocationServices; 
import com.google.android.gms.location.LocationSettingsRequest; 
import com.google.android.gms.location.LocationSettingsResult; 
import com.google.android.gms.location.LocationSettingsStates; 
import com.google.android.gms.location.LocationSettingsStatusCodes; 
import com.google.android.gms.maps.CameraUpdateFactory; 
import com.google.android.gms.maps.GoogleMap; 
import com.google.android.gms.maps.OnMapReadyCallback; 
import com.google.android.gms.maps.SupportMapFragment; 
import com.google.android.gms.maps.model.BitmapDescriptorFactory; 
import com.google.android.gms.maps.model.LatLng; 
import com.google.android.gms.maps.model.Marker; 
import com.google.android.gms.maps.model.MarkerOptions; 

import java.text.DateFormat; 
import java.util.Date; 

public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, 
     GoogleApiClient.OnConnectionFailedListener, LocationListener, OnMapReadyCallback { 

    private GoogleApiClient mGoogleApiClient; 
    private LocationRequest mLocationRequest; 
    private Location mCurrentLocation; 
    private String mLocationUpdatedDate; 

    private TextView mLatitude; 
    private TextView mLongitude; 
    private TextView mDateText; 

    private GoogleMap mMap; 
    private Marker mCurrentMarker; 

    private final int MY_PERMISSIONS_REQUEST_READ_LOCATION = 100; 
    private final int REQUEST_CHECK_SETTINGS = 101; 
    private final int REQUEST_PERMISSION_SETTING = 102; 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     mLatitude = (TextView) findViewById(R.id.latText); 
     mLongitude = (TextView) findViewById(R.id.longText); 
     mDateText = (TextView) findViewById(R.id.dateText); 

     if (mGoogleApiClient == null) { 
      mGoogleApiClient = new GoogleApiClient.Builder(this) 
        .addConnectionCallbacks(this) 
        .addOnConnectionFailedListener(this) 
        .addApi(LocationServices.API) 
        .build(); 
     } 

     createLocationRequest(); 

     SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() 
       .findFragmentById(R.id.map); 
     mapFragment.getMapAsync(this); 

    } 

    private void fetchLocation() { 

     if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED 
       && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { 
      mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(
        mGoogleApiClient); 
     } 
    } 

    private void updateUI() { 
     if (mCurrentLocation != null) { 
      mLatitude.setText(String.valueOf(mCurrentLocation.getLatitude())); 
      mLongitude.setText(String.valueOf(mCurrentLocation.getLongitude())); 
      mDateText.setText(mLocationUpdatedDate); 
     } 
    } 


    protected void onStart() { 
     mGoogleApiClient.connect(); 
     super.onStart(); 
    } 

    protected void onStop() { 
     mGoogleApiClient.disconnect(); 
     super.onStop(); 
    } 


    @Override 
    public void onConnected(@Nullable Bundle bundle) { 
     if (ActivityCompat.checkSelfPermission(MainActivity.this, 
       Manifest.permission.ACCESS_COARSE_LOCATION) 
       != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MainActivity.this, 
       Manifest.permission.ACCESS_FINE_LOCATION) 
       != PackageManager.PERMISSION_GRANTED) { 

      ActivityCompat.requestPermissions(MainActivity.this, 
        new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 
        MY_PERMISSIONS_REQUEST_READ_LOCATION); 

     } else { 
      fetchLocation(); 
      updateUI(); 

      startLocationUpdates(); 

     } 

    } 

    @Override 
    public void onConnectionSuspended(int i) { 

    } 

    @Override 
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { 

    } 


    protected void createLocationRequest() { 
     mLocationRequest = new LocationRequest(); 
     mLocationRequest.setInterval(10000); 
     mLocationRequest.setFastestInterval(5000); 
     mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 

     LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder() 
       .addLocationRequest(mLocationRequest); 

     PendingResult<LocationSettingsResult> result = 
       LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, 
         builder.build()); 


     result.setResultCallback(new ResultCallback<LocationSettingsResult>() { 
      @Override 
      public void onResult(@NonNull LocationSettingsResult result) { 
       final Status status = result.getStatus(); 
       // final LocationSettingsStates = result.getLocationSettingsStates(); 
       switch (status.getStatusCode()) { 
        case LocationSettingsStatusCodes.SUCCESS: 
         // All location settings are satisfied. The client can 
         // initialize location requests here. 

         break; 
        case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: 
         // Location settings are not satisfied, but this can be fixed 
         // by showing the user a dialog. 
         try { 
          // Show the dialog by calling startResolutionForResult(), 
          // and check the result in onActivityResult(). 
          status.startResolutionForResult(
            MainActivity.this, 
            REQUEST_CHECK_SETTINGS); 
         } catch (IntentSender.SendIntentException e) { 
          // Ignore the error. 
         } 
         break; 
        case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE: 
         // Location settings are not satisfied. However, we have no way 
         // to fix the settings so we won't show the dialog. 

         break; 
       } 
      } 
     }); 

    } 


    protected void startLocationUpdates() { 
     if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED 
       && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { 

      LocationServices.FusedLocationApi.requestLocationUpdates(
        mGoogleApiClient, mLocationRequest, this); 
     } 
    } 

    protected void stopLocationUpdates() { 
     LocationServices.FusedLocationApi.removeLocationUpdates(
       mGoogleApiClient, this); 
    } 


    @Override 
    protected void onPause() { 
     if (!mGoogleApiClient.isConnected()) 
      stopLocationUpdates(); 
     super.onPause(); 

    } 

    @Override 
    protected void onResume() { 
     if (mGoogleApiClient.isConnected()) { 
      startLocationUpdates(); 
     } 
     super.onResume(); 

    } 

    @Override 
    public void onRequestPermissionsResult(int requestCode, 
              String permissions[], int[] grantResults) { 
     switch (requestCode) { 
      case MY_PERMISSIONS_REQUEST_READ_LOCATION: { 
       // If request is cancelled, the result arrays are empty. 
       // String permission = permissions[0]; 
       for (int i = 0, len = permissions.length; i < len; i++) { 
        String permission = permissions[0]; 
        if (grantResults.length > 0 
          && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 

         fetchLocation(); 
         updateUI(); 

        } else { 

         if (!ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, permission)) { 

          // user denied WITH never ask again 
          showSettingDialog(); 


         } else if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permission)) { 
          showPermissionDialog(); 
          // user denied WITHOUT never ask again 
          // this is a good place to explain the user 
          // why you need the permission and ask if he want 
          // to accept it (the rationale) 
         } 


        } 
        return; 
       } 
      } 

      // other 'case' lines to check for other 
      // permissions this app might request 
     } 
    } 

    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 

     if (requestCode == REQUEST_PERMISSION_SETTING) { 
      // updateUI(fetchLocation()); 

      Toast.makeText(MainActivity.this, "RequestCode = " + requestCode + " ResultCode = " + resultCode, Toast.LENGTH_SHORT).show(); 
     } 
    } 

    @Override 
    public void onLocationChanged(Location location) { 
     mCurrentLocation = location; 
     mLocationUpdatedDate = DateFormat.getTimeInstance().format(new Date()); 
     updateUI(); 

     if (mCurrentMarker != null) { 
      mCurrentMarker.remove(); 

     } 

     if (mMap != null) { 
      /* LatLng currentPosition = new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude()); 
      mMap.addMarker(new MarkerOptions().position(currentPosition).title("Myself")); 
      mMap.moveCamera(CameraUpdateFactory.newLatLng(currentPosition));*/ 

      LatLng latLng = new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude()); 
      mCurrentMarker = mMap.addMarker(new MarkerOptions().position(latLng).title("Abhishek").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE))); 
      // Showing the current location in Google Map 
      mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); 

      // Zoom in the Google Map 
      mMap.animateCamera(CameraUpdateFactory.zoomTo(20)); 
     } 


    } 


    private void showPermissionDialog() { 

     final AlertDialog dialog = new AlertDialog.Builder(MainActivity.this).create(); 
     dialog.setButton(AlertDialog.BUTTON_POSITIVE, "Ok", new DialogInterface.OnClickListener() { 
      @Override 
      public void onClick(DialogInterface dialogInterface, int i) { 

       dialog.cancel(); 
       ActivityCompat.requestPermissions(MainActivity.this, 
         new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 
         MY_PERMISSIONS_REQUEST_READ_LOCATION); 

      } 
     }); 
     dialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() { 
      @Override 
      public void onClick(DialogInterface dialogInterface, int i) { 
       dialog.cancel(); 
      } 
     }); 

     dialog.setTitle("Location explaination"); 
     dialog.setMessage("Location permission is taken so that we can provide you with better service"); 
     dialog.show(); 
    } 

    private void showSettingDialog() { 

     final AlertDialog dialog = new AlertDialog.Builder(MainActivity.this).create(); 
     dialog.setButton(AlertDialog.BUTTON_POSITIVE, "Ok", new DialogInterface.OnClickListener() { 
      @Override 
      public void onClick(DialogInterface dialogInterface, int i) { 


       Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); 
       Uri uri = Uri.fromParts("package", getPackageName(), null); 
       intent.setData(uri); 
       startActivityForResult(intent, REQUEST_PERMISSION_SETTING); 
       dialog.cancel(); 

      } 
     }); 
     dialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() { 
      @Override 
      public void onClick(DialogInterface dialogInterface, int i) { 
       dialog.cancel(); 
      } 
     }); 

     dialog.setTitle("Permission Denied"); 
     dialog.setMessage("Please enable location from your app setting screen"); 
     dialog.show(); 
    } 

    @Override 
    public void onMapReady(GoogleMap googleMap) { 


     mMap = googleMap; 
     if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && 
       ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { 
      mMap.setMyLocationEnabled(true); 
     } 



     // Add a marker in Sydney and move the camera 
     if(mCurrentLocation != null) { 
      LatLng currentPosition = new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude()); 
      mMap.addMarker(new MarkerOptions().position(currentPosition).title("Myself")); 
      mMap.moveCamera(CameraUpdateFactory.newLatLng(currentPosition)); 
     } 
    } 
} 

activity_main

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:id="@+id/activity_main" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    tools:context="abhishek.com.testing.MainActivity"> 


    <fragment 
     android:id="@+id/map" 
     android:name="com.google.android.gms.maps.SupportMapFragment" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     tools:context="abhishek.com.testing.MapsActivity" /> 



    <LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:orientation="vertical" 
     android:gravity="center_horizontal" 
     android:weightSum="3"> 

     <TextView 
      android:id="@+id/latText" 
      android:layout_width="wrap_content" 
      android:layout_height="0dp" 
      android:layout_weight="1" 
      android:text="Latitude" /> 


     <TextView 
      android:id="@+id/longText" 
      android:layout_width="wrap_content" 
      android:layout_height="0dp" 
      android:layout_weight="1" 
      android:text="Longitude" /> 


     <TextView 
      android:id="@+id/dateText" 
      android:layout_width="wrap_content" 
      android:layout_height="0dp" 
      android:layout_weight="1" 
      android:text="Updated at"/> 

    </LinearLayout> 



</RelativeLayout> 
0

getLastKnownLocation возвращает кэшированное значение. Он не включает отслеживание местоположения. Поэтому, если какое-то другое приложение недавно не включило отслеживание местоположения, оно не будет иметь хорошего значения, чтобы дать вам и возвращает null. Если вы хотите получить гарантированное значение, вам необходимо включить отслеживание местоположения через requestLocationUpdates или requestSingleUpdate. Любой из них сообщит ОС, чтобы выяснить ваше текущее местоположение и дать вам обратный вызов, когда это будет сделано. Обратите внимание, что обратный вызов может занять некоторое время, особенно для GPS. И если телефон не может получить информацию о спутниковой информации/GPS-сателлитах, он никогда не сделает обратный вызов.

+0

Эй, я пробовал, что сказал, но все-таки не смог найти место. –

+0

Я потратил на это 5 часов эта проблема перед отправкой вопроса, теперь мне хочется сдаться. –

0

Вы можете взглянуть на RxGpsService (услуга Android для получения местоположений GPS и статистики маршрута с использованием RxJava). Он извлекает объект RouteStats, который содержит текущую скорость, расстояние, пройденное время и путевые точки.

Смежные вопросы