我开发了一个Android应用程序,其中gps的任何时候都会打开。现在我如何找到用户的经纬度。请帮帮我
答案 0 :(得分:0)
要通过位置提供程序访问当前位置信息,我们需要使用android清单文件设置权限。
<manifest ... >
<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" />
</manifest>
当我们为Android应用使用网络位置提供商时,会使用ACCESS_COARSE_LOCATION。但是,ACCESS_FINE_LOCATION正在为两个提供商提供权限。必须使用INTERNET权限才能使用网络提供商。
创建LocationManager实例作为对位置服务的引用
对于任何后台Android服务,我们需要获得使用它的参考。同样,将使用getSystemService()方法创建位置服务引用。此引用将与新创建的LocationManager实例一起添加,如下所示。
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
从LocationManager请求当前位置
创建位置服务引用后,使用LocationManager的requestLocationUpdates()方法请求位置更新。对于此函数,我们需要发送位置提供程序的类型,秒数,距离以及要更新位置的LocationListener对象。
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
从LocationListener接收有关位置更改的位置更新
将根据指定的距离间隔或秒数通知LocationListener。
此示例使用GPS提供程序提供当前位置更新。整个Android应用程序代码如下,
public class MainActivity extends Activity implements LocationListener{
protected LocationManager locationManager;
protected LocationListener locationListener;
protected Context context;
TextView txtLat;
String lat;
String provider;
protected String latitude,longitude;
protected boolean gps_enabled,network_enabled;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtLat = (TextView) findViewById(R.id.textview1);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
@Override
public void onLocationChanged(Location location) {
txtLat = (TextView) findViewById(R.id.textview1);
txtLat.setText("Latitude:" + location.getLatitude() + ", Longitude:" + 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");
}
}
布局和Android清单的XML文件如下所示
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world" />
</RelativeLayout>