2017-02-04 4 views
-1

Мое требование очень простое.Невозможно получить координаты местоположения и отобразить их на экране

Я хочу получить местоположение пользователя и отобразить его на экране.

Эмулятор показывает текущее местоположение. Но я не могу извлечь то же самое в свой TextView. Не совсем уверен, что здесь не так.

Пожалуйста, найдите мой код ниже. Помогите оценить.

MainActivity.java

package com.varun.weatherbee; 

import android.content.pm.PackageManager; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.os.Bundle; 
import android.support.v4.app.ActivityCompat; 
import android.support.v7.app.AppCompatActivity; 
import android.util.Log; 
import android.widget.TextView; 

import java.util.List; 

public class MainActivity extends AppCompatActivity implements LocationListener { 

    private final static String TAG = MainActivity.class.getSimpleName(); 

    TextView mLongitudeText; 
    TextView mLatitudeText; 

    LocationManager locationManager; 
    Location location; 
    double latitude; 
    double longitutde; 

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

     mLatitudeText = (TextView) findViewById(R.id.mLatitudeText); 
     mLongitudeText = (TextView) findViewById(R.id.mLongitudeText); 

     locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); 
     List<String> providers = locationManager.getAllProviders(); 
     for (int i = 0; i < providers.size(); i++) { 
      Log.i(TAG, providers.get(i)); 
     } 
     if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.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. 
      Log.i(TAG, "Permission Granted"); 
      return; 
     } 
     location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
     if (location != null) { 
      mLatitudeText.setText("Latitude: " + location.getLatitude()); 
      mLongitudeText.setText("Longitude: " + location.getLongitude()); 
     } 
    } 

    @Override 
    protected void onStart() { 
     super.onStart(); 
     if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.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(LocationManager.GPS_PROVIDER, 10000, 1000, this); 
    } 

    @Override 
    protected void onStop() { 
     super.onStop(); 
     if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.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); 
    } 

    @Override 
    public void onLocationChanged(Location location) { 

    } 

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

    } 

    @Override 
    public void onProviderEnabled(String provider) { 

    } 

    @Override 
    public void onProviderDisabled(String provider) { 

    } 
} 
+0

Вы, вероятно, хотите обновить TextViews в onLocationChanged. –

ответ

1

попробовать этот код:

1.your выполнения permission проверки неправильно

2.Also getLastKnownLocation(LocationManager.GPS_PROVIDER) может возвращать нуль See here

3.you может изменить textview с обновленным расположением в onLocationChanged() метод

вот простой пример:

public class MainActivity extends AppCompatActivity implements LocationListener { 

    private final static String TAG = MainActivity.class.getSimpleName(); 

    TextView mLongitudeText; 
    TextView mLatitudeText; 

    LocationManager locationManager; 
    Location location; 
    double latitude; 
    double longitutde; 

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

     mLatitudeText = (TextView) findViewById(R.id.mLatitudeText); 
     mLongitudeText = (TextView) findViewById(R.id.mLongitudeText); 

     locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); 
     List<String> providers = locationManager.getAllProviders(); 
     for (int i = 0; i < providers.size(); i++) { 
      Log.i(TAG, providers.get(i)); 
     } 


     //location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 

     if (isLocationPermissionGranted()) { 
      location = getLastKnownLocation(); 
      if (location != null) { 
       mLatitudeText.setText("Latitude: " + location.getLatitude()); 
       mLongitudeText.setText("Longitude: " + location.getLongitude()); 
      } 
     } 
    } 


    private Location getLastKnownLocation() { 
     locationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE); 
     List<String> providers = locationManager.getProviders(true); 
     Location bestLocation = null; 
     for (String provider : providers) { 
      Location l = locationManager.getLastKnownLocation(provider); 
      if (l == null) { 
       continue; 
      } 
      if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) { 
       // Found best last known location: %s", l); 
       bestLocation = l; 
      } 
     } 
     return bestLocation; 
    } 

    @Override 
    protected void onStart() { 
     super.onStart(); 
     if (isLocationPermissionGranted()) 
      locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 1000, this); 
    } 

    @Override 
    protected void onStop() { 
     super.onStop(); 
     locationManager.removeUpdates(this); 
    } 

    @Override 
    public void onLocationChanged(Location location) { 
     mLatitudeText.setText("Latitude: " + location.getLatitude()); 
     mLongitudeText.setText("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) { 

    } 

    public boolean isLocationPermissionGranted() { 
     if (Build.VERSION.SDK_INT >= 23) { 
      if (checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) 
        == PackageManager.PERMISSION_GRANTED) { 
       Log.v(TAG, "Permission is granted"); 
       return true; 
      } else { 

       Log.v(TAG, "Permission is revoked"); 
       ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1); 
       return false; 
      } 
     } else { //permission is automatically granted on sdk<23 upon installation 
      Log.v(TAG, "Permission is granted"); 
      return true; 
     } 
    } 


    @Override 
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { 
     super.onRequestPermissionsResult(requestCode, permissions, grantResults); 
     if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { 
      Log.v(TAG, "Permission: " + permissions[0] + "was " + grantResults[0]); 
      //resume tasks needing this permission 
     } 
    } 
} 
+0

Да, мой getLastKnownLocation действительно возвращал null. Вы, например, много помогли! Спасибо! –

+0

Если ответ работает, отметьте его как правильное для будущих ссылок ... thankx – rafsanahmad007

+0

Сделано! Забыл отметить как ответ :) –

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