Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/370.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 所有my FusedLocation请求的列表_Java_Google Play Services_Fusedlocationproviderapi_Android Fusedlocation_Google Location Services - Fatal编程技术网

Java 所有my FusedLocation请求的列表

Java 所有my FusedLocation请求的列表,java,google-play-services,fusedlocationproviderapi,android-fusedlocation,google-location-services,Java,Google Play Services,Fusedlocationproviderapi,Android Fusedlocation,Google Location Services,我正在使用下面的代码在一个活动中注册位置更新,但如何检查我的应用程序是否已注册此请求(或查询我的活动位置请求),并且仍在等待位置响应,以便我不会重复请求?我可以关闭我的应用程序并再次运行,而无需停止此请求: this.locationRequest = new LocationRequest(); this.locationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS); this.locationRequest.setFastestIn

我正在使用下面的代码在一个活动中注册位置更新,但如何检查我的应用程序是否已注册此请求(或查询我的活动位置请求),并且仍在等待位置响应,以便我不会重复请求?我可以关闭我的应用程序并再次运行,而无需停止此请求:

this.locationRequest = new LocationRequest();
this.locationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
this.locationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
this.locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(this.locationRequest);
this.locationSettingsRequest = builder.build();

this.locationCallback = new LocationCallback() {
    @Override
    public void onLocationResult(LocationResult locationResult) {
        super.onLocationResult(locationResult); // why? this. is. crazy. Android.
        Location currentLocation = locationResult.getLastLocation();

        GPSPoint gpsPoint = new GPSPoint(currentLocation.getLatitude(),
                                         currentLocation.getLongitude());
        Log.i(TAG, "Location Callback results: " + gpsPoint);
        if (null != workable)
            workable.work(gpsPoint);
    }
};

this.mFusedLocationClient =
        LocationServices.getFusedLocationProviderClient(MainApplication.getAppContext());
this.mFusedLocationClient.requestLocationUpdates(this.locationRequest,
                this.locationCallback, Looper.myLooper());
公共类BackgroundLocationService扩展服务实现
GoogleAppClient.ConnectionCallbacks,
GoogleAppClient.OnConnectionFailedListener,
GpsStatus.Listener,
位置侦听器{
//这里的常数。。。。
私人GoogleapClient MGoogleapClient;
私人位置请求mLocationRequest;
私人场所经理场所经理;
//指示请求是否正在进行的标志。
私人发展;
私人通知管理我的通知经理;
私有布尔值servicesAvailable=false;
//这里还有其他变量。。。
@凌驾
public void onCreate()
{
super.onCreate();
myNotificationManager=新建NotificationManagement(getApplicationContext());
myNotificationManager.displayMainNotification();
mInProgress=false;
//创建LocationRequest对象
mLocationRequest=LocationRequest.create();
//使用高精度
mLocationRequest.setPriority(位置请求.优先级高精度);
//设置更新间隔
mLocationRequest.setInterval(首选的_间隔);
//设置最快的更新间隔
mLocationRequest.SetFastTestInterval(最快间隔);
servicesAvailable=servicesConnected();
locationManager=(locationManager)getSystemService(Context.LOCATION\u服务);
locationManager.addGpsStatusListener(此);
setupLocationClientIfNeed();
}
/**
*使用封闭类创建新的location客户端
*处理回调。
*/
受保护的同步无效BuildGoogleAppClient()
{
this.mgoogleapclient=新的Googleapclient.Builder(this)
.addConnectionCallbacks(此)
.addOnConnectionFailedListener(此)
.addApi(LocationServices.API)
.build();
}
私有布尔服务连接()
{
//检查Google Play服务是否可用
int-resultCode=GooglePlayServicesUtil.isgoogleplayservicesavaailable(this);
//如果Google Play服务可用
if(ConnectionResult.SUCCESS==resultCode)
{
返回true;
}
其他的
{
返回false;
}
}
公共int onStartCommand(Intent Intent、int标志、int startId)
{
super.onStartCommand(intent、flags、startId);
如果(!servicesAvailable | | mGoogleApiClient.isConnected()| | mInProgress)
返回开始时间;
setupLocationClientIfNeed();
如果(!mGoogleApiClient.isConnected()| |!mGoogleApiClient.isConnecting()&&!mInProgress)
{
mInProgress=true;
mGoogleApiClient.connect();
}
返回开始时间;
}
私有void setupLocationClientIfNeed()
{
if(mGoogleApiClient==null)
buildGoogleAppClient();
}
公共无效onGpsStatusChanged(内部事件)
{
}
//定义接收位置更新的回调方法
@凌驾
已更改位置上的公共无效(位置)
{
simpleGPSFilter(位置);
}
//这里还有其他需要的东西。。。
/**
*“愚蠢”过滤器,利用经验数据过滤掉位置噪声。
*@param location包含所有所需信息的对象
*/
私有void simpleGPSFilter(位置)
{
//加载所有必需的变量
int信号功率=0;
卫星=0;
//获取卫星
mGpsStatus=locationManager.getGpsStatus(mGpsStatus);
Iterable sats=mGpsStatus.getSatellites();
如果(sats!=null)
{
用于(GpsSatellite卫星:sats)
{
如果(sat.usedInFix())
{
卫星++;
信号功率+=卫星获取信噪比();
}
}
}
如果(卫星!=0)
信号功率=信号功率/卫星;
mySpeed=(location.getSpeed()*3600)/1000;
myAccuracy=location.getAccurance();
myBearing=location.getBearing();
纬度=位置。getLatitude();
longitude=location.getLongitude();
Log.i(“周期开始”、“周期开始”);
Log.i(“Sat强度”,整数.toString(信号功率));
Log.i(“锁定卫星”,Integer.toString(卫星));
//计算一下坐标距离
/*
*给定纬度的地球半径。
*公式:半径=sqrt(((赤道角^2*cos(纬度))^2+(北极角^2*sin(纬度))^2)/((赤道角*cos(纬度))^2+(北极角*sin(纬度))^2)
*重要提示:Math lib对三角方程使用弧度,因此不要忘记使用toRadians()
*/
Log.i(“纬度表示半径”,双倍于弦(纬度));
双地球半径=数学sqrt((数学pow((地球半径赤道*地球半径赤道*数学cos)2)
+Math.pow((地球半径极点*地球半径极点*数学cos(数学toRadians(纬度))),2))
/(数学pow((地球半径赤道*数学cos(数学toRadians(纬度))),2)
+数学功率((地球半径极点*Math.cos(数学托拉面(纬度)),2));
Log.i(“地球半径”,Double.toString(地球半径));
/*
*使用哈弗公式(反正切书写)和以下算法计算地图上两点之间的距离
*纬度差=纬度-最后的纬度;
*lngDifference=经度-上次经度;
*a=(sin(纬度差/2))^2+cos(最后纬度)*cos(纬度)*(sin(纬度差/2))^2
*c=2*atan2(sqrt(a),sqrt(1-a))
*距离=接地半径*c
*/
双纬度差=纬度-最后一个纬度;
双lngDifference=经度-上次经度;
double a=Math.pow((Math.sin(Math.toRadians(latDifference/2))),2)+(Math.cos(Math.toRadians(lastLastLatitude))
*数学常数(数学常数(纬度))
*数学。pow(数学。sin(数学。toRadians(l
public class BackgroundLocationService extends Service implements
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener,
    GpsStatus.Listener,
    LocationListener {

// Constants here....

private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private LocationManager locationManager;
// Flag that indicates if a request is underway.
private boolean mInProgress;

private NotificationManagement myNotificationManager;
private Boolean servicesAvailable = false;

//And other variables here...

@Override
public void onCreate()
{
    super.onCreate();

    myNotificationManager = new NotificationManagement(getApplicationContext());
    myNotificationManager.displayMainNotification();

    mInProgress = false;
    // Create the LocationRequest object
    mLocationRequest = LocationRequest.create();
    // Use high accuracy
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    // Set the update interval
    mLocationRequest.setInterval(PREFERRED_INTERVAL);
    // Set the fastest update interval
    mLocationRequest.setFastestInterval(FASTEST_INTERVAL);

    servicesAvailable = servicesConnected();

    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    locationManager.addGpsStatusListener(this);

    setUpLocationClientIfNeeded();
}

/**
 * Create a new location client, using the enclosing class to
 * handle callbacks.
 */
protected synchronized void buildGoogleApiClient()
{
    this.mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
}

private boolean servicesConnected()
{

    // Check that Google Play services is available
    int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);

    // If Google Play services is available
    if (ConnectionResult.SUCCESS == resultCode)
    {
        return true;
    }
    else
    {
        return false;
    }
}

public int onStartCommand(Intent intent, int flags, int startId)
{
    super.onStartCommand(intent, flags, startId);

    if (!servicesAvailable || mGoogleApiClient.isConnected() || mInProgress)
        return START_STICKY;

    setUpLocationClientIfNeeded();
    if (!mGoogleApiClient.isConnected() || !mGoogleApiClient.isConnecting() && !mInProgress)
    {
        mInProgress = true;
        mGoogleApiClient.connect();
    }
    return START_STICKY;
}


private void setUpLocationClientIfNeeded()
{
    if (mGoogleApiClient == null)
        buildGoogleApiClient();
}

public void onGpsStatusChanged(int event)
{

}

// Define the callback method that receives location updates
@Override
public void onLocationChanged(Location location)
{
    simpleGPSFilter(location);
}

// Other fancy and needed stuff here...

/**
 * "Stupid" filter that utilizes experience data to filter out location noise.
 * @param location Location object carrying all the needed information
 */
private void simpleGPSFilter(Location location)
{
    //Loading all the required variables
    int signalPower = 0;
    satellites = 0;
    // Getting the satellites
    mGpsStatus = locationManager.getGpsStatus(mGpsStatus);
    Iterable<GpsSatellite> sats = mGpsStatus.getSatellites();
    if (sats != null)
    {
        for (GpsSatellite sat : sats)
        {
            if (sat.usedInFix())
            {
                satellites++;
                signalPower += sat.getSnr();
            }
        }
    }
    if (satellites != 0)
        signalPower = signalPower/satellites;
    mySpeed = (location.getSpeed() * 3600) / 1000;
    myAccuracy = location.getAccuracy();
    myBearing = location.getBearing();
    latitude = location.getLatitude();
    longitude = location.getLongitude();
    Log.i("START OF CYCLE", "START OF CYCLE");
    Log.i("Sat Strength", Integer.toString(signalPower));
    Log.i("Locked Sats", Integer.toString(satellites));

    // Do the math for the coordinates distance
    /*
     * Earth's radius at given Latitude.
     * Formula: Radius = sqrt( ((equatorR^2 * cos(latitude))^2 + (poleR^2 * sin(latitude))^2 ) / ((equatorR * cos(latitude))^2 + (poleR * sin(latitude))^2)
     * IMPORTANT: Math lib uses radians for the trigonometry equations so do not forget to use toRadians()
     */
    Log.i("Lat for Radius", Double.toString(latitude));
    double earthRadius = Math.sqrt((Math.pow((EARTH_RADIUS_EQUATOR * EARTH_RADIUS_EQUATOR * Math.cos(Math.toRadians(latitude))), 2)
            + Math.pow((EARTH_RADIUS_POLES * EARTH_RADIUS_POLES * Math.cos(Math.toRadians(latitude))), 2))
            / (Math.pow((EARTH_RADIUS_EQUATOR * Math.cos(Math.toRadians(latitude))), 2)
            + Math.pow((EARTH_RADIUS_POLES * Math.cos(Math.toRadians(latitude))), 2)));
    Log.i("Earth Radius", Double.toString(earthRadius));

    /*
     * Calculating distance between 2 points on map using the Haversine formula (arctangent writing) with the following algorithm
     * latDifference = latitude - lastLatitude;
     * lngDifference = longitude - lastLongitude;
     * a = (sin(latDifference/2))^2 + cos(lastLatitude) * cos(latitude) * (sin(lngDifference/2))^2
     * c = 2 * atan2( sqrt(a), sqrt(1-a) )
     * distance = earthRadius * c
     */
    double latDifference = latitude - lastLatitude;
    double lngDifference = longitude - lastLongitude;
    double a = Math.pow((Math.sin(Math.toRadians(latDifference / 2))), 2) + (Math.cos(Math.toRadians(lastLatitude))
            * Math.cos(Math.toRadians(latitude))
            * Math.pow((Math.sin(Math.toRadians(lngDifference / 2))), 2));
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    double distance = earthRadius * c;
    Log.i("New point distance", Double.toString(distance));

    // Filter logic
    // Make an initial location log
    if ((!isInit) && (myAccuracy < ACCEPTED_ACCURACY))
    {
        isInit = true;
        lastLatitude = latitude;
        lastLongitude = longitude;
        logLocations(location);
    }
    else
    {
        // Satellite lock (use of GPS) on the higher level
        if (satellites == 0)
        {
            // Accuracy filtering at the second level
            if (myAccuracy < ACCEPTED_ACCURACY)
            {
                if ((distance > ACCEPTED_DISTANCE))
                {
                    lastLatitude = latitude;
                    lastLongitude = longitude;
                    logLocations(location);
                    Log.i("Location Logged", "No Sats");
                    /*
                    // Calculate speed in correlation to perceived movement
                    double speed = distance / (PREFERRED_INTERVAL / 1000);  // TODO: Need to make actual time dynamic as the fused location does not have fixed timing
                    if (speed < ACCEPTED_SPEED)
                    {
                        lastLatitude = latitude;
                        lastLongitude = longitude;
                        logLocations(location);
                    } */
                }
            }
        }
        else if ((satellites < 4) && (signalPower > ACCEPTED_SIGNAL))
        {
            if (myAccuracy < (ACCEPTED_ACCURACY + 50))
            {
                logLocations(location);
                Log.i("Location Logged", "With Sats");
            }
        }
        else
        {
            if (myAccuracy < (ACCEPTED_ACCURACY + 100))
            {
                lastSpeed = mySpeed;
                lastBearing = myBearing;
                lastLatitude = latitude;
                lastLongitude = longitude;
                logLocations(location);
                Log.i("Location Logged", "With Good Sats");
            }
        }
    }
    Log.i("END OF CYCLE", "END OF CYCLE");
}

private void logLocations(Location location)
{
    String myprovider = "false";

    String temp = timestampFormat.format(location.getTime());
    MySQLiteHelper dbHelper = new MySQLiteHelper(getApplicationContext());

    try
    {
        dbHelper.createEntry(latitude, longitude, allschemes, temp, mySpeed, myAccuracy, myBearing, myprovider, satellites);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

    CheckAutoArrive(String.valueOf(latitude), String.valueOf(longitude));

}
public abstract PendingResult<Status> requestLocationUpdates (GoogleApiClient client, LocationRequest request, LocationListener listener, Looper looper)