2016-09-23 466 views
-3

這是我的Android項目。該應用程序顯示當前位置的信息。
但是,該應用始終顯示該位置爲空。我已經搜索了很多,但仍然無法找到解決方案或無法實施解決方案。位置始終爲空

這裏是我的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#requestPermissions'你真的*有*要做到這一點,如果你在Android M及以上運行 – njzk2

+0

@Raghunandan我已經做到了這一點 –

回答

-1

喜爲什麼要使用getLastKnownLocation .IT回到以前的經度和緯度,它可能需要一些時間來更新lastknown位置。 大多數情況下,它會在你的位置後重啓你。

我只是指你谷歌Fused api爲位置任何類型的updation或current.Its非常準確。

如何在項目中融合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(); 
} 

} 

第二步。使此接口 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返回緩存值。它沒有打開位置跟蹤。所以除非其他應用程序最近開啓了位置跟蹤功能,否則它將不會有很好的價值給您並返回空值。如果您想要一個有保證的價值,您需要通過requestLocationUpdatesrequestSingleUpdate打開位置跟蹤。這些都會告訴操作系統找出你當前的位置,並在完成後給你一個回調。請注意,回撥可能需要一段時間才能被呼叫 - 特別是對於GPS。如果手機無法獲取網絡信息/ GPS衛星數據,那麼它將永遠不會進行回調。

+0

嘿,我試過了你說的但仍然無法獲取位置 –

+0

我花了5個小時在這個應用程序解決這個問題在發佈問題之前,現在我想放棄。 –

0

你可以看看RxGpsService(一個Android服務,用RxJava檢索GPS位置和路由統計信息)。它檢索一個包含當前速度,距離,時間和航點的RouteStats對象。