Android通过GPS或NetWork获取当前位置信息

demo下载地址:https://download.csdn.net/download/sinat_35349353/10706484

刚完成一个需要通过GPS获取位置信息的项目(内网项目),所以根据LocationManager获取Providers会出现依旧能判断有网络连接,debug获取providers为[passive, gps, network, local_database]。

下面贴出解决代码:

package com.src;

import java.text.SimpleDateFormat;
import java.util.List;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

	private TextView lon, lat, altitude, speed, bearing, time;

	private LocationManager locationManager;
	private String locationProvider;

	private GpsStatus gpsStatus;
	private GpsStatus.Listener statusListener;

	String TAG = getClass().getSimpleName();

	private static final int NETWORK_NONE = -1;// 没有连接网络

	private static final int NETWORK_MOBILE = 0;// 移动网络

	private static final int NETWORK_WIFI = 1;// 无线网络

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		lon = (TextView) findViewById(R.id.lon);
		lat = (TextView) findViewById(R.id.lat);
		altitude = (TextView) findViewById(R.id.altitude);
		speed = (TextView) findViewById(R.id.speed);
		bearing = (TextView) findViewById(R.id.bearing);
		time = (TextView) findViewById(R.id.time);

		getLocation();

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

		removeLocationUpdatesListener();
	}

	// 方法一
	/*private void getLocation() {
		// 需要检查权限,否则编译报错,想抽取成方法都不行,还是会报错。只能这样重复 code 了。
		if (Build.VERSION.SDK_INT >= 23
				&& ActivityCompat.checkSelfPermission(this,
						android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
				&& ActivityCompat.checkSelfPermission(this,
						android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
			return;
		}
		if (ActivityCompat.checkSelfPermission(this,
				Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
				&& ActivityCompat.checkSelfPermission(this,
						Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
			return;
		}
		// 1.获取位置管理器
		locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
		// 2.获取位置提供器,GPS或是NetWork
		List providers = locationManager.getProviders(true);
		if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
			// 如果是网络定位
			Log.d(TAG, "如果是网络定位");
			locationProvider = LocationManager.NETWORK_PROVIDER;
		} else if (providers.contains(LocationManager.GPS_PROVIDER)) {
			// 如果是GPS定位
			Log.d(TAG, "如果是GPS定位");
			locationProvider = LocationManager.GPS_PROVIDER;
		} else {
			Log.d(TAG, "没有可用的位置提供器");
			return;
		}
		// 3.获取上次的位置,一般第一次运行,此值为null
		Location location = locationManager.getLastKnownLocation(locationProvider);
		if (location != null) {
			setLocation(location);
		}
		// 监视地理位置变化,第二个和第三个参数分别为更新的最短时间minTime和最短距离minDistace
		locationManager.requestLocationUpdates(locationProvider, 5000, 3, locationListener);
	}*/

	// 方法二
	private void getLocation() {
		// 需要检查权限,否则编译报错
		if (Build.VERSION.SDK_INT >= 23
				&& ActivityCompat.checkSelfPermission(this,
						android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
				&& ActivityCompat.checkSelfPermission(this,
						android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
			return;
		}
		if (ActivityCompat.checkSelfPermission(this,
				Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
				&& ActivityCompat.checkSelfPermission(this,
						Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
			return;
		}

		// 1.获取位置管理器
		locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
		// 2.获取网络状态
		if (getNetWorkState(this) == NETWORK_NONE) {
			Log.d(TAG, "当前是GPS定位");
			statusListener = new GpsStatus.Listener() {
				@Override
				public void onGpsStatusChanged(int event) {
					gpsStatus = locationManager.getGpsStatus(null);
					switch (event) {
					case GpsStatus.GPS_EVENT_STARTED:
						Log.d(TAG, "GPS系统已开始工作");
						break;
					case GpsStatus.GPS_EVENT_STOPPED:
						Log.d(TAG, "GPS系统已停止工作");
						break;
					default:
						break;
					}

				}
			};

			locationManager.addGpsStatusListener(statusListener);

			// 监视地理位置变化,第二个和第三个参数分别为更新的最短时间minTime(单位为毫秒)和最短距离minDistace(单位为米)
			locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 0, locationListener);

		} else {
			Log.d(TAG, "当前是网络定位");
			// 监视地理位置变化,第二个和第三个参数分别为更新的最短时间minTime(单位为毫秒)和最短距离minDistace(单位为米)
			locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 3000, 0, locationListener);
		}

	}

	private void setLocation(Location location) {

		lon.setText("经度:" + location.getLongitude());
		lat.setText("纬度:" + location.getLatitude());
		altitude.setText("海拔:" + location.getAltitude());
		speed.setText("速度:" + location.getSpeed());
		bearing.setText("航向:" + location.getBearing());
		time.setText("时间:" + formatUtc(location.getTime()));
	}

	// 移除定位监听
	public void removeLocationUpdatesListener() {
		// 需要检查权限,否则编译不过
		if (Build.VERSION.SDK_INT >= 23
				&& ActivityCompat.checkSelfPermission(this,
						android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
				&& ActivityCompat.checkSelfPermission(this,
						android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
			return;
		}
		if (locationManager != null) {
			locationManager.removeUpdates(locationListener);
		}
	}

	/**
	 * LocationListern监听器 参数:地理位置提供器、监听位置变化的时间间隔、位置变化的距离间隔、LocationListener监听器
	 */

	LocationListener locationListener = new LocationListener() {

		/**
		 * 当某个位置提供者的状态发生改变时
		 */
		@Override
		public void onStatusChanged(String provider, int status, Bundle arg2) {

		}

		/**
		 * 某个设备打开时
		 */
		@Override
		public void onProviderEnabled(String provider) {
			Toast.makeText(getApplicationContext(), "位置提供者已启用", Toast.LENGTH_LONG).show();
		}

		/**
		 * 某个设备关闭时
		 */
		@Override
		public void onProviderDisabled(String provider) {
			Toast.makeText(getApplicationContext(), "位置提供者已禁用", Toast.LENGTH_LONG).show();
		}

		/**
		 * 手机位置发生变动
		 */
		@Override
		public void onLocationChanged(Location location) {
			location.getAccuracy();// 精确度
			setLocation(location);
		}
	};

	@SuppressLint("SimpleDateFormat")
	private String formatUtc(long time) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return format.format(time);
	}

	/**
	 * @Title: getNetWorkState
	 * 
	 * @Description: 获取当前网络状态
	 * 
	 * @param context
	 * @return int
	 */
	private int getNetWorkState(Context context) {
		// 得到连接管理器对象
		ConnectivityManager connectivityManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);

		NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
		if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {

			if (activeNetworkInfo.getType() == (ConnectivityManager.TYPE_WIFI)) {
				return NETWORK_WIFI;
			} else if (activeNetworkInfo.getType() == (ConnectivityManager.TYPE_MOBILE)) {
				return NETWORK_MOBILE;
			}
		} else {
			return NETWORK_NONE;
		}
		return NETWORK_NONE;
	}
}

注意事项:

1. GPS获取位置信息需要在开阔地方才有GPS信号。

2.开启相对应的权限。

 
 

 
 
 

 
 

 
 

 

你可能感兴趣的:(Android)