繁体   English   中英

如何在 Android 中获取持续的位置更新?

[英]How can I get continuous location updates in Android?

GoogleApiClient已被弃用,现在我在学习获取持续位置更新的最新方法时遇到了一些麻烦。 另外,我可以使用LocationCallbackLocationRequetMethod获取位置更新吗?

我很高兴我终于找到了它。 代码很短。 我使用了LocationRequestLocationCallback方法。 此外,我已将fusedLocationProviderClient用于requestLocationUpdates

public class MainActivity extends AppCompatActivity {

    private FusedLocationProviderClient fusedLocationProviderClient;
    TextView locationTextView;
    LocationRequest locationRequest;

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

        locationTextView = findViewById(R.id.location_text);

        fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

//Not the best practices to get runtime permissions, but still here I ask permissions.
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 2);
        }

//Instantiating the Location request and setting the priority and the interval I need to update the location.
        locationRequest = locationRequest.create();
        locationRequest.setInterval(100);
        locationRequest.setFastestInterval(50);
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

//instantiating the LocationCallBack
        LocationCallback locationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(LocationResult locationResult) {
                if (locationResult != null) {
                    if (locationResult == null) {
                        return;
                    }
     //Showing the latitude, longitude and accuracy on the home screen.
                    for (Location location : locationResult.getLocations()) {
                        locationTextView.setText(MessageFormat.format("Lat: {0} Long: {1} Accuracy: {2}", location.getLatitude(),
                                location.getLongitude(), location.getAccuracy()));
                    }
                }
            }
        };
        fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.getMainLooper());
    }
}

activity_main.xml

<TextView
        android:id="@+id/location_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:fontFamily="@font/andika"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

另外,在所有这些之前,我在我的依赖项中添加了这个

    implementation 'com.google.android.gms:play-services-location:17.0.0'

这在我的清单


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

这会按照您选择的时间间隔不断更新

您好,您应该避免持续更新位置,因为它会耗尽电池电量。 您可以使用 locationlistner,您可以在其中收听位置变化。 假设您想更新位置并获取每 10 米变化的姿态和经度。

最后检查的示例代码,每 100 米长

class LocationService : Service(), LocationListener {
protected var locationManager: LocationManager? = null
var checkGPS = false
var checkNetwork = false

// boolean canGetLocation = false;
var loc: Location? = null

//    double latitude;
//    double longitude;
override fun onBind(intent: Intent): IBinder? {
    return null
}

override fun onLocationChanged(location: Location) {
    // Toast.makeText(getApplicationContext(), Double.toString(location.getLatitude()) + location.getLongitude(), Toast.LENGTH_LONG).show();
}

override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {}
override fun onProviderEnabled(provider: String) {}
override fun onProviderDisabled(provider: String) {}
override fun onCreate() {
    super.onCreate()
    location
}

        Toast.makeText(getApplicationContext(), Double.toString(latitude) + longitude + "from method", Toast.LENGTH_LONG).show();
private val location: Location?
    private get() {
        if (ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) !=
            PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_COARSE_LOCATION
            )
            != PackageManager.PERMISSION_GRANTED
        ) {
        }
        locationManager = applicationContext
            .getSystemService(LOCATION_SERVICE) as LocationManager
        checkGPS = locationManager!!
            .isProviderEnabled(LocationManager.GPS_PROVIDER)
        checkNetwork = locationManager!!
            .isProviderEnabled(LocationManager.NETWORK_PROVIDER)
        locationManager!!.requestLocationUpdates(
            LocationManager.GPS_PROVIDER,
            MIN_TIME_BW_UPDATES,
            MIN_DISTANCE_CHANGE_FOR_UPDATES.toFloat(), this
        )
        if (locationManager != null) {
            val fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
            fusedLocationClient.lastLocation.addOnSuccessListener { location ->
                if (location != null) {
                    Toast.makeText(
                        applicationContext,
                        java.lang.Double.toString(location.latitude) + location.longitude + "from method",
                        Toast.LENGTH_LONG
                    ).show()
                }
            }
        }
                Toast.makeText(getApplicationContext(), Double.toString(latitude) + longitude + "from method", Toast.LENGTH_LONG).show();
        return loc
    }

companion object {
    private const val MIN_DISTANCE_CHANGE_FOR_UPDATES: Long = 100
    private const val MIN_TIME_BW_UPDATES: Long = 30
}

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM