2016-03-15 215 views
3

我正試圖在3天內解決這個問題。我失去了調試的視野,無法看到我的錯誤。 我想構建一個請求當前位置的應用程序。爲什麼getLastLocation返回null?

我的getLastLocation返回null,是否有任何一點指向我在哪裏做錯了?

這裏是我的代碼

public class MapActivityFragment extends FragmentActivity implements 
     LocationListener, 
     OnMapReadyCallback, 
     GoogleApiClient.ConnectionCallbacks, 
     GoogleApiClient.OnConnectionFailedListener, 
     GoogleMap.OnMarkerDragListener, 
     GoogleMap.OnMapLongClickListener, View.OnClickListener { 

    //Our Map 
    private GoogleMap mMap; 

    //To store longitude and latitude from map 
    private double longitude; 
    private double latitude; 

    //Google ApiClient 
    private GoogleApiClient googleApiClient; 
    private ImageButton buttonCurrent; 
    private TextView tv; 
    private String myLocation; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_maps); 
     // Obtain the SupportMapFragment and get notified when the map is ready to be used. 
     SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() 
       .findFragmentById(R.id.map); 
     mapFragment.getMapAsync(this); 

     tv = (TextView) findViewById(R.id.textViewTv); 

     LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 

     //Initializing googleapi client 
     googleApiClient = new GoogleApiClient.Builder(this) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .addApi(LocationServices.API) 
       .build(); 

     buttonCurrent = (ImageButton) findViewById(R.id.buttonCurrent); 
     buttonCurrent.setOnClickListener(this); 

     //Initializing views and adding onclick listeners 
    } 

    @Override 
    protected void onStart() { 
     googleApiClient.connect(); 
     // Log.d("Tag Name", "GOOGLE : : : " + googleApiClient); 
     super.onStart(); 
    } 

    @Override 
    protected void onResume() { 
     googleApiClient.connect(); 
     super.onResume(); 
    } 

    //Getting current location 
    private void getCurrentLocation() { 
     //mMap.clear(); 
     //Creating a location object 
     Log.d("Tag Name", "GOOGLE : : : " + googleApiClient); 
     Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient); 
     Log.d("Tag Name", "asdsa " + location); 
     Toast.makeText(MapActivityFragment.this, "googleApiclient:" + googleApiClient, Toast.LENGTH_LONG).show(); 
     Toast.makeText(MapActivityFragment.this, "location:" + location, Toast.LENGTH_LONG).show(); 

     mMap.clear(); 

     if (location != null) { 
      Log.d("Tag Name", "2222"); 
      //Getting longitude and latitude 
      longitude = location.getLongitude(); 
      latitude = location.getLatitude(); 
      tv.setText("longitude: " + longitude + " " + "latitude: " + latitude); 

      //Toast.makeText(this, "long ; " + longitude, Toast.LENGTH_LONG).show(); 
      Log.d("Tag Name", "Log Message"); 

      //moving the map to location 
      moveMap(); 
     } 
    } 

    //Function to move the map 
    private void moveMap() { 

     //String to display current latitude and longitude 
     String msg = latitude + " , " + longitude; 
     //Creating a LatLng Object to store Coordinates 
     LatLng latLng = new LatLng(latitude, longitude); 
     //Adding marker to map 
     mMap.addMarker(new MarkerOptions() 
       .position(latLng) //setting position 
       .draggable(true) //Making the marker draggable 
       .title("Current Location")); //Adding a title 
     //Moving the camera 
     mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); 
     //Animating the camera 
     //mMap.animateCamera(CameraUpdateFactory.zoomTo(15)); 
     //Displaying current coordinates in toast 
     Toast.makeText(this, msg, Toast.LENGTH_LONG).show(); 
    } 

    @Override 
    public void onMapReady(GoogleMap googleMap) { 
     mMap = googleMap; 
     LatLng latLng = new LatLng(-34, 151); 
     mMap.addMarker(new MarkerOptions().position(latLng).draggable(true)); 
     mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); 
     mMap.setOnMarkerDragListener(this); 
     mMap.setOnMapLongClickListener(this); 
    } 

    @Override 
    public void onConnected(Bundle bundle) { 
     Log.i("TAG", "Location services connected."); 
     getCurrentLocation(); 
    } 

    @Override 
    public void onConnectionSuspended(int i) { 
     Log.i("TAG", "Location services suspended. Please reconnect."); 
    } 

    @Override 
    public void onConnectionFailed(ConnectionResult connectionResult) { 
    } 

    @Override 
    public void onMapLongClick(LatLng latLng) { 
     mMap.clear(); 
     mMap.addMarker(new MarkerOptions() 
       .position(latLng) 
       .draggable(true)); 
    } 

    @Override 
    public void onMarkerDragStart(Marker marker) { 
    } 

    @Override 
    public void onMarkerDrag(Marker marker) { 
    } 

    @Override 
    public void onMarkerDragEnd(Marker marker) { 
     latitude = marker.getPosition().latitude; 
     longitude = marker.getPosition().longitude; 
     moveMap(); 
    } 

    @Override 
    public void onClick(View v) { 

     if (v == buttonCurrent) { 
      mMap.setMyLocationEnabled(true); 
      getCurrentLocation(); 
      //moveMap(); 
      mMap.addMarker(new MarkerOptions() 
        .position(new LatLng(40, 40)).title("Hello World")); 
     } 
    } 

    @Override 
    public void onLocationChanged(Location location) { 
     location.getLatitude(); 
     location.getLongitude(); 
     tv.setText("Latitude = " + location.getLatitude() + " Longitude = " + location.getLongitude()); 
    } 

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

    @Override 
    public void onProviderEnabled(String provider) { 
    } 

    @Override 
    public void onProviderDisabled(String provider) { 
    } 
} 
+0

權限怎麼樣?在清單中添加了必需的權限(並且自API23以來在運行時請求)? – Opiatefuchs

+0

<使用權限android:name =「android.permission.ACCESS_NETWORK_STATE」/> <使用權限android:name =「android.permission。 WRITE_EXTERNAL_STORAGE」 /> <用途的許可機器人:名稱= 「com.google.android.providers.gsf.permission.READ_GSERVICES」/> <使用的許可機器人:名稱= 「android.permission.ACCESS_COARSE_LOCATION」/>

+0

和運行時權限檢查?你在API => 23上開發嗎? – Opiatefuchs

回答

0

這一個工作對我來說,從谷歌的一些變化提供。

@Override 
public void onConnected(Bundle dataBundle) { 
    // Display the connection status 
    if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
     // TODO: Consider calling 
     requestLocationPermission(); 
     return; 
    } 
    Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); 
    if (location != null) { 
     Toast.makeText(getActivity(), "GPS location was found!", Toast.LENGTH_SHORT).show(); 
     } 
     LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude()); 
     CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 17); 
     mMap.animateCamera(cameraUpdate); 
     startLocationUpdates(); 
} 

權限模型代碼是API級> = 23

提到從下一個編輯的運行一些日誌以獲得更多幫助。

編輯 requestLocationPermission()要求用戶允許使用該權限啓用。

 protected void requestLocationPermission() { 
     Log.i(TAG, "LOCATION permission has NOT been granted. Requesting permission."); 

     if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), 
       Manifest.permission.ACCESS_FINE_LOCATION) || ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), 
       Manifest.permission.ACCESS_COARSE_LOCATION)) { 
      // Provide an additional rationale to the user if the permission was not granted 
      // and the user would benefit from additional context for the use of the permission. 
      // For example if the user has previously denied the permission. 
      Log.i(TAG, 
        "Displaying location permission rationale to provide additional context."); 
// some snackbar thingy 
     } else { 
      // Camera permission has not been granted yet. Request it directly. 
      ActivityCompat.requestPermissions(getActivity(), PERMISSIONS_LOCATION, 
        REQUEST_LOCATION); 
     } 
    } 
+0

requestLocationPermission(); ? –

0

試試這個..

List<String> providers = mLocationManager.getProviders(true); 
android.location.Location bestLocation = null; 
for (String provider : providers) { 
    android.location.Location l = mLocationManager.getLastKnownLocation(provider); 
    if (l == null) { 
     continue; 
    } 
    if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) { 
     // Found best last known location: %s", l); 
     bestLocation = l; 
    } 
} 
//bestlocation is required location 
0

getLastKnownLocation將返回null如果沒有緩存的最後已知位置。與人們認爲操作系統不保證存儲它在內存中接收到的最後一個位置不同,根據我的經驗,這種設備之間會發生變化,因此您應該始終檢查是否爲空並進行相應處理。

因此,要真正回答您的問題,如果最後一個已知位置爲空,您需要獲取或等待當前位置。

http://developer.android.com/training/location/receive-location-updates.html