Android获取位置信息 - GPS定位 Network定位

时间:2022-09-03 23:52:50
1. 用GPS或者Network获取位置信息
src/com/wind/whereami/LocationSend.java
package com.wind.whereami;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class LocationSend extends Activity implements OnClickListener {

	protected static final String TAG = "LocationSend";
	private Button mSendLocationButton;
	private Button mGetLocationButton;
	private TextView mLocationInfo;
	private LocationManager mLocationManager;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_location_send);
		mSendLocationButton = (Button) this.findViewById(R.id.send_location);
		mGetLocationButton = (Button) this.findViewById(R.id.get_location);
		mLocationInfo = (TextView) this.findViewById(R.id.location_info);
		mSendLocationButton.setOnClickListener(this);
		mGetLocationButton.setOnClickListener(this);

		mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.location_send, menu);
		return true;
	}

	@Override
	public void onClick(View v) {
		if (v == mSendLocationButton) {
			/*
			  * 发起地址信息短串请求,一个位置的地理信息一可以通过GeoCode/反GeoCode搜索获得.
			  * mSearch 为 MKSearch象,
			  * 参数pt为要分享的位置的经纬度坐标 ,name和addr为百度地图客户端在展示该位置时显示的名称和地址.
			  */
			//GeoPoint pt = new GeoPoint((int)(39.945*1E6),(int)(116.404*1E6));


		} else if (v == mGetLocationButton) {
			//方法1:指定GPS或者Network来获取位置
			/*checkGPSSettings();
			Location location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
			mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 1, locationListener);*/
			checkNetworkSettings();
			Location location = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
			mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 2000, 1, locationListener);
			
			getLocationInfo(location);
			
			//方法2:获取高精度的位置
			//getLocation();	
		}
	}

	private Location getLocation()
	{
		//查找服务信息
		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 = mLocationManager.getBestProvider(criteria, true); //获取Provider信息,为gps或network
		Log.v(TAG, "provider = " + provider);
		Location location = mLocationManager.getLastKnownLocation(provider);
		
		mLocationManager.requestLocationUpdates(provider, 1000, 0, locationListener);
		return location;
	}
	
	private void checkGPSSettings() {
		if (mLocationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
			Toast.makeText(this, "GPS模块正常", Toast.LENGTH_SHORT).show();
			return;
		}

		Toast.makeText(this, "请开启GPS!", Toast.LENGTH_SHORT).show();
		Intent intent = new Intent(Settings.ACTION_LOCALE_SETTINGS);
		startActivityForResult(intent, 0); // 此为设置完成后返回到获取界面

	}

	private void checkNetworkSettings() {
		if (mLocationManager.isProviderEnabled(android.location.LocationManager.NETWORK_PROVIDER)) {
			Toast.makeText(this, "NETWORK_PROVIDER模块正常", Toast.LENGTH_SHORT).show();
			return;
		}

		Toast.makeText(this, "请开启NETWORK_PROVIDER!", Toast.LENGTH_SHORT).show();
		Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
		startActivityForResult(intent, 0); // 此为设置完成后返回到获取界面

	}
	
	private void getLocationInfo(Location location) {
		String latLongInfo;
		if (location != null) {
			double lat = location.getLatitude();
			double lng = location.getLongitude();
			latLongInfo = "Lat:" + lat + "nLong:" + lng;
			
			mLocationInfo.setText(latLongInfo);
		} else {
			latLongInfo = "No location found";
			mLocationInfo.setText(latLongInfo);
		}
	}

	private final LocationListener locationListener = new LocationListener() {
		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub
			Log.v(TAG, "onStatusChanged");
		}

		@Override
		public void onProviderEnabled(String provider) {
			getLocationInfo(null);
			Log.v(TAG, "onProviderEnabled");
		}

		@Override
		public void onProviderDisabled(String provider) {
			getLocationInfo(null);
			Log.v(TAG, "onProviderDisabled");
		}

		@Override
		public void onLocationChanged(Location location) {
			getLocationInfo(location);
			Toast.makeText(LocationSend.this, "onLocationChanged", 3000).show();
		}
	};
}




2. 记得添加权限
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.wind.whereami"
    android:versionCode="1"
    android:versionName="1.0" >
	<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" />
	         
    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.wind.whereami.LocationSend"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

3. 使用的layout文件
/res/layout/activity_location_send.xml
<LinearLayout 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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".LocationSend" 
    android:orientation="vertical">
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
    <Button
        android:id="@+id/send_location"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textView1"
        android:text="@string/send_location" />

    <Button
        android:id="@+id/get_location"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/textView1"
        android:layout_below="@+id/button1"
        android:text="@string/get_location" />

    <TextView
        android:id="@+id/location_info"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button2"
        android:layout_below="@+id/button2"
        android:layout_marginTop="19dp"
        android:text="@string/location_info" />
</LinearLayout>
补充一点,很多人会说,GPS无法定位,Location location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
location一直为空。我解释一下:去调用这个函数,多大数返回都是空的,因为GPS没有那么强,一下就获取到位置了。所以会注册一个listener来监听位置的改变
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 1, locationListener);
有人还说会拿不到数据,那么你首先确定你的GPS是好用的(我就犯过错误是用网络定过之后百度地图上留下了我最近的位置,关掉网络,还是能定位,貌似是GPS定的,实际上我的GPS根本不能用,只好的测试方法就是到户外,看看GPS会不会跟着你走,顺便测试下你写的程序)