Android gets current location information through GPS or NetWork

Posted by t_galan on Wed, 18 Dec 2019 17:25:47 +0100

demo download address: https://download.csdn.net/download/sinat_35349353/10706484

Just completed a project (intranet project) that needs to obtain location information through GPS, so it can still judge that there is a network connection when acquiring providers according to LocationManager. The provider obtained by debug is [passive, gps, network, local_database].

Here is the solution code:

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;// No network connection

	private static final int NETWORK_MOBILE = 0;// Mobile network

	private static final int NETWORK_WIFI = 1;// wireless network

	@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();
	}

	// Method 1
	/*private void getLocation() {
		// You need to check the permission, otherwise the compilation will report an error. If you want to extract the method, you will still report an error. This is the only way to repeat the 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.Get location manager
		locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
		// 2.Get location provider, GPS or NetWork
		List<String> providers = locationManager.getProviders(true);
		if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
			// If it's network location
			Log.d(TAG, "If it's network location ');
			locationProvider = LocationManager.NETWORK_PROVIDER;
		} else if (providers.contains(LocationManager.GPS_PROVIDER)) {
			// If GPS positioning
			Log.d(TAG, "If GPS positioning);
			locationProvider = LocationManager.GPS_PROVIDER;
		} else {
			Log.d(TAG, "No location provider available ');
			return;
		}
		// 3.Get the last location, usually run for the first time, this value is null
		Location location = locationManager.getLastKnownLocation(locationProvider);
		if (location != null) {
			setLocation(location);
		}
		// The second and third parameters are the updated minimum time minTime and minimum distance minDistace
		locationManager.requestLocationUpdates(locationProvider, 5000, 3, locationListener);
	}*/

	// Method two
	private void getLocation() {
		// You need to check the permission, otherwise the compilation reports an error
		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. Get location manager
		locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
		// 2. Get network status
		if (getNetWorkState(this) == NETWORK_NONE) {
			Log.d(TAG, "Currently GPS location");
			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 System started working");
						break;
					case GpsStatus.GPS_EVENT_STOPPED:
						Log.d(TAG, "GPS System stopped working");
						break;
					default:
						break;
					}

				}
			};

			locationManager.addGpsStatusListener(statusListener);

			// The second and third parameters are the updated minimum time (in milliseconds) and minimum distance (in meters), respectively
			locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 0, locationListener);

		} else {
			Log.d(TAG, "Current network location");
			// The second and third parameters are the updated minimum time (in milliseconds) and minimum distance (in meters), respectively
			locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 3000, 0, locationListener);
		}

	}

	private void setLocation(Location location) {

		lon.setText("Longitude:" + location.getLongitude());
		lat.setText("Latitude:" + location.getLatitude());
		altitude.setText("Altitude:" + location.getAltitude());
		speed.setText("Speed:" + location.getSpeed());
		bearing.setText("Heading:" + location.getBearing());
		time.setText("Time:" + formatUtc(location.getTime()));
	}

	// Remove location monitoring
	public void removeLocationUpdatesListener() {
		// Permission needs to be checked, otherwise compilation fails
		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 Listener parameters: geographic location provider, time interval of monitoring location change, distance interval of location change, LocationListener listener
	 */

	LocationListener locationListener = new LocationListener() {

		/**
		 * When the status of a location provider changes
		 */
		@Override
		public void onStatusChanged(String provider, int status, Bundle arg2) {

		}

		/**
		 * When a device is turned on
		 */
		@Override
		public void onProviderEnabled(String provider) {
			Toast.makeText(getApplicationContext(), "Location provider enabled", Toast.LENGTH_LONG).show();
		}

		/**
		 * When a device is turned off
		 */
		@Override
		public void onProviderDisabled(String provider) {
			Toast.makeText(getApplicationContext(), "Location provider disabled", Toast.LENGTH_LONG).show();
		}

		/**
		 * Mobile location changes
		 */
		@Override
		public void onLocationChanged(Location location) {
			location.getAccuracy();// accuracy
			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: Get current network status
	 * 
	 * @param context
	 * @return int
	 */
	private int getNetWorkState(Context context) {
		// Get connection manager object
		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;
	}
}

matters needing attention:

1. GPS needs to be in an open place to get position information.

2. Open the corresponding authority.

 <! -- allow programs to open network sockets -- >
 <uses-permission android:name="android.permission.INTERNET" />

 <! -- GPS positioning authority -- >
 <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

 <! -- allow program access to GSM network information -- >
 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

 <! -- get the status of current WiFi access and WLAN hotspot information -- >
 <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

 

Topics: Android network Java Mobile