0

私は1つのアクティビティでロケーションアップデートを登録するために以下のコードを使用していますが、私のアプリがこのリクエストを登録しているかどうかを確認するにはどうすればいいですか?(、またはアクティブロケーションリクエスト)ロケーションの応答を待っているので、重複したリクエストはしません。私は私のアプリを閉じて、この要求を停止することなく、再びそれを実行することがあります。私のFusedLocationリクエストのリスト

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

答えて

-2
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)); 

} 

これは基本的に動作しますが、あなたはこれらの事の詳細な説明が必要な場合は、私の中で私のYouTubeチャンネルTechzologyをご覧くださいことJAVAの融合ロケーションに関する今後のビデオ。

+0

説明なしで250行以上のコードを投稿することは、正確にStack Overflowの答えの定義ではありません。 –

1

しかし、私のアプリがこのリクエストを登録している(またはアクティブなロケーションリクエストをクエリしていない)かどうかを確認するにはどうすればいいですか?

[FusedLocationProvider API(https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderApi#requestLocationUpdates(com.google.android.gms.common.api.GoogleApiClient、com.google.android.gms.location.LocationRequest、com.google.android.gms.location.LocationListener、android.os.Looper))については、この文書によれば、

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

上記のコードすることができます

戻る通話のためのPendingResult、それが成功した かどうかを判断するためにisSuccess()を確認してください。

たぶん、あなたは要求がすでに登録されているかどうかを確認し、それがtrueをスローした場合、それはすでに別の要求を行って停止する必要があることをその検証を適用するisSuccess()を試みることができます。

関連する問題