1

Я создаю приложение, которое получит имя пользователя от DB и распечатает ID, а затем нажав кнопку, он отобразит текущий GPS coordinates. Я реализовал его, но не знаю, почему он не работает.Невозможно просмотреть текущие координаты при нажатии кнопки в студии android

Вот мой Manifest файл

<uses-permission android:name="android.permission.INTERNET"/> 
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> 
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> 
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> 

Ниже мой MainActivity.java

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


private static final String TAG = "MainActivity"; 
private TextView tv_lat; 
private TextView tv_long; 
private Button btn_loc; 
private GoogleApiClient googleApiClient; 
private Location location; 
private LocationManager mLocationManager; 
private LocationManager locationManager; 

private LocationRequest locationRequest; 
private LocationListener locationListener; 
private long UPDATE_INTERVAL = 2 * 1000; /* 10 secs */ 
private long FASTEST_INTERVAL = 2000; /* 2 sec */ 

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

    tv_lat = (TextView)findViewById(R.id.tv_lat); 
    tv_long = (TextView)findViewById(R.id.tv_long); 
    btn_loc = (Button)findViewById(R.id.btn_loc); 


    // show location button click event 
    btn_loc.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      googleApiClient = new GoogleApiClient.Builder(MainActivity.this) 
        .addConnectionCallbacks(MainActivity.this) 
        .addOnConnectionFailedListener(MainActivity.this) 
        .addApi(LocationServices.API) 
        .build(); 


     } 
    }); 

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

    checkLocation(); //check whether location service is enable or not in your phone 

} 

@Override 
public void onConnected(Bundle bundle) { 

    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; 
    } 
    startLocationUpdates(); 

    location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient); 

    if(location == null) 
    { 
     startLocationUpdates(); 
    } 
    if (location != null) 
    { 

    } 
    else { 
     Toast.makeText(this, "Location not Detected", Toast.LENGTH_SHORT).show(); 
    } 

} 

@Override 
public void onConnectionSuspended(int i) { 

    Log.i(TAG, "Connection Suspended"); 
    googleApiClient.connect(); 

} 

@Override 
public void onConnectionFailed(ConnectionResult connectionResult) { 
    Log.i(TAG, "Connection failed. Error: " + connectionResult.getErrorCode()); 
} 

@Override 
protected void onStart() { 
    super.onStart(); 
    if (googleApiClient != null) { 
     googleApiClient.connect(); 
    } 
} 

@Override 
protected void onStop() { 
    super.onStop(); 
    if (googleApiClient.isConnected()) { 
     googleApiClient.disconnect(); 
    } 
} 

private void startLocationUpdates() { 

    // Create the location request 
    locationRequest = LocationRequest.create() 
      .setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY) 
      .setInterval(UPDATE_INTERVAL) 
      .setFastestInterval(FASTEST_INTERVAL); 

    // Request location updates 
    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; 
    } 
    LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, 
      locationRequest, this); 
    Log.d("reque", "--->>>>"); 
} 

@Override 
public void onLocationChanged(Location location) { 

    double lattitude = location.getLatitude(); 
    double longitude = location.getLongitude(); 

    String msg = "Updated Location: " + 
      Double.toString(lattitude) + " , " + 
      Double.toString(longitude); 

    tv_lat.setText("Latitude is " + lattitude); 
    tv_long.setText("Longitude is " + longitude); 

    Toast.makeText(this, msg, Toast.LENGTH_SHORT).show(); 

    // You can now create a LatLng Object for use with maps 
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude()); 

} 

private boolean checkLocation() { 

    if(!isLocationEnabled()) 
    showAlert(); 

    return isLocationEnabled(); 
} 


private boolean isLocationEnabled() { 
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
    return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || 
      locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); 
} 
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99; 
private void showAlert() { 

    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) 
      != PackageManager.PERMISSION_GRANTED) { 
     // Should we show an explanation? 
     if (ActivityCompat.shouldShowRequestPermissionRationale(this, 
       Manifest.permission.ACCESS_FINE_LOCATION)) { 

      final AlertDialog.Builder dialog = new AlertDialog.Builder(this); 
      dialog.setTitle("Enable Location") 
        .setMessage("Your Locations Settings is set to 'Off'.\nPlease Enable Location to " + 
          "use this app") 
        .setPositiveButton("Location Settings", new DialogInterface.OnClickListener() { 
         @Override 
         public void onClick(DialogInterface paramDialogInterface, int paramInt) { 

          Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
          startActivity(myIntent); 
         } 
        }) 
        .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
         @Override 
         public void onClick(DialogInterface paramDialogInterface, int paramInt) { 

         } 
        }); 
      dialog.create().show(); 
     } 
    } 
    else { 
     // No explanation needed, we can request the permission. 
     ActivityCompat.requestPermissions(this, 
       new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 
       MY_PERMISSIONS_REQUEST_LOCATION); 
    } 
} 


} 

Когда я бегу мое приложение на устройстве, ниже результат показан

enter image description here

Когда я нажимаю на get location coordinates ничего не происходит. Также в logcat ошибок и предупреждений нет.

Update 1

Я переместил весь код вне от button click события

googleApiClient = new GoogleApiClient.Builder(this) 
      .addConnectionCallbacks(this) 
      .addOnConnectionFailedListener(this) 
      .addApi(LocationServices.API) 
      .build(); 
    googleApiClient.connect(); 

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

А потом отлажена, и я получил результат ниже.

enter image description here

Я не знаю, почему координаты не отображаются :(

Любая помощь будет высоко оценен

+0

, на чьей странице вы работаете? зефир или нуга? и предоставили ли вы разрешения? –

+0

Предлагаю вам ознакомиться с учебным пособием и загрузить исходный код. Здесь вы найдете все детали. Gotto этот ответ, вы найдете ссылку там. http://stackoverflow.com/questions/1513485/how-do-i-get-the-current-gps-location-programmatically-in-android/36110892#36110892 –

+0

@HammadNasir Я запускаю его на зефир и да, у меня есть установить разрешения – faisal1208

ответ

1

Когда ваше устройство находится над Android 6.0 Marshmal вы должны проверить, разрешено ли разрешение местоположения в настройках приложения. Вы можете включить его вручную в настройках или использовать библиотеку разрешений времени выполнения. Я нашел для этого очень полезную библиотеку: https://github.com/ParkSangGwon/TedPermission

+1

ОК, попробовав это – faisal1208

+0

Он попросил меня разрешения и, разрешив его, он все еще не показывает мне координаты :( – faisal1208

+0

Вы пытались перезапустить приложение после вас получил разрешение на размещение? –

1

перейти на мобильные настройки -.> Место проверить ли ваш мобильное устройство GPS включено или выключено и включается, если оно выключено. надеюсь, что это поможет.

+0

Мои настройки местоположения включены на моем устройстве – faisal1208

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