如何在Android中获取用户的当前位置

切特纳

我想长按一下按钮来获取用户当前的经纬度。我知道您可以使用FusedLocationApi获取最近的已知位置。但是我无法理解的是,是否需要为此打开GPS或位置服务?如果是,如何检查用户已打开位置并获取当前位置。另外,如何在获取位置时包括棉花糖权限检查。

我已经提到过:1)googlesamples / android-play-location 2)googlesamples / android-XYZTouristAttractions和许多其他链接,但无法完成完整的流程。

代码

public class AccessLocationFragment extends BaseFragment implements View.OnClickListener, LocationListener,
    GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, GeneralDialogFragment.GeneralDialogClickListener {

private static final int MY_PERMISSIONS_REQUEST_LOCATION = 101;
private static final String TAG = AccessLocationFragment.class.getSimpleName();
private static final int REQUEST_CHECK_SETTINGS = 102;
private Button mAccessLocation;
private EditText mZipCode;
private Dialog progressDialog;
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;

public static AccessLocationFragment newInstance() {
    return new AccessLocationFragment();
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_access_location, container, false);
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    RecycleApplication.getEventBus().register(this);
    mAccessLocation = (Button) view.findViewById(R.id.access_location);
    mZipCode = (EditText) view.findViewById(R.id.zip_code);
    mAccessLocation.setOnClickListener(this);

    mZipCode.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                String zipCode = mZipCode.getText().toString().trim();
                if (TextUtils.isEmpty(zipCode)) {
                    Toast.makeText(mActivity, "Please enter zip code", Toast.LENGTH_SHORT).show();
                } else {
                    Call<Address> response = mRecycleService.getAddress(zipCode);
                    response.enqueue(new GetLocationCallback(AccessLocationFragment.this));
                }
            }
            return false;
        }
    });
    // Create an instance of GoogleAPIClient.
    if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(mActivity)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }
    if (!LocationUtils.checkFineLocationPermission(mActivity)) {
        // See if user has denied permission in the past
        if (shouldShowRequestPermissionRationale(android.Manifest.permission.ACCESS_FINE_LOCATION)) {
            // Show a simple snackbar explaining the request instead
            showPermissionSnackbar();
        } else {
            requestFineLocationPermission();
        }
    } else {
        displayLocationSettingsRequest();
    }
}

private void startHomeActivity(Address address) {
    RecyclePreferences.getInstance().setCity(address.getCity());
    RecyclePreferences.getInstance().setState(address.getState());
    RecyclePreferences.getInstance().setLatitude(address.getLatitude());
    RecyclePreferences.getInstance().setLongitude(address.getLongitude());
    RecyclePreferences.getInstance().setZipCode(address.getZipCode());
    startActivity(new Intent(mActivity, HomeActivity.class));
    mActivity.finish();
}

@Override
public void onSuccess(Call<Address> call, Response<Address> response) {
    mActivity.hideProgressDialog(progressDialog);
    if (response.isSuccessful()) {
        Address address = response.body();
        startHomeActivity(address);
    }
}

@Override
public void onFailure(Call<Address> call, Throwable t) {
    mActivity.hideProgressDialog(progressDialog);
}

@Override
public void onClick(View view) {
    if (view.getId() == R.id.access_location) {
        fetchAddress(mLastLocation);
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_LOCATION: {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
               displayLocationSettingsRequest();
            }
        }
    }
}

private void fetchAddress(Location location) {
    mRecycleService = new RecycleRetrofitBuilder(mActivity).getService();
    Call<Address> response = mRecycleService.getAddress(String.valueOf(location.getLatitude()), String.valueOf(location.getLongitude()));
    progressDialog = mActivity.showProgressDialog(mActivity);
    response.enqueue(new GetLocationCallback(AccessLocationFragment.this));
}

private void requestFineLocationPermission() {
    requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION);
}

private void showPermissionSnackbar() {
    GeneralDialogFragment generalDialogFragment = GeneralDialogFragment.
            newInstance("Permissions", "Allow Recycle the World to use your location.", "Allow", "Go Back", this);
    mActivity.showDialogFragment(generalDialogFragment);
    displayLocationSettingsRequest();
}

private void displayLocationSettingsRequest() {
    LocationRequest locationRequest = LocationRequest.create();
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationRequest.setInterval(10000);
    locationRequest.setFastestInterval(10000 / 2);

    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
    builder.setAlwaysShow(true);

    PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
    result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
        @Override
        public void onResult(LocationSettingsResult result) {
            final Status status = result.getStatus();
            switch (status.getStatusCode()) {
                case LocationSettingsStatusCodes.SUCCESS:
                    getLocation();
                    break;
                case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                    Log.i(TAG, "Location settings are not satisfied. Show the user a dialog to upgrade location settings ");
                    try {
                        status.startResolutionForResult(mActivity, REQUEST_CHECK_SETTINGS);
                    } catch (IntentSender.SendIntentException e) {
                        Log.i(TAG, "PendingIntent unable to execute request.");
                    }
                    break;
                case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                    Log.i(TAG, "Location settings are inadequate, and cannot be fixed here. Dialog not created.");
                    break;
            }
        }
    });
}

private void getLocation() {
    if (ActivityCompat.checkSelfPermission(mActivity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(mActivity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REQUEST_CHECK_SETTINGS) {
        getLocation();
    }
}

@Override
public void onStart() {
    mGoogleApiClient.connect();
    super.onStart();
}

@Override
public void onStop() {
    mGoogleApiClient.disconnect();
    super.onStop();
}

@Override
public void onConnected(@Nullable Bundle bundle) {
    getLocation();
}

@Override
public void onDestroy() {
    super.onDestroy();
    RecycleApplication.getEventBus().unregister(this);
}


@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}

@Override
public void onOk(DialogFragment dialogFragment) {
    dialogFragment.dismiss();
    requestFineLocationPermission();
}

@Override
public void onCancel(DialogFragment dialogFragment) {
    dialogFragment.dismiss();

}

}

班达夫

抱歉,我没有遍历您的代码,我只是在编写您在问题中要求的功能。首先,您需要建立与google api客户端的连接,例如:

private synchronized void buildGoogleApiClient(){
    mGoogleApiClient = new GoogleApiClient.Builder(GTApplication.getContext())
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    mGoogleApiClient.connect();
}

根据我的经验,您几乎总是会得到被调用的onConnected()函数,在该函数之后,您可以在API级别23之后请求位置许可:

public void checkLocationPermission(){
    if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
        // You don't have the permission you need to request it 
        ActivityCompat.requestPermissions(this, Manifest.permission.ACCESS_FINE_LOCATION), REQ_CODE);
    }else{
        // You have the permission.
        requestLocationAccess();
    }
}

如果您请求许可,onRequestPermissionsResult()则将使用调用您的函数REQ_CODE如果您需要更多信息来实现事件,请查看原始文档以获取运行时权限,这非常有用。
拥有权限后,您可以检查位置是否已启用,例如:

public void requestLocationAccess(){
    LocationRequest mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval((long) (LocationHelper.UPDATE_INTERVAL_IN_MILLISECONDS*1.1));
    mLocationRequest.setFastestInterval(LocationHelper.UPDATE_INTERVAL_IN_MILLISECONDS);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    final LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(mLocationRequest);
    builder.setAlwaysShow(true); //this is the key ingredient
    com.google.android.gms.common.api.PendingResult<LocationSettingsResult> result =
                LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
    result.setResultCallback(new ResultCallback<LocationSettingsResult>(){
        @Override
        public void onResult(@NonNull LocationSettingsResult result){
            if(requester != null){
                final Status resultStatus = result.getStatus();
                switch(resultStatus.getStatusCode()){
                    case LocationSettingsStatusCodes.SUCCESS:
                        // All location settings are satisfied. You can ask for the user's location HERE



                        break;
                    case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                        // Location settings are not satisfied. But could be fixed by showing the user a dialog.
                        try{
                            resultStatus.startResolutionForResult(this, REQUEST_LOCATION);
                            break;
                        }catch(IntentSender.SendIntentException ignored){}
                    }
                }
            }
        }
    });  
}

如果需要向用户显示启用位置对话框,您将获得onActivityResult()带有请求代码的函数回调REQUEST_LOCATION

完成所有此过程后,您就可以呼叫locationManager.getLastKnownLocation()或启动位置请求或任何您想要的操作。

PS .:我已经从较大的类中删除了此代码,因此,如果您发现任何错误,请随时提出。我只指定了一切顺利的情况,因为它包含了本质,您可以自己处理希望的异常。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

如何在Android中获取用户的当前位置

来自分类Dev

如何在Dialogflow chatbot中获取用户的当前位置?

来自分类Dev

如何在android中获取准确的当前位置?

来自分类Dev

如何在android中获取准确的当前位置?

来自分类Dev

如何在不使用核心位置服务的情况下获取用户的当前城市名称?

来自分类Dev

如何在不使用核心位置服务的情况下获取用户的当前城市名称?

来自分类Dev

如何让谷歌地图api获取用户的当前位置以将其存储在数据库中?

来自分类Dev

Google Maps iOS SDK,获取用户的当前位置

来自分类Dev

Google Maps iOS SDK,获取用户的当前位置

来自分类Dev

如何使用Google Geocode API和PHP获取用户的当前位置

来自分类Dev

尝试在 Dialogflow 中获取用户的当前位置时遇到错误

来自分类Dev

如何在mkmapview中查找用户的当前位置

来自分类Dev

如何在angularjs中获取元素的当前位置

来自分类Dev

在Zig中获取用户输入的当前方法

来自分类Dev

在Android中获取用户当前的城市

来自分类Dev

如何在后台在android中24x7运行服务以获取用户的位置

来自分类Dev

如何在android中获取webview的当前活动

来自分类Dev

在我的android应用程序中获取用户的当前手机号码

来自分类Dev

如何重构此获取用户当前位置的 JS 代码?

来自分类Dev

使用IOS中的CLLocation获取用户当前位置

来自分类Dev

如何在ng-autocomplete中添加用户的当前位置

来自分类Dev

如何在ASP.NET Core中获取用于登录重定向的当前应用程序相对URL

来自分类Dev

获取用户当前位置 - Kotlin

来自分类Dev

如何在Facebook API中获取用户位置和用户家乡?

来自分类Dev

如何在Facebook API中获取用户位置和用户家乡?

来自分类Dev

在不使用GPS或互联网的情况下获取用户的当前位置名称,而是通过在Android中使用Network_Provider

来自分类Dev

如何在PHP中获取当前月份的当前周数

来自分类Dev

如何获取用户的当前ID传递给_Layout ASP.NET Core?

来自分类Dev

Powerpoint如何获取用户所在的当前缩放百分比?

Related 相关文章

  1. 1

    如何在Android中获取用户的当前位置

  2. 2

    如何在Dialogflow chatbot中获取用户的当前位置?

  3. 3

    如何在android中获取准确的当前位置?

  4. 4

    如何在android中获取准确的当前位置?

  5. 5

    如何在不使用核心位置服务的情况下获取用户的当前城市名称?

  6. 6

    如何在不使用核心位置服务的情况下获取用户的当前城市名称?

  7. 7

    如何让谷歌地图api获取用户的当前位置以将其存储在数据库中?

  8. 8

    Google Maps iOS SDK,获取用户的当前位置

  9. 9

    Google Maps iOS SDK,获取用户的当前位置

  10. 10

    如何使用Google Geocode API和PHP获取用户的当前位置

  11. 11

    尝试在 Dialogflow 中获取用户的当前位置时遇到错误

  12. 12

    如何在mkmapview中查找用户的当前位置

  13. 13

    如何在angularjs中获取元素的当前位置

  14. 14

    在Zig中获取用户输入的当前方法

  15. 15

    在Android中获取用户当前的城市

  16. 16

    如何在后台在android中24x7运行服务以获取用户的位置

  17. 17

    如何在android中获取webview的当前活动

  18. 18

    在我的android应用程序中获取用户的当前手机号码

  19. 19

    如何重构此获取用户当前位置的 JS 代码?

  20. 20

    使用IOS中的CLLocation获取用户当前位置

  21. 21

    如何在ng-autocomplete中添加用户的当前位置

  22. 22

    如何在ASP.NET Core中获取用于登录重定向的当前应用程序相对URL

  23. 23

    获取用户当前位置 - Kotlin

  24. 24

    如何在Facebook API中获取用户位置和用户家乡?

  25. 25

    如何在Facebook API中获取用户位置和用户家乡?

  26. 26

    在不使用GPS或互联网的情况下获取用户的当前位置名称,而是通过在Android中使用Network_Provider

  27. 27

    如何在PHP中获取当前月份的当前周数

  28. 28

    如何获取用户的当前ID传递给_Layout ASP.NET Core?

  29. 29

    Powerpoint如何获取用户所在的当前缩放百分比?

热门标签

归档