<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"/>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="net.bwie.locationandsessior.MainActivity"> <Button android:id="@+id/location_btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="定位"/> <TextView android:id="@+id/result_tv" android:text="结果" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </LinearLayout>
public class MainActivity extends AppCompatActivity implements View.OnClickListener, LocationListener { protected Button mLocationBtn; protected TextView mResultTv; private LocationManager mLocationManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); super.setContentView(R.layout.activity_main); initView(); } private void initView() { mLocationBtn = (Button) findViewById(R.id.location_btn); mLocationBtn.setOnClickListener(MainActivity.this); mResultTv = (TextView) findViewById(R.id.result_tv); } @Override public void onClick(View view) { if (view.getId() == R.id.location_btn) { locate(); } } // 定位 private void locate() { // 定位管理者 mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); // NETWORK_PROVIDER:使用网络定位(粗略定位) // GPS_PROVIDER:使用GPS定位(精准定位) mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 200, 200, this); } // 获取当前设备的经纬度 @Override public void onLocationChanged(Location location) { double latitude = location.getLatitude();// 纬度 double longitude = location.getLongitude();// 经度 mResultTv.setText("纬度:" + latitude + ",经度:" + longitude); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } }