Как получить текущее местоположение (широту, долготу) на adroid с помощью deviceAdministrator? - PullRequest
0 голосов
/ 06 мая 2020

Я хочу получить текущее местоположение (широта, долгота) при неудачной попытке разблокировать телефон

этот класс для получения последнего местоположения

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;

public class LocationSample {

    FusedLocationProviderClient mFusedLocationClient;

    String latitudeText = "0", longitudeText = "0";

    Context context;

    LocationSample(Context ctx)
    {
        context = ctx;
        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(ctx);
    }
    @SuppressLint("MissingPermission")
    public void getLastLocation(){

        if (checkPermissions()) {
            if (isLocationEnabled()) {
                mFusedLocationClient.getLastLocation().addOnCompleteListener(
                        new OnCompleteListener<Location>() {
                            @Override
                            public void onComplete(@NonNull Task<Location> task) {
                                Location location = task.getResult();
                                if (location == null) {
                                    requestNewLocationData();
                                } else {
                                    latitudeText = String.valueOf(location.getLatitude()) ;
                                    longitudeText = String.valueOf(location.getLongitude()) ;

                                }
                            }
                        }
                );
            } else {
                /*Toast.makeText(this, "Turn on location", Toast.LENGTH_LONG).show();
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(intent);*/
                Log.d("LocationSample", "GPS is disabled !!!");
                Toast.makeText(context, "GPS is disabled !!!", Toast.LENGTH_LONG).show();
            }
        } else {
            Log.d("LocationSample", "there is no permession for location");
            Toast.makeText(context, "there is no permession for location", Toast.LENGTH_LONG).show();
        }
    }

    private LocationCallback mLocationCallback = new LocationCallback() {
        @Override
        public void onLocationResult(LocationResult locationResult) {
            Location location = locationResult.getLastLocation();
            latitudeText = String.valueOf(location.getLatitude());
            longitudeText = String.valueOf(location.getLongitude());
        }
    };

    @SuppressLint("MissingPermission")
    private void requestNewLocationData(){

        Toast.makeText(context, "requestNewLocationData", Toast.LENGTH_LONG).show();
        LocationRequest mLocationRequest = new LocationRequest();
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setInterval(0);
        mLocationRequest.setFastestInterval(0);
        mLocationRequest.setNumUpdates(1);

        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(context);
        mFusedLocationClient.requestLocationUpdates(
                mLocationRequest, mLocationCallback,
                Looper.myLooper()
        );

    }


    private boolean checkPermissions() {
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission( context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            return true;
        }
        return false;
    }


    private boolean isLocationEnabled() {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(
                LocationManager.NETWORK_PROVIDER
        );
    }

    public String getLatitudeText() {
        return latitudeText;
    }

    public String getLongitudeText() {
        return longitudeText;
    }

}

И я звоню функции getLastLocation () и getLatitudeText () и getLongitudeText () в функции onPasswordFailed () класса DeviceAdminSampleReceiver, но всегда получаю Latitude = 0 / Longitude = 0

 @SuppressLint("LongLogTag")
    @Override
    public void onPasswordFailed(Context context, Intent intent) {
        super.onPasswordFailed(context, intent);

        Log.d(TAG, "onPasswordFailed");

        int attempts =0;
        DevicePolicyManager DevicePolicyManager=
                (DevicePolicyManager)context.getSystemService(Context.DEVICE_POLICY_SERVICE);
        if(DevicePolicyManager != null)
            attempts = DevicePolicyManager.getCurrentFailedPasswordAttempts();


        //GetLastLocation
        LocationSample detectedLocation = new LocationSample(context);
        detectedLocation.getLastLocation();
        String Latitude = "Latitude = " + detectedLocation.getLatitudeText();
        String Longitude = "Longitude = " + detectedLocation.getLongitudeText();

        Log.d(TAG, Latitude);
        Log.d(TAG, Longitude);

    }

1 Ответ

0 голосов
/ 15 мая 2020
import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;

public class AppLocationService extends Service implements LocationListener {

protected LocationManager locationManager;
Location location;

private static final long MIN_DISTANCE_FOR_UPDATE = 10;
private static final long MIN_TIME_FOR_UPDATE = 1000 * 60 * 2;

public AppLocationService(Context context) {
    locationManager = (LocationManager) context
            .getSystemService(LOCATION_SERVICE);
}

@SuppressLint("MissingPermission")
public Location getLocation(String provider) {
    if (locationManager.isProviderEnabled(provider)) {
        locationManager.requestLocationUpdates(provider,
                MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
        if (locationManager != null) {
            location = locationManager.getLastKnownLocation(provider);
            return location;
        }

    }
    return null;
}

@Override
public void onLocationChanged(Location location) {
}

@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;
}

}

для вызова Службы геолокации:

AppLocationService appLocationService = new AppLocationService(context);
                    Location gpsLocation = appLocationService
                            .getLocation(LocationManager.GPS_PROVIDER);
                    if (gpsLocation != null) {
                        double latitude = gpsLocation.getLatitude();
                        double longitude = gpsLocation.getLongitude();
                        String result = "Latitude: " + gpsLocation.getLatitude() +
                                " Longitude: " + gpsLocation.getLongitude();
                        Log.d(TAG, "resulat location = " + result);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...