Получение нулевого местоположения, несмотря на проверку всего - PullRequest
0 голосов
/ 02 февраля 2019

Я хочу получить доступ к позиции пользователя с помощью системы GPS телефона.

В манифест я включил

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-feature android:name="android.hardware.location.gps" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

Я получаю нулевое местоположение в.appLocationService.getLocation ();

public class MainActivity extends AppCompatActivity {
AppLocationService appLocationService;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    appLocationService = new AppLocationService(MainActivity.this);
}
public void OpenAddress(View v) {
    appLocationService =new AppLocationService(MainActivity.this);
    Location location = appLocationService.getLocation();
    if (location != null) {
        // getting co-ordinates and address
    }
    else showSettingsAlert();
  }
}

Я получаю нулевое местоположение в .getLastKnownLocation (поставщик); Здесь я получаю все местоположения от всех поставщиков.Но все, кажется, возвращают нулевое местоположение

public class AppLocationService extends Service implements LocationListener {
public AppLocationService(){}
Context mcontext;protected LocationManager locationManager;Location location;
private static final long MIN_DISTANCE_FOR_UPDATE = 10, MIN_TIME_FOR_UPDATE = 1000 * 60;
public AppLocationService(Context context) {
    locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    mcontext=context;
}
public Location getLocation() {
    boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    if (!isGPSEnabled) //enabling it    
    else {
        if (locationManager != null) {
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
            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())
                    bestLocation=l;
            }
            return bestLocation;
        }
    }
    return null;
}

1 Ответ

0 голосов
/ 02 февраля 2019

Вот полное решение.Я написал это и работает довольно хорошо на моем устройстве.Я также поделился на github.

Github: нажмите здесь

MainActivity.java

public class MainActivity extends AppCompatActivity {

    AppLocationService mAppLocationService;
    boolean mBounded;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = (Button) findViewById(R.id.callLocation);

    }

    public void OpenAddress(View view){
        Location location = mAppLocationService.getLastKnownLocation();
        if (location != null){
            Log.e("location","latitude:"+location.getLatitude()+" longtitude"+location.getLongitude());
        }else {
            Log.e("location","location return null");
        }
    }

    ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {

            mBounded = true;
            AppLocationService.LocalBinder binder = (AppLocationService.LocalBinder) service;
            mAppLocationService = binder.getInstance();

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mBounded = false;
            mAppLocationService = null;
        }
    };

    @Override
    protected void onStart() {
        super.onStart();
        Intent i = new Intent(MainActivity.this,AppLocationService.class);
        bindService(i,mConnection,BIND_AUTO_CREATE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mBounded){
            unbindService(mConnection);
            mBounded = false;
        }
    }


}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/callLocation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="OpenAddress"
        android:text="Location"/>

</android.support.constraint.ConstraintLayout>

AppLocationService.java

public class AppLocationService extends Service implements LocationListener {

    Location location;
    Context mcontext;
    protected LocationManager locationManager;
    private static final long MIN_DISTANCE_FOR_UPDATE = 10, MIN_TIME_FOR_UPDATE = 1000 * 60;
    IBinder binder = new LocalBinder();

    @Override
    public void onCreate() {
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    public class LocalBinder extends Binder{
        public AppLocationService getInstance(){
            return AppLocationService.this;
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    public Location getLastKnownLocation() {
        final long MIN_DISTANCE_FOR_UPDATE = 10, MIN_TIME_FOR_UPDATE = 1000 * 60;
        Location bestLocation = null;
        boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if (isGPSEnabled) {
            if (Permissions.getInstance(this).checkLocationPermission()) {
                locationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
                List<String> providers = locationManager.getProviders(true);
                for (String provider : providers) {

                    Location l = locationManager.getLastKnownLocation(provider);

                    if (l == null) {
                        continue;
                    }
                    if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
                        bestLocation = l;

                    }
                }
            }
        } else {
            Log.e("check", "Gps is not enable");
        }
        return bestLocation;
    }

    @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) {

    }
}

Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.shahz.testing">

    <!--
         The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
         Google Maps Android API v2, but you must specify either coarse or fine
         location permissions for the 'MyLocation' functionality. 
    -->
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-feature android:name="android.hardware.location.gps" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

<service android:name=".AppLocationService"/>
    </application>

</manifest>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...