Android中GPS定位(獲取經(jīng)緯度)
AndroidGPS定位問題,眾所周知是一個蠻麻煩的問題.當(dāng)初我是新手,現(xiàn)在我也是新手,也搞了我頭大,網(wǎng)上搜索了很多的例子,一直處于僵持階段,而現(xiàn)在終于搞定了,因為我現(xiàn)在只需要獲取到經(jīng)緯度就可以了,反正獲取經(jīng)緯度可以從我這篇文章中看看;上代碼。
在AndroidManifest.xml中加入權(quán)限:
<uses-permission android:name="android.permission.ACCESSFINELOCATION"/>
<uses-permission android:name="android.permission.ACCESSCOARSELOCATION"/>
- package com.example.tt;
- import android.location.Location;
- import android.location.LocationListener;
- import android.location.LocationManager;
- import android.os.Bundle;
- import android.app.Activity;
- import android.content.Context;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.TextView;
- import android.widget.Toast;
- public class MainActivity extends Activity {
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- Button button=(Button)findViewById(R.id.button1);
- button.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View arg0) {
- // TODO Auto-generated method stub
- String serviceString=Context.LOCATION_SERVICE;
- LocationManager locationManager=(LocationManager)getSystemService(serviceString);
- String provider=LocationManager.GPS_PROVIDER;
- Location location=locationManager.getLastKnownLocation(provider);
- getLocationInfo(location);
- locationManager.requestLocationUpdates(provider, 2000, 0, locationListener);
- }
- });
- }
- private void getLocationInfo(Location location) {
- String latLongInfo;
- TextView lo=(TextView)findViewById(R.id.textView1);
- if(location!=null){
- double lat=location.getLatitude();
- double lng=location.getLongitude();
- latLongInfo="Lat:"+lat+"\nLong:"+lng;
- lo.setText(latLongInfo);
- }else {
- latLongInfo="No location found";
- lo.setText(latLongInfo);
- }
- }
- private final LocationListener locationListener =new LocationListener() {
- @Override
- public void onStatusChanged(String provider, int status, Bundle extras) {
- // TODO Auto-generated method stub
- }
- @Override
- public void onProviderEnabled(String provider) {
- getLocationInfo(null);
- }
- @Override
- public void onProviderDisabled(String provider) {
- getLocationInfo(null);
- }
- @Override
- public void onLocationChanged(Location location) {
- getLocationInfo(location);
- Toast.makeText(MainActivity.this, "位置改變了::::::::::::", 3000).show();
- }
- };
- }
當(dāng)需要使用基站定位時,可以將String provider=LocationManager.GPS_PROVIDER;改為**String provider=LocationManager.NETWORK_PROVIDER;
**
具體如果還要判斷GPS搜索不到時切換基站定位,那樣的功能就不要我寫了,新手都應(yīng)該會.
還有就是如果用到Google定位到哪個城市地點什么的,也easy了。
以上就是我個人對AndroidGPS定位的理解和實現(xiàn)方法。