Я хочу получить место в Android 2.2, и я уже добавил Google gms play services library. И я могу установить requestLocationUpdates
и getLastKnownLocation
, но местоположение равно null.Не могу получить местоположение - Android
Этот лог напечатан только 03-10 01:23:13.720 27437-27437/? V/GPSTracker provider﹕ gps 03-10 01:23:13.720 27437-27437/? V/GPSTracker﹕ requestLocationUpdates 03-10 01:23:13.720 27437-27437/? V/GPSTracker﹕ getLastKnownLocation
. Широта и долгота не показывались.
package com.example.testlocation;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
public class GPSTracker extends Service implements LocationListener {
private Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
String provider = "";
float accuracy = 0;
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker() {
}
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, true);
if (provider != null) {
locationManager.requestLocationUpdates(provider,30000,10, this);
Log.v("GPSTracker", "requestLocationUpdates");
}
if (locationManager != null && provider != null) {
location = locationManager.getLastKnownLocation(provider);
Log.v("GPSTracker", "getLastKnownLocation");
if (location != null) {
accuracy = location.getAccuracy();
latitude = location.getLatitude();
longitude = location.getLongitude();
Log.v("GPSTracker", latitude+", "+longitude);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* @return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
@Override
public void onLocationChanged(Location location) {
this.location = location;
getLatitude();
getLongitude();
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
public String getProvider(){
return provider;
}
public float getAccuracy(){
return accuracy;
}
}
MainActivity.java
public class MainActivity extends ActionBarActivity {
private TextView tvLat, tvLong, tvProvider, tvAccuracy;
private Button btnRefresh;
private double latitude, longitude;
private GPSTracker gps;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvProvider = (TextView)findViewById(R.id.tvProvider);
tvAccuracy = (TextView)findViewById(R.id.tvAccuracy);
tvLat = (TextView)findViewById(R.id.tvLat);
tvLong = (TextView)findViewById(R.id.tvLong);
btnRefresh = (Button)findViewById(R.id.btnRefresh);
gps = new GPSTracker(this);
latitude = gps.getLatitude();
longitude = gps.getLongitude();
tvProvider.setText("Provider: "+gps.getProvider());
tvAccuracy.setText("Accuracy: "+gps.getAccuracy());
tvLat.setText("Latitude: "+latitude);
tvLong.setText("Longitude: "+longitude);
btnRefresh.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
latitude = gps.getLatitude();
longitude = gps.getLongitude();
tvProvider.setText("Provider: "+gps.getProvider());
tvAccuracy.setText("Accuracy: "+gps.getAccuracy());
tvLat.setText("Latitude: "+latitude);
tvLong.setText("Longitude: "+longitude);
}
});
}
}
Gradle
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:appcompat-v7:21.0.3'
compile 'com.google.android.gms:play-services:6.5.87'
}
файл манифеста
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.testlocation" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-sdk tools:overrideLibrary="com.google.android.gms"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<meta-data android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".GPSTracker" />
</application>
</manifest>
Хорошо, я должен спросить ... испытаны ли вы ваше приложение правильно? Вы двигались не менее 10 метров? И ждали 3 секунды? Тогда ваш 'onLocationChanged' должен был быть запущен, и если вы зарегистрировали что-то в нем, оно должно было быть напечатано ... Метод' getLastKnownLocation' может возвращать 'null', что является полностью нормальным, но ваш' onLocationChanged' должен был срабатывать после того, как вы переехали 10 м и после 3 секунд, и в нем должны были быть новые координаты ... – miselking
У меня меньше всего 10 минут, а широта и долгота все равно 0. –
Вы двигались 10 м в ожидании? Вам нужно переместиться и ждать времени для прохождения (согласно документации: «Параметр minDistance также может использоваться для управления частотой обновлений местоположения. Если он больше 0, поставщик местоположения будет отправлять ваше приложение только в том случае, если местоположение изменилось, по крайней мере, на minDistance meters, и по крайней мере minTime миллисекунды прошли. ») – miselking