使用GPS定位

在开发与地理位置相关时,经常需要用到经纬度,因为这个的位置比较精确。然后可以转换成我们需要的数据。

直接列出开发实现步骤:

1、业务层实现,通过这个代码可以获得经纬度:

package org.Base.Utils;


import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;


/**
 * @author coldwait
 * @version
 */
public class CoordinateHelper {
	public CoordinateHelper(Context context, TextView longitude,
			TextView latitude) {
		this.context = context;
		this.latitude = latitude;
		this.longitude = longitude;


		setLocationParam();
	}


	double lat;
	double lng;
	private LocationManager locationManager;
	private Context context;
	private TextView longitude;
	private TextView latitude;


	public String getLatitude() {
		return String.valueOf(lat);
	}


	public String getLongitude() {
		return String.valueOf(lng);
	}


	private void setLocationParam() {
		try {
			String serviceName = Context.LOCATION_SERVICE;
			locationManager = (LocationManager) context
					.getSystemService(serviceName);


			/*
			 * locationManager =
			 * (LocationManager)getSystemService(LOCATION_SERVICE);
			 * 
			 * String provider=LocationManager.GPS_PROVIDER; Location location =
			 * locationManager.getLastKnownLocation(provider);
			 */


			Criteria criteria = new Criteria();
			criteria.setAccuracy(Criteria.ACCURACY_FINE);
			criteria.setAltitudeRequired(false);
			criteria.setBearingRequired(false);
			criteria.setCostAllowed(true);
			criteria.setPowerRequirement(Criteria.POWER_LOW);


			String provider = locationManager.getBestProvider(criteria, true);
			Location location = locationManager.getLastKnownLocation(provider);
			updateWithNewLocation(location);
			// 设置监听器,自动更新的最小时间为间隔1秒,最小位移变化超过5米
			locationManager.requestLocationUpdates(provider, 1000, 5,
					locationListener);
		} catch (Exception e) {
			Log.e("Exception", e.getMessage());
		}


	}


	private final LocationListener locationListener = new LocationListener() {


		public void onLocationChanged(Location location) {
			updateWithNewLocation(location);
		}


		public void onProviderDisabled(String provider) {
			updateWithNewLocation(null);
		}


		public void onProviderEnabled(String provider) {
		}


		public void onStatusChanged(String provider, int status, Bundle extras) {
		}


	};


	private void updateWithNewLocation(Location location) {
		if (location != null) {
			lat = location.getLatitude();
			lng = location.getLongitude();
		} else {
			lat = 0;
			lng = 0;
		}
		latitude.setText(getLatitude());
		longitude.setText(getLongitude());
	}
}
2、设置布局文件main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:id="@+id/carregion" android:layout_width="fill_parent"
	android:layout_height="fill_parent">
	
		<LinearLayout android:orientation="vertical"
			android:layout_alignParentTop="true" android:layout_above="@+id/menu"
			android:layout_width="fill_parent" android:layout_height="wrap_content"
			android:padding="10dip">
			<TableLayout android:layout_width="fill_parent"
				android:layout_height="wrap_content" android:paddingLeft="10dip"
				android:paddingRight="10dip" android:stretchColumns="0,1"
				android:shrinkColumns="1">
			
				
				
				
				<TableRow android:paddingTop="10dip" android:paddingBottom="10dip">
					<TextView android:text="经度:" android:textSize="19sp" />
					<TextView android:id="@+id/longitude" android:text=""
						android:textSize="18sp" />
				</TableRow>
				
				<TableRow android:paddingTop="10dip" android:paddingBottom="10dip">
						<TextView android:text="纬度:" android:textSize="19sp" />
						<TextView android:id="@+id/latitude" android:text=""
							android:textSize="18sp" />
				</TableRow>
				<TableRow android:paddingTop="10dip" android:paddingBottom="10dip">
					
					<TextView android:id="@+id/pickupdata" android:text="是否采集到坐标:"
						android:textSize="18sp" />
					<TextView android:id="@+id/ispicked" android:text="否"
						android:textSize="18sp" />
				</TableRow>
			</TableLayout>
			</LinearLayout>
</RelativeLayout>
3、开发Activity文件
public class QuestionReport extends Activity{
        private TextView longitude;//设置显示经度文本框
	private TextView latitude;//设置显示纬度文本框
	private TextView isPicked;//设置是否捕获到经纬度
      public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.question_reported);
		location();//通过调用此成员方法,设置经纬度
		
	}
	private void location() {
		new CoordinateHelper(this, longitude, latitude);
		/**
		 * Set a special listener to be called when an action is performed on the text view. 
		 * This will be called when the enter key is pressed, or when an action supplied to the IME is selected by the user. 
		 * Setting this means that the normal hard key event will not insert a newline into the text view, even if it is multi-line; 
		 * holding down the ALT modifier will, however, allow the user to insert a newline character. 
		 * 
		 * */
		latitude.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
				// TODO Auto-generated method stub
				return false;
			}

		});
		/**
		 * Adds a TextWatcher to the list of those whose methods are called 
		 * whenever this TextView's text changes
		 */
		latitude.addTextChangedListener(new TextWatcher() {
			@Override
			public void afterTextChanged(Editable arg0) {
				// TODO Auto-generated method stub

			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
				// TODO Auto-generated method stub

			}
			/**
			 * This method is called to notify you that, within s, 
			 * the count characters beginning at start have just replaced old text that had length before. 
			 * It is an error to attempt to make changes to s from this callback.
			 */

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				// TODO Auto-generated method stub
				if ("0.0".equals(longitude.getText().toString())
						|| "".equals(longitude.getText().toString())) {//如果获取不到纬度或者得到经度为0,则显示是否获得经纬度为否
					isPicked.setText("否");
				} else {
					isPicked.setText("是");
				}
			}

		});
		longitude.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
				// TODO Auto-generated method stub
				return false;
			}

		});
		longitude.addTextChangedListener(new TextWatcher() {

			@Override
			public void afterTextChanged(Editable arg0) {
				// TODO Auto-generated method stub

			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				// TODO Auto-generated method stub
				if ("0.0".equals(longitude.getText().toString())
						|| "".equals(longitude.getText().toString())) {如果获取不到经度或者得到经度为0,则显示是否获得经纬度为否
					isPicked.setText("否");
				} else {
					isPicked.setText("是");
				}
			}

		});
	}

}
4、为应用程序声明获取位置信息的权限
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />









  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值