[android] get current location with Google play service

소스 참조 : http://developer.android.com/training/location/retrieve-current.html

 

  1. SDK manager에서 google play service 를 설치
  2. import sdk/extras/google/google_play_services/libproject/google-play-services_lib
  3. 새로운 프로젝트 생성
  4. 내가 만든 프로젝트의 library로 연결

 

public class MainActivity extends Activity
{
   private TextView _text;
   private LocationClient mLocationClient;

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

      _text = (TextView) findViewById(R.id.textView1);

      Button btn1 = (Button) findViewById(R.id.button1);
      btn1.setOnClickListener(new View.OnClickListener()
      {
         @Override
         public void onClick(View v)
         {
            getLocation();
         }
      });

      mLocationClient = new LocationClient(this, connectionCallbacks, connectionFailedListener);
      mLocationClient.connect();
   }

   @Override
   protected void onStop()
   {
      super.onStop();

      mLocationClient.disconnect();
   }

   private void getLocation()
   {
      if (servicesConnected())
      {
         Location currentLocation = mLocationClient.getLastLocation();
         _text.setText(currentLocation.getLatitude() + "," + currentLocation.getLongitude());
      }
   }

   private boolean servicesConnected()
   {
      int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);

      if (ConnectionResult.SUCCESS == resultCode)
      {
         return true;
      }
      else
      {
         Log.w("MainActivity.java | servicesConnected", "|" + "error" + "|");
         return false;
      }
   }

   private ConnectionCallbacks connectionCallbacks = new ConnectionCallbacks()
   {
      @Override
      public void onDisconnected(){}
      @Override
      public void onConnected(Bundle connectionHint){}
   };

   private OnConnectionFailedListener connectionFailedListener = new OnConnectionFailedListener()
   {
      @Override
      public void onConnectionFailed(ConnectionResult result){}
   };
}

 

 

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

 

 

 

TestCurrentLocation