【问题标题】:How do I get android location once at the push of a button?只需按一下按钮,我如何获得 android 位置?
【发布时间】:2016-06-21 06:06:04
【问题描述】:

我目前正在制作一个应用程序,我需要在单击按钮时获取用户的位置。我正在使用this 示例,它作为示例应用程序非常有用。我的问题是,如何将它实现到我的应用程序按钮的 onClick 事件中?我不需要它经常刷新,我只需要它,以便当用户单击按钮时,它会获取用户的纬度和经度并将它们保存到两个变量中。最好的方法是什么?我没有发布我自己的代码,因为我只有一个带有 onClick 事件的按钮。

【问题讨论】:

    标签: java android android-location


    【解决方案1】:

    按照以下步骤获取按钮点击的位置:

    在您的活动中实现LocationListener,例如:

       public class MainActivity Extends AppCompactActivity implements LocationListener
    

    然后为LocationManagerlongitudelatitude 创建一个实例,如下所示:

         LocationManager locationManager; // create global outside all methods
         Double currentLattitude, currentLongitude;
    

    在您的按钮上设置点击事件如下:

          btnLocation.setOnClickListner( new View.onClickListner
          {
              @Override
               public void onClick(View v)
                {
                      locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    
                      locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
                }
          });
    

    现在实现LocationListener的方法如下:

           @Override
           public void onLocationChanged(Location location) {
    
               currentLattitude = location.getLatitude();
               currentLongitude = location.getLongitude());
           }
    
           @Override
           public void onProviderDisabled(String provider) {
                 Log.d("Latitude","disable");
           }
    
           @Override
           public void onProviderEnabled(String provider) {
                  Log.d("Latitude","enable");
           }
    
           @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
                   Log.d("Latitude","status");
            }
    

    有了这个,你可以通过点击你的按钮来获得你的位置。

    不要忘记的主要事情是设置权限(在您的清单中),如下所示:

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

    【讨论】:

      【解决方案2】:

      使用 fused location API 这是最快的。

      public class LocationActivity extends Activity implements
              LocationListener,
              GoogleApiClient.ConnectionCallbacks,
              GoogleApiClient.OnConnectionFailedListener {
      
          private static final String TAG = "LocationActivity";
          private static final long INTERVAL = 1000 * 10;
          private static final long FASTEST_INTERVAL = 1000 * 5;
          Button btnFusedLocation;
          TextView tvLocation;
          LocationRequest mLocationRequest;
          GoogleApiClient mGoogleApiClient;
          Location mCurrentLocation;
          String mLastUpdateTime;
      
          protected void createLocationRequest() {
              mLocationRequest = new LocationRequest();
              mLocationRequest.setInterval(INTERVAL);
              mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
              mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
          }
      
          @Override
          protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              Log.d(TAG, "onCreate ...............................");
              //show error dialog if GoolglePlayServices not available
              if (!isGooglePlayServicesAvailable()) {
                  finish();
              }
              createLocationRequest();
              mGoogleApiClient = new GoogleApiClient.Builder(this)
                      .addApi(LocationServices.API)
                      .addConnectionCallbacks(this)
                      .addOnConnectionFailedListener(this)
                      .build();
      
              setContentView(R.layout.activity_main);
              tvLocation = (TextView) findViewById(R.id.tvLocation);
      
              btnFusedLocation = (Button) findViewById(R.id.btnShowLocation);
              btnFusedLocation.setOnClickListener(new View.OnClickListener() {
                  @Override
                  public void onClick(View arg0) {
                      updateUI();
                  }
              });
      
          }
      
          @Override
          public void onStart() {
              super.onStart();
              Log.d(TAG, "onStart fired ..............");
              mGoogleApiClient.connect();
          }
      
          @Override
          public void onStop() {
              super.onStop();
              Log.d(TAG, "onStop fired ..............");
              mGoogleApiClient.disconnect();
              Log.d(TAG, "isConnected ...............: " + mGoogleApiClient.isConnected());
          }
      
          private boolean isGooglePlayServicesAvailable() {
              int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
              if (ConnectionResult.SUCCESS == status) {
                  return true;
              } else {
                  GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
                  return false;
              }
          }
      
          @Override
          public void onConnected(Bundle bundle) {
              Log.d(TAG, "onConnected - isConnected ...............: " + mGoogleApiClient.isConnected());
              startLocationUpdates();
          }
      
          protected void startLocationUpdates() {
              PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
                      mGoogleApiClient, mLocationRequest, this);
              Log.d(TAG, "Location update started ..............: ");
          }
      
          @Override
          public void onConnectionSuspended(int i) {
      
          }
      
          @Override
          public void onConnectionFailed(ConnectionResult connectionResult) {
              Log.d(TAG, "Connection failed: " + connectionResult.toString());
          }
      
          @Override
          public void onLocationChanged(Location location) {
              Log.d(TAG, "Firing onLocationChanged..............................................");
              mCurrentLocation = location;
              mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
              updateUI();
          }
      
          private void updateUI() {
              Log.d(TAG, "UI update initiated .............");
              if (null != mCurrentLocation) {
                  String lat = String.valueOf(mCurrentLocation.getLatitude());
                  String lng = String.valueOf(mCurrentLocation.getLongitude());
                  tvLocation.setText("At Time: " + mLastUpdateTime + "\n" +
                          "Latitude: " + lat + "\n" +
                          "Longitude: " + lng + "\n" +
                          "Accuracy: " + mCurrentLocation.getAccuracy() + "\n" +
                          "Provider: " + mCurrentLocation.getProvider());
              } else {
                  Log.d(TAG, "location is null ...............");
              }
          }
      
          @Override
          protected void onPause() {
              super.onPause();
              stopLocationUpdates();
          }
      
          protected void stopLocationUpdates() {
              LocationServices.FusedLocationApi.removeLocationUpdates(
                      mGoogleApiClient, this);
              Log.d(TAG, "Location update stopped .......................");
          }
      
          @Override
          public void onResume() {
              super.onResume();
              if (mGoogleApiClient.isConnected()) {
                  startLocationUpdates();
                  Log.d(TAG, "Location update resumed .....................");
              }
          }
      }
      
      • LocationListener 通过 onLocationChanged 提供位置更改回调。

      • GoogleApiClient.ConnectionCallbacks 为 GoogleApiClient onConnected 提供回调。

      • GoogleApiClient.OnConnectionFailedListener 为 GoogleApiClient onConnectionFailed 提供回调。

      来源: http://javapapers.com/android/android-location-fused-provider/

      【讨论】:

      • 当我的按钮被点击时,我如何从我的 MainActivity 调用它来获取位置?
      • 仔细查看链接,您将了解如何使用它。它也被称为按钮单击它。只需在你的 mainActivity 中实现这些方法` public class MainActivity extends Activity implements LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener`
      • 如果我打算在多项活动中使用它,这仍然是最好的方法吗?
      • 是的,这是获取更多信息的最佳方式,请阅读 Google 开发者博客
      • 非常感谢您的帮助!我现在就试试这个! :)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-14
      • 2012-11-18
      • 2017-04-17
      • 2022-07-08
      • 1970-01-01
      相关资源
      最近更新 更多