ANDROID_MARS学习笔记_S03_003_LocationManager、LocationListener
一、简介
二、代码
1.xml
(1)AndroidManifest.xml
增加
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> </manifest>
2.java
(1)MainActivity.java
1 package com.location1; 2 3 import android.app.Activity; 4 import android.content.Context; 5 import android.location.Location; 6 import android.location.LocationListener; 7 import android.location.LocationManager; 8 import android.os.Bundle; 9 import android.view.View; 10 import android.view.View.OnClickListener; 11 import android.widget.Button; 12 13 public class MainActivity extends Activity { 14 15 private Button button = null; 16 private LocationManager locationManager = null; 17 LocationListener locationListener = null; 18 @Override 19 protected void onCreate(Bundle savedInstanceState) { 20 super.onCreate(savedInstanceState); 21 setContentView(R.layout.activity_main); 22 23 24 button = (Button)findViewById(R.id.buttonId); 25 locationManager = (LocationManager) MainActivity.this.getSystemService(Context.LOCATION_SERVICE); 26 27 locationListener = new LocationListener() { 28 @Override 29 public void onStatusChanged(String provider, int status, Bundle extras) { 30 System.out.println("onStatusChanged--->"); 31 } 32 33 @Override 34 public void onProviderEnabled(String provider) { 35 System.out.println("onProviderEnabled--->"); 36 } 37 38 @Override 39 public void onProviderDisabled(String provider) { 40 System.out.println("onProviderDisabled--->"); 41 } 42 43 @Override 44 public void onLocationChanged(Location location) { 45 System.out.println("onLocationChanged--->"); 46 System.out.println(location.getLatitude()); 47 System.out.println(location.getLongitude()); 48 } 49 }; 50 51 button.setOnClickListener(new OnClickListener() { 52 @Override 53 public void onClick(View v) { 54 //绑定监听器,第二个参数表示更新的最小时间(毫秒);第三个参数表示更新的最小距离(米) 55 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener); 56 } 57 }); 58 } 59 }
You can do anything you set your mind to, man!