我有此活动想要获取当前位置,但现在没有如何以正确的方式完成它..REQUEST_CODE_ASK_PERMISSIONS是什么?
我必须生成一个吗?
public class MainActivity extends AppCompatActivity implements Googleapiclient.ConnectionCallbacks, Googleapiclient.OnConnectionFailedListener { private double longitude; private double latitude; private TextVIEw latitudeText, longitudeText; private FusedLocationProvIDerClIEnt fusedLocationProvIDerClIEnt; private Googleapiclient Googleapiclient; private LocationManager locationManager; private LocationListener locationListener; private LocationRequest locationRequest; private LocationCallback locationCallback; final private int REQUEST_CODE_ASK_PERMISSIONS = 123; @OverrIDe protected voID onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentVIEw(R.layout.activity_main); latitudeText = findVIEwByID(R.ID.latitudeText); longitudeText = findVIEwByID(R.ID.longitudeText); getLocation(); } private voID getLocation() { locationRequest = new LocationRequest() .setInterval(2000).setFastestInterval(2000).setPriority(1000); LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder() .addLocationRequest(locationRequest); SettingsClIEnt clIEnt = LocationServices.getSettingsClIEnt(this); Task<LocationSettingsResponse> task = clIEnt.checkLocationSettings(builder.build()); locationCallback = new LocationCallback() { @OverrIDe public voID onLocationResult(LocationResult locationResult) { for (Location location : locationResult.getLocations()) { latitude = location.getLatitude(); longitude = location.getLongitude(); latitudeText.setText(String.valueOf(latitude)); longitudeText.setText(String.valueOf(longitude)); } } }; task.addOnSuccessListener(this, new OnSuccessListener<LocationSettingsResponse>() { @OverrIDe public voID onSuccess(LocationSettingsResponse locationSettingsResponse) { } }); } @OverrIDe protected voID onResume() { super.onResume(); if (ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){ ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest .permission.ACCESS_FINE_LOCATION},REQUEST_CODE_ASK_PERMISSIONS); } else if(){ } } @OverrIDe public voID onConnected(@Nullable Bundle bundle) { } @OverrIDe public voID onConnectionSuspended(int i) { } @OverrIDe public voID onConnectionFailed(@NonNull ConnectionResult connectionResult) { }}
…………………………………………… …………………………………………… …………………………………………………………
解决方法:
在build.gradle(Module:app)中添加依赖项
implementation 'com.Google.androID.gms:play-services-location:16.0.0'
声明清单中的必要权限
<uses-permission androID:name="androID.permission.INTERNET"/><uses-permission androID:name="androID.permission.ACCESS_FINE_LOCATION"/><uses-permission androID:name="androID.permission.ACCESS_COARSE_LOCATION"/>
EasyLocationProvIDer.java
import androID.annotation.Suppresslint;import androID.arch.lifecycle.lifecycle;import androID.arch.lifecycle.lifecycleObserver;import androID.arch.lifecycle.OnlifecycleEvent;import androID.content.Context;import androID.content.IntentSender;import androID.os.Bundle;import androID.os.Looper;import androID.support.annotation.NonNull;import androID.support.annotation.Nullable;import androID.support.v7.app.AppCompatActivity;import androID.util.Log;import androID.Widget.Toast;import com.Google.androID.gms.common.ConnectionResult;import com.Google.androID.gms.common.GoogleAPIAvailability;import com.Google.androID.gms.common.API.APIException;import com.Google.androID.gms.common.API.Googleapiclient;import com.Google.androID.gms.common.API.ResolvableAPIException;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.location.LocationSettingsRequest;import com.Google.androID.gms.location.LocationSettingsResponse;import com.Google.androID.gms.location.LocationSettingsstatusCodes;import com.Google.androID.gms.location.SettingsClIEnt;import com.Google.androID.gms.tasks.OnCanceledListener;import com.Google.androID.gms.tasks.OnFailureListener;import com.Google.androID.gms.tasks.OnSuccessListener;public class EasyLocationProvIDer implements lifecycleObserver { private EasyLocationCallback callback; private Context context; private FusedLocationProvIDerClIEnt mFusedLocationClIEnt; private SettingsClIEnt mSettingsClIEnt; private LocationCallback mLocationCallback; private LocationRequest mLocationRequest; private Googleapiclient mGoogleapiclient; private LocationSettingsRequest mLocationSettingsRequest; private long interval; private long fastestInterval; private int priority; private double Latitude = 0.0, Longitude = 0.0; private EasyLocationProvIDer(final Builder builder) { context = builder.context; callback = builder.callback; interval = builder.interval; fastestInterval = builder.fastestInterval; priority = builder.priority; } @Suppresslint("MissingPermission") public voID requestLocationUpdate() { mFusedLocationClIEnt.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper()); } private voID connectGoogleClIEnt() { GoogleAPIAvailability GoogleAPI = GoogleAPIAvailability.getInstance(); int resultCode = GoogleAPI.isGooglePlayServicesAvailable(context); if (resultCode == ConnectionResult.SUCCESS) { mGoogleapiclient.connect(); } else { int REQUEST_Google_PLAY_SERVICE = 988; GoogleAPI.getErrorDialog((AppCompatActivity) context, resultCode, REQUEST_Google_PLAY_SERVICE); } } @OnlifecycleEvent(lifecycle.Event.ON_CREATE) private voID onCreateLocationProvIDer() { } @OnlifecycleEvent(lifecycle.Event.ON_RESUME) private voID onLocationResume() { buildGoogleapiclient(); } @Suppresslint("MissingPermission") private synchronized voID buildGoogleapiclient() { mFusedLocationClIEnt = LocationServices.getFusedLocationProvIDerClIEnt(context); mSettingsClIEnt = LocationServices.getSettingsClIEnt(context); mGoogleapiclient = new Googleapiclient.Builder(context) .addConnectionCallbacks(new Googleapiclient.ConnectionCallbacks() { @OverrIDe public voID onConnected(@Nullable Bundle bundle) { callback.onGoogleapiclient(mGoogleapiclient, "Connected"); mLocationRequest = new LocationRequest(); mLocationRequest.setInterval(interval); mLocationRequest.setFastestInterval(fastestInterval); mLocationRequest.setPriority(priority); mLocationRequest.setSmallestdisplacement(0); LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder(); builder.addLocationRequest(mLocationRequest); builder.setAlwaysShow(true); mLocationSettingsRequest = builder.build(); mSettingsClIEnt .checkLocationSettings(mLocationSettingsRequest) .addOnSuccessListener(new OnSuccessListener<LocationSettingsResponse>() { @OverrIDe public voID onSuccess(LocationSettingsResponse locationSettingsResponse) { showLog("GPS is Enabled Requested Location Update"); requestLocationUpdate(); } }).addOnFailureListener(new OnFailureListener() { @OverrIDe public voID onFailure(@NonNull Exception e) { int statusCode = ((APIException) e).getStatusCode(); switch (statusCode) { case LocationSettingsstatusCodes.RESolUTION_required: try { int REQUEST_CHECK_SETTINGS = 214; ResolvableAPIException rae = (ResolvableAPIException) e; rae.startResolutionForResult((AppCompatActivity) context, REQUEST_CHECK_SETTINGS); } catch (IntentSender.SendIntentException sIE) { showLog("Unable to Execute Request"); } break; case LocationSettingsstatusCodes.SETTINGS_CHANGE_UNAVAILABLE: showLog("Location Settings are Inadequate, and Cannot be fixed here. Fix in Settings"); } } }).addOnCanceledListener(new OnCanceledListener() { @OverrIDe public voID onCanceled() { showLog("onCanceled"); } }); } @OverrIDe public voID onConnectionSuspended(int i) { connectGoogleClIEnt(); callback.onGoogleapiclient(mGoogleapiclient, "Connection Suspended"); } }) .addOnConnectionFailedListener(new Googleapiclient.OnConnectionFailedListener() { @OverrIDe public voID onConnectionFailed(@NonNull ConnectionResult connectionResult) { callback.onGoogleapiclient(mGoogleapiclient, "" + connectionResult.getErrorCode() + " " + connectionResult.getErrorMessage()); } }) .addAPI(LocationServices.API) .build(); connectGoogleClIEnt(); mLocationCallback = new LocationCallback() { @OverrIDe public voID onLocationResult(final LocationResult locationResult) { super.onLocationResult(locationResult); Latitude = locationResult.getLastLocation().getLatitude(); Longitude = locationResult.getLastLocation().getLongitude(); if (Latitude == 0.0 && Longitude == 0.0) { showLog("New Location Requested"); requestLocationUpdate(); } else { callback.onLocationUpdated(Latitude, Longitude); } } }; } @Suppresslint("MissingPermission") public voID removeUpdates() { try { callback.onLocationUpdateRemoved(); } catch (Exception e) { e.printstacktrace(); } } private voID showLog(String message) { Log.e("EasyLocationProvIDer", "" + message); } public interface EasyLocationCallback { voID onGoogleapiclient(Googleapiclient Googleapiclient, String message); voID onLocationUpdated(double latitude, double longitude); voID onLocationUpdateRemoved(); } public static class Builder { private Context context; private EasyLocationCallback callback; private long interval = 10 * 1000; private long fastestInterval = 5 * 1000; private int priority = LocationRequest.PRIORITY_HIGH_ACCURACY; public Builder(Context context) { this.context = context; } public EasyLocationProvIDer build() { if (callback == null) { Toast.makeText(context, "EasyLocationCallback Listener can not be null", Toast.LENGTH_SHORT).show(); } return new EasyLocationProvIDer(this); } public Builder setListener(EasyLocationCallback callback) { this.callback = callback; return this; } public Builder setInterval(long interval) { this.interval = interval; return this; } public Builder setFastestInterval(int fastestInterval) { this.fastestInterval = fastestInterval; return this; } public Builder setPriority(int priority) { this.priority = priority; return this; } }}
采用:
EasyLocationProvIDer easyLocationProvIDer; //Declare Global VariableeasyLocationProvIDer = new EasyLocationProvIDer.Builder(BottomNavigationActivity.this) .setInterval(5000) .setFastestInterval(2000) //.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY) .setListener(new EasyLocationProvIDer.EasyLocationCallback() { @OverrIDe public voID onGoogleapiclient(Googleapiclient Googleapiclient, String message) { Log.e("EasyLocationProvIDer","onGoogleapiclient: "+message); } @OverrIDe public voID onLocationUpdated(double latitude, double longitude) { Log.e("EasyLocationProvIDer","onLocationUpdated:: "+ "Latitude: "+latitude+" Longitude: "+longitude); } @OverrIDe public voID onLocationUpdateRemoved() { Log.e("EasyLocationProvIDer","onLocationUpdateRemoved"); } }).build();getlifecycle().addobserver(easyLocationProvIDer);
删除位置更新回调
@OverrIDeprotected voID onDestroy() { easyLocationProvIDer.removeUpdates(); getlifecycle().removeObserver(easyLocationProvIDer); super.onDestroy();}
注意:授予棉花糖和更高版本的设备的权限
总结以上是内存溢出为你收集整理的java-使用融合的位置提供程序获取当前位置全部内容,希望文章能够帮你解决java-使用融合的位置提供程序获取当前位置所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)