2016-10-15 104 views
2

這個問題可能會問很多時間,但我找不到任何解決方案。 我需要在後臺獲取用戶的位置,歷時15分鐘。即使使用融合位置API關閉gps,如何獲取位置更新?

當GPS打開時它工作正常,但當GPS關閉時,應用程序沒有獲取位置更新。我需要它至少得到網絡位置或WiFi位置。

如何使用融合位置API實現此目標?

位置管理器具有此功能,但在融合的位置。因爲Google建議開發者使用Play服務API中的位置信息,所以我不想使用位置管理器。 我怎樣才能做到這一點,所以讓我寄我試過到目前爲止:

import android.content.Context; 
import android.location.Location; 
import android.os.Bundle; 
import android.support.annotation.NonNull; 
import android.util.Log; 

import com.google.android.gms.common.ConnectionResult; 
import com.google.android.gms.common.api.GoogleApiClient; 
import com.google.android.gms.location.FusedLocationProviderApi; 
import com.google.android.gms.location.LocationListener; 
import com.google.android.gms.location.LocationRequest; 
import com.google.android.gms.location.LocationServices; 

/** 
* Created by 4264 on 14-10-2016. 
*/ 

public class Locationlistener implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,LocationListener { 


    private Location mlocation; // location 
    private double latitude; // latitude 
    private double longitude; // longitude 
    private GoogleApiClient mGAC; 
    private Context mContext; 
    public static final String TAG = "GPSresource"; 
    private FusedLocationProviderApi fusedLocationProviderApi; 
    private LocationRequest locationRequest; 

    public Locationlistener(Context c) 
    { 
     mContext = c; 
     try { 
      buildGoogleApiClient(); 
      mGAC.connect(); 
     } 
     catch(Exception e) 
     { 
      Log.d(TAG,e.toString()); 
     } 
    } 

    protected synchronized void buildGoogleApiClient() { 
     locationRequest = LocationRequest.create(); 
     locationRequest.setPriority(LocationRequest.PRIORITY_LOW_POWER); 
     locationRequest.setInterval(1); 
     locationRequest.setFastestInterval(1); 
     mGAC = new GoogleApiClient.Builder(mContext) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .addApi(LocationServices.API) 
       .build(); 
     } 


    public double getLatitude(){ 
     if(mlocation != null){ 
      latitude = mlocation.getLatitude(); 
     } 

     // return latitude 
     return latitude; 
    } 

    /** 
    * Function to get longitude 
    * */ 
    public double getLongitude() { 
     if (mlocation != null) { 
      longitude = mlocation.getLongitude(); 
     } 

     // return longitude 
     return longitude; 
    } 

    public Location GetLocationBlocking() throws InterruptedException { 



     //  String lat=String.valueOf(moCurrentLocation.getLatitude()); 
     // String longt=String.valueOf(moCurrentLocation.getLongitude()); 
//  Toast.makeText(oContext,"Lat"+lat+"long"+longt,Toast.LENGTH_SHORT).show(); 
     return mlocation; 

    } 


    @Override 
    public void onConnected(Bundle bundle) { 
      Location oLocation = LocationServices.FusedLocationApi.getLastLocation(mGAC); 
      if (mGAC != null) { 

       mlocation = oLocation; 
      getLatitude(); 
      getLongitude(); 
      if (oLocation != null){ 
       Log.d("lat",String.valueOf(mlocation.getLatitude())); 
      Log.d("long",String.valueOf(mlocation.getLongitude())); 
      } 
      else{ 
       LocationServices.FusedLocationApi.requestLocationUpdates(mGAC, locationRequest, this); 
     } }} 


    @Override 
    public void onConnectionSuspended(int i) { 

    } 




    @Override 
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { 

    } 

    @Override 
    public void onLocationChanged(Location location) { 
     mlocation=location; 
    } 
} 
+0

看到.http://stackoverflow.com/questions/34305377/get-current-location-0-in-marshmallow-where-below-23-api-its-give-exact-current –

回答

1

我不當你說你不想使用位置管理器和GPS ......看看這個Location Strategies明白.. 。基於這個文檔我們有3個策略訪問的位置:

  1. 全球定位系統
  2. 網絡位置提供商
  3. 或同時使用

但對於您的位置問題,這是我的建議: 內的活動,把下面的連接並開始接收位置更新:

private GoogleApiClient mGoogleApiClient; 
private LocationRequest mLocationRequest; 

private long UPDATE_INTERVAL = 10 * 1000; /* 10 secs */ 
private long FASTEST_INTERVAL = 2000; /* 2 sec */ 

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    // Create the location client to start receiving updates 
    mGoogleApiClient = new GoogleApiClient.Builder(this) 
          .addApi(LocationServices.API) 
          .addConnectionCallbacks(this) 
          .addOnConnectionFailedListener(this).build(); 
} 

protected void onStart() { 
    super.onStart(); 
    // Connect the client. 
    mGoogleApiClient.connect(); 
} 

protected void onStop() { 
    // Disconnecting the client invalidates it. 
    LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this); 

    // only stop if it's connected, otherwise we crash 
    if (mGoogleApiClient != null) { 
     mGoogleApiClient.disconnect(); 
    } 
    super.onStop(); 
} 

public void onConnected(Bundle dataBundle) { 
    // Get last known recent location. 
    Location mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); 
    // Note that this can be NULL if last location isn't already known. 
    if (mCurrentLocation != null) { 
     // Print current location if not null 
     Log.d("DEBUG", "current location: " + mCurrentLocation.toString()); 
     LatLng latLng = new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude()); 
    } 
    // Begin polling for new location updates. 
    startLocationUpdates(); 
} 

@Override 
public void onConnectionSuspended(int i) { 
    if (i == CAUSE_SERVICE_DISCONNECTED) { 
     Toast.makeText(this, "Disconnected. Please re-connect.", Toast.LENGTH_SHORT).show(); 
    } else if (i == CAUSE_NETWORK_LOST) { 
     Toast.makeText(this, "Network lost. Please re-connect.", Toast.LENGTH_SHORT).show(); 
    } 
} 

// Trigger new location updates at interval 
protected void startLocationUpdates() { 
    // Create the location request 
    mLocationRequest = LocationRequest.create() 
     .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY) 
     .setInterval(UPDATE_INTERVAL) 
     .setFastestInterval(FASTEST_INTERVAL); 
    // Request location updates 
    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, 
     mLocationRequest, this); 
} 

,然後用onLocationChanged註冊位置更新:

public void onLocationChanged(Location location) { 
    // New location has now been determined 
    String msg = "Updated Location: " + 
     Double.toString(location.getLatitude()) + "," + 
     Double.toString(location.getLongitude()); 
    Toast.makeText(this, msg, Toast.LENGTH_SHORT).show(); 
    // You can now create a LatLng Object for use with maps 
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude()); 
} 

有關熔合位置API的更多信息,請參閱Make ypur app Location Aware 故障排除位置更新

應該始終使用GoogleApiClient來完成位置更新,如上所示利用LocationServices.API。不要使用較不可靠的較舊的Location API。即使使用正確的FusedLocationApi,也有很多事情可能會出錯。考慮以下潛在問題:

  • 您是否添加了必要的權限?確保您的應用程序具有 INTERNETACCESS_COARSE_LOCATION權限,以確保可以按照上述指南中的說明訪問 位置。
  • 您是否在致電 LocationServices.FusedLocationApi.getLastLocation時變空?這是正常的 ,因爲如果最近已由另一個應用程序檢索到位置 ,則此方法僅返回。如果返回null,則此 表示您需要開始接收位置更新,其中 LocationServices.FusedLocationApi.requestLocationUpdates在 之前接收到上述位置。
  • 您是否試圖在genymotion模擬器上獲取位置?確保 您已啓用GPS並正確配置了lat/lng。如果需要,嘗試重新啓動 模擬器,並重新啓用GPS或嘗試設備(或 官方模擬器),而不是排除genymotion特定的問題。
+0

它應該在不與用戶交互的情況下在後臺運行,那麼如何與活動連接 –