How do I get the current GPS location programmatically in Android?

前端 未结 22 2714
梦谈多话
梦谈多话 2020-11-21 04:42

I need to get my current location using GPS programmatically. How can i achieve it?

22条回答
  •  自闭症患者
    2020-11-21 05:16

    Simple and easy way,

    Get location using https://github.com/sachinvarma/EasyLocation.

    Step 1: Just call

    new EasyLocationInit(MainActivity.this, timeInterval, fastestTimeInterval, runAsBackgroundService);
    

    timeInterval -> setInterval(long)(inMilliSeconds) means - set the interval in which you want to get locations.

    fastestTimeInterval -> setFastestInterval(long)(inMilliSeconds) means - if a location is available sooner you can get it. (i.e. another app is using the location services).

    runAsBackgroundService = True -> (Service will run in Background and updates Frequently(according to the timeInterval and fastestTimeInterval)) runAsBackgroundService = False -> (Service will getDestroyed after a successful location update )

    Step 2: Prepare EventBus subscribers: Declare and annotate your subscribing method, optionally specify a thread mode:

    eg:

         @Override
         public void onStart() {
             super.onStart();
             EventBus.getDefault().register(this);
         }
    
         @Override
         public void onStop() {
             super.onStop();
             EventBus.getDefault().unregister(this);
         }
    
      @SuppressLint("SetTextI18n")
      @Subscribe
      public void getEvent(final Event event) {
    
        if (event instanceof LocationEvent) {
          if (((LocationEvent) event).location != null) {
            ((TextView) findViewById(R.id.tvLocation)).setText("The Latitude is "
              + ((LocationEvent) event).location.getLatitude()
              + " and the Longitude is "
              + ((LocationEvent) event).location.getLongitude());
          }
        }
      }
    

    That's all.

    Hope it will help someone in future.

提交回复
热议问题