问题描述
Android FusedLocationProvider客户端不支持APN SIM(这意味着私有互联网,并非所有人都可以访问)它可以使用Wifi或普通互联网(这意味着全球移动互联网),我也尝试了位置管理器(Play服务不支持这些设备)。
活动课
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
//import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.PowerManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationAvailability;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnCanceledListener;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.SuccessContinuation;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import java.util.Locale;
public class LocationActivity extends AppCompatActivity implements LocationListener {
private FusedLocationProviderClient mFusedLocationClient;
private double wayLatitude = 0.0, wayLongitude = 0.0;
private LocationRequest locationRequest;
private LocationCallback locationCallback;
private Button btnLocation;
private TextView txtLocation;
private Button btnContinueLocation;
private TextView txtContinueLocation;
private StringBuilder stringBuilder;
private boolean isContinue = false;
private int LOCATION_REQUEST = 1000;
GPSTracker gps;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location);
this.txtContinueLocation = (TextView) findViewById(R.id.txtContinueLocation);
this.btnContinueLocation = (Button) findViewById(R.id.btnContinueLocation);
this.txtLocation = (TextView) findViewById(R.id.txtLocation);
this.btnLocation = (Button) findViewById(R.id.btnLocation);
try {
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(10 * 1000); // 10 seconds
locationRequest.setFastestInterval(5 * 1000); // 5 seconds
locationCallback = new LocationCallback() {
@Override
public void onLocationAvailability(LocationAvailability locationAvailability) {
super.onLocationAvailability(locationAvailability);
try {
if (!locationAvailability.isLocationAvailable()) {
GoogleApiAvailability api = GoogleApiAvailability.getInstance();
Task<Void> task = api.makeGooglePlayServicesAvailable(LocationActivity.this);
task.addOnCompleteListener(LocationActivity.this, new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
// getLocation();
// mFusedLocationClient.removeLocationUpdates(this);
gps = new GPSTracker(LocationActivity.this);
// Check if GPS enabled
if (gps.canGetLocation()) {
wayLatitude = gps.getLatitude();
wayLongitude = gps.getLongitude();
//
is for new line
Toast.makeText(getApplicationContext(), "Your Location is -
Lat: " + wayLatitude + "
Long: " + wayLongitude, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "No location", Toast.LENGTH_LONG).show();
}
}
});
task.addOnFailureListener(LocationActivity.this, new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(LocationActivity.this, "Playservice failure", Toast.LENGTH_LONG).show();
}
});
}
//init();
// }
} catch (SecurityException e) {
}
}
@Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult == null) {
return;
}
for (Location location : locationResult.getLocations()) {
if (location != null) {
wayLatitude = location.getLatitude();
wayLongitude = location.getLongitude();
// if (!isContinue) {
// txtLocation.setText(String.format(Locale.US, "%s - %s", wayLatitude, wayLongitude));
// } else {
// stringBuilder.append(wayLatitude);
// stringBuilder.append("-");
// stringBuilder.append(wayLongitude);
// stringBuilder.append("
");
// txtContinueLocation.setText(stringBuilder.toString());
Toast.makeText(LocationActivity.this, wayLatitude + " _ " + wayLongitude, Toast.LENGTH_LONG).show();
// }
// if (mFusedLocationClient != null) {
// mFusedLocationClient.removeLocationUpdates(locationCallback);
// }
}
}
}
};
btnLocation.setOnClickListener(v -> {
// checkGooglePlayServices();
getLocation();
});
btnContinueLocation.setOnClickListener(v -> {
// checkGooglePlayServices();
// PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
// boolean isPowerSaveMode = pm.isPowerSaveMode();
// Log.e("TAG", "Mode " + isPowerSaveMode);
//
// init();
getLocation();
// _getLocation();
});
// getLocation();
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
} catch (Exception e) {
Log.e("TAG", e.getMessage());
}
}
private void getLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
LOCATION_REQUEST);
} else {
getLatLang();
// init();
}
}
public void getLatLang() {
try {
mFusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null);
mFusedLocationClient.getLastLocation().addOnSuccessListener(this, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if (location != null) {
wayLatitude = location.getLatitude();
wayLongitude = location.getLongitude();
Toast.makeText(LocationActivity.this, wayLatitude + " _ " + wayLongitude, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(LocationActivity.this, "Location not get Fused client", Toast.LENGTH_LONG).show();
}
}
});
mFusedLocationClient.getLastLocation().addOnFailureListener(this, new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
wayLatitude = 0.0;
wayLongitude = 0.0;
Toast.makeText(LocationActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
});
mFusedLocationClient.getLastLocation().addOnCanceledListener(this, new OnCanceledListener() {
@Override
public void onCanceled() {
Log.e("TAG", "loc cancel");
}
});
} catch (Exception e) {
Log.e("TAG", "loc exce" + e.getMessage());
}
}
@SuppressLint("MissingPermission")
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case 1000: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getLatLang();
// init();
} else {
Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
}
break;
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
}
}
@Override
protected void onDestroy() {
super.onDestroy();
// mFusedLocationClient.removeLocationUpdates(locationCallback);
// if(locMgr!=null)
// locMgr.removeUpdates();
}
@Override
public void onLocationChanged(Location location) {
if (location != null) {
wayLatitude = location.getLatitude();
wayLongitude = location.getLongitude();
Toast.makeText(LocationActivity.this, wayLatitude + " _ " + wayLongitude + " CHANGE", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(LocationActivity.this, "Location not get Fused client chnage locATION", Toast.LENGTH_LONG).show();
}
}
}
帮助者-如果位置无法获取,则我们尝试所有三个提供者。如果任何提供者提供结果,则我们跳过其他提供者。
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
boolean isPassive = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
@SuppressLint("MissingPermission")
public Location getLocation() {
try {
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
isPassive = locationManager
.isProviderEnabled(LocationManager.PASSIVE_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled && !isPassive) {
// no network provider is enabled
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isPassive) {
// if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.PASSIVE_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Toast.makeText(mContext, "Location Try Passive Provider", Toast.LENGTH_SHORT);
Log.e("Passive Enabled", "Passive Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
} else {
Toast.makeText(mContext, "Location Not get Passive Provider", Toast.LENGTH_SHORT);
}
}
}
// }.
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Toast.makeText(mContext, "Location Try GPS Provider", Toast.LENGTH_SHORT);
Log.e("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
Log.e("TAG", "GPS " + latitude + " vjhg " + longitude);
} else {
Toast.makeText(mContext, "Location Not get GPS Provider", Toast.LENGTH_SHORT);
}
}
}
}
if (isNetworkEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.e("Network", "Network Enabled");
Toast.makeText(mContext, "Location Try Network Provider", Toast.LENGTH_SHORT);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
} else {
Toast.makeText(mContext, "Location Not get Network Provider", Toast.LENGTH_SHORT);
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
*/
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
*/
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
*/
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
*
* @return boolean
*/
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
*/
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
@Override
public void onLocationChanged(Location location) {
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
Log.e("TAG", "Change " + latitude + " ``` " + longitude);
}
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
}
货单
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<!-- <uses-permission android:name="android.permission.ACCESS_" />-->
<uses-feature
android:name="android.hardware.location.gps"
android:required="false" />
<uses-feature
android:name="android.hardware.location.network"
android:required="false" />
<application
android:allowBackup="false"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:largeHeap="true"
android:roundIcon="@mipmap/ic_launcher_round"
android:screenOrientation="portrait"
android:supportsRtl="true">
这是我的样例代码。一旦我连接了我的wifi,它就可以工作了,但我的观点是,我们想要使用APN sim。
推荐答案
答案: 谷歌位置服务使用谷歌的混合位置数据来更快地定位设备的位置。
来自:Do network location provider need internet to determine location?和Google IO 2019视频:Seamless and Smooth Location Everywhere with the new FusedLocationProvider,其中提供了有关FusedLocationProvider的详细信息。
GPS仍然有效,只是定位速度更慢,而且在户外效果最好。AGPS (Assisted GPS)需要移动连接以帮助GPS定位。如果你想要在室内或城市环境中定位,你将需要一个使用Hybrid Positioning的外部服务,该服务使用Wi-Fi、蓝牙,可能还使用手机发射塔?但由于位置数据库不断更新(即WiFi热点发生变化,新的建设可能会改变无线电模式),因此至少需要一些与外部服务的频繁连接,因此这与在专用网络上访问Google服务存在相同的问题。
我需要将[Google Services]列入白名单的Google URL是什么?
发件人:FCM ports and your firewall:
对于出站连接,FCM不提供具体的IP,因为我们的网段变化太频繁,您的防火墙规则可能会过时,影响您的用户体验。理想情况下,您应该将没有IP限制的端口5228-5230列入白名单。但是,如果您必须有IP限制,则应将Google's ASN of 15169中列出的IPv4和IPv6块中的所有IP地址列入白名单。这是一个很大的清单,你应该计划每月更新你的规则。防火墙IP限制导致的问题通常是间歇性的,很难诊断。
要为传入消息打开的端口:
5228
5229
5230
允许传出连接的端口:
其中之一(首选选项1):
- 无IP限制
- Google's ASN of 15169中列出的IP块中包含的所有IP地址。不要忘记至少每月更新一次。
虽然Google服务不是Firebase Cloud消息传递,但它基于相同的不断变化的全球基础设施,因此在没有具体文档说明的情况下是合理的匹配。
另外,鉴于Google Maps不是Google Location Services,请参阅此问题中的Google Maps相关资源:Using google maps api behind firewall
替代方案
另一种选择是不为您的混合位置提供商使用Google服务。有像HERE这样的第三方供应商似乎有自己的高级Advanced Positioning by HERE服务。您必须检查plan would be appropriate for your usage内容,并与他们联系,了解如果What IP-addresses do I need to allow the firewall to access geocoder.api.here.com?
未涵盖哪些IP地址/域需要被列入白名单可能还有像Skyhook这样的其他提供商可以进行调查,以确定它们是否符合您的需求。我会看看APN SIM提供商是否有服务。或者,如果所有设备都是由一家制造商提供的,请查看该制造商是否有专有(非谷歌)的定位服务。
无法执行上述任何操作
如果企业不允许上述选项,则应用程序仅限于在GPS可用时修复GPS的速度较慢的应用程序。GPS是免费的,但要想更快地定位或改善城市/室内位置,需要一些第三方服务来告诉设备它在哪里。
这篇关于Android融合位置提供商客户端不使用APN模拟其使用Wifi或普通互联网或离线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!