2017-10-14 87 views
0

我試圖使用此代碼獲取當前位置,它在啓動應用程序時以及將其引入前臺時起作用。在兩種情況下吐司都會出現,但否則他們不會。有人可以告訴我我在哪裏搞砸了嗎?onLocationChanged未在Android 6.0 API中調用23

public class LocationFragment extends Fragment implements GoogleApiClient.ConnectionCallbacks, 
    GoogleApiClient.OnConnectionFailedListener, LocationListener { 

double oldLon,oldLat; 

private static final String TAG = MainActivity.class.getSimpleName();  // LogCat tag 
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000; 
private static final int MY_PERMISSIONS_REQUEST_FINE_LOCATION = 100; 
private Location mLastLocation; 
private GoogleApiClient mGoogleApiClient; 
private FusedLocationProviderClient mFusedLocationClient; 

private LocationRequest mLocationRequest; 

// Location updates intervals in sec 
private static int UPDATE_INTERVAL = 10000; // 10 sec 
private static int FATEST_INTERVAL = 5000; // 5 sec 


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

    // First we need to check availability of play services 
    if (checkPlayServices()) { 

     buildGoogleApiClient(); 
     createLocationRequest(); 
    } 

} 

@Override 
public void onDetach() { 
    mCallback = null; // => avoid leaking 
    super.onDetach(); 
} 


public interface InterfaceTextClicked { 
    public void sendText(String text); 
} 


private boolean checkPermission(){ 

    if(ActivityCompat.checkSelfPermission(getContext(), 
      ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){ 
     System.out.println("We have been granted."); 
     return true;} 
    else return false; 
} 

private void requestPermission(){ 
    ActivityCompat.requestPermissions(getActivity(),new String[] 
      {ACCESS_FINE_LOCATION},MY_PERMISSIONS_REQUEST_FINE_LOCATION); 
} 

@Override 
public void onRequestPermissionsResult(int requestCode, 
             String permissions[], int[] grantResults) { 
    switch (requestCode) { 
     case MY_PERMISSIONS_REQUEST_FINE_LOCATION: { 
      // If request is cancelled, the result arrays are empty. 
      if (grantResults.length > 0 
        && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 

       // permission was granted, yay! 
       System.out.println("Permission Granted!"); 

      } else { 

       // permission denied, boo! 
       System.out.println("Permission Denied!"); 

       if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){ 
        if(shouldShowRequestPermissionRationale(ACCESS_FINE_LOCATION)){ 
         new AlertDialog.Builder(getActivity()) 
           .setMessage("Permission needed to access your location.") 
           .setPositiveButton("OK", new DialogInterface.OnClickListener(){ 
            @Override 
            public void onClick(DialogInterface dialog,int which){ 
             if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){ 
              requestPermissions(new String[]{ACCESS_FINE_LOCATION}, 
                MY_PERMISSIONS_REQUEST_FINE_LOCATION); 
             } 
            } 
           }) 
           .setNegativeButton("Cancel", null) 
           .create() 
           .show(); 
         return; 
        } 
       } 
      } 
      // return; 
     } 
     } 
} 

private void displayLocation(){ 

    System.out.println("Inside displayLocation"); 

    requestPermission(); 

    if(checkPermission()){ 
     mLastLocation = LocationServices.FusedLocationApi 
       .getLastLocation(mGoogleApiClient); 
    } 

    if (mLastLocation != null) { 
     double latitude = mLastLocation.getLatitude(); 
     double longitude = mLastLocation.getLongitude(); 

     System.out.println("Location1: "+latitude+" "+longitude); 
     if(Double.compare(oldLat,latitude)==0 || Double.compare(oldLon,longitude)==0){ 
      Toast.makeText(getContext(), "Location didn't change! "+latitude+ " "+ longitude, 
        Toast.LENGTH_LONG).show(); 
     }else{ 
      Toast.makeText(getContext(), "Location changed! NEW: "+latitude+ " "+ longitude+" OLD: "+oldLat+ " "+oldLon, 
        Toast.LENGTH_LONG).show(); 
     } 

     // mCallback.sendText(latitude+" "+longitude); 

     oldLon = longitude; 
     oldLat = latitude; 

    } else { 
     System.out.println("Couldn't get coordinates"); 
     if(mGoogleApiClient.isConnected()){ 
      System.out.println("Client connected"); 
     }else{ 
      System.out.println("Client NOT connected"); 
     } 
    } 
} 

/** 
* Creating google api client object 
* */ 
protected synchronized void buildGoogleApiClient() { 
    mGoogleApiClient = new GoogleApiClient.Builder(getContext()) 
      .addConnectionCallbacks(this) 
      .addOnConnectionFailedListener(this) 
      .addApi(LocationServices.API).build(); 

} 

/** 
* Method to verify google play services on the device 
* */ 
private boolean checkPlayServices() { 
    GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance(); 
    int resultCode = googleAPI.isGooglePlayServicesAvailable(getContext()); 
    if (resultCode != ConnectionResult.SUCCESS) { 
     if(googleAPI.isUserResolvableError(resultCode)){ 
      googleAPI.getErrorDialog(getActivity(),resultCode, 
        PLAY_SERVICES_RESOLUTION_REQUEST).show(); 
     } else { 
      Toast.makeText(getContext(), 
        "This device is not supported.", Toast.LENGTH_LONG) 
        .show(); 
      getActivity().finish(); 
     } 
     return false; 
    } 
    return true; 
} 

@Override 
public void onStart() { 
    super.onStart(); 
    if (mGoogleApiClient != null) { 
     mGoogleApiClient.connect(); 
    } 
} 

@Override 
public void onResume() { 
    super.onResume(); 
    if (mGoogleApiClient != null && !mGoogleApiClient.isConnected()) { 
     mGoogleApiClient.connect(); 
    } 
    checkPlayServices(); 
} 


@Override 
public void onStop() { 
    super.onStop(); 
    if (mGoogleApiClient.isConnected()) { 
     mGoogleApiClient.disconnect(); 
    } 
} 

/** 
* Creating location request object 
* */ 
protected void createLocationRequest() { 
    mLocationRequest = LocationRequest.create(); 
    mLocationRequest.setInterval(UPDATE_INTERVAL); 
    mLocationRequest.setFastestInterval(FATEST_INTERVAL); 
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); } 

/** 
* Starting the location updates 
* */ 
protected void startLocationUpdates() { 

    System.out.println("Inside startLocationUpdates"); 
    requestPermission(); 
    if(checkPermission()){ 

     if ((mGoogleApiClient != null) && (mGoogleApiClient.isConnected())){ 

      LocationServices.FusedLocationApi.requestLocationUpdates(
        mGoogleApiClient, mLocationRequest, this); 

     } 
    } 
} 


/** 
* Google api callback methods 
*/ 
@Override 
public void onConnectionFailed(ConnectionResult result) { 
    Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " 
      + result.getErrorCode()); 

} 

@Override 
public void onConnected(Bundle arg0){ 

     startLocationUpdates(); 
     // Once connected with google api, get the location 
     displayLocation(); 

} 

@Override 
public void onConnectionSuspended(int arg0) { 
    mGoogleApiClient.connect(); 
} 

@Override 
public void onPause() { 
    super.onPause(); 
    stopLocationUpdates(); 
} 



/** 
* Stopping location updates 
*/ 
protected void stopLocationUpdates() { 
    if ((mGoogleApiClient != null) && (mGoogleApiClient.isConnected())) { 
     LocationServices.FusedLocationApi.removeLocationUpdates(
       mGoogleApiClient, this); 
    } 
} 


@Override 
public void onLocationChanged(Location location) { 
    // Assign the new location 
    mLastLocation = location; 

    Toast.makeText(getContext(), "******Location changed!", 
      Toast.LENGTH_SHORT).show(); 

    // Displaying the new location on UI 
    displayLocation(); 

} 

}

對不起,投入這麼多的代碼在那裏,我還以爲我的錯誤可能是任何地方,所以不想切出任何東西。

日誌顯示如下:

10-14 01:10:27.408 14485-14485/com.android.wy.parkingauthoritytickingsystem I/System.out: Inside startLocationUpdates 
10-14 01:10:27.536 14485-14485/com.android.wy.parkingauthoritytickingsystem I/System.out: We have been granted. 
10-14 01:10:27.610 14485-14485/com.android.wy.parkingauthoritytickingsystem I/System.out: Inside displayLocation 
10-14 01:10:27.617 14485-14485/com.android.wy.parkingauthoritytickingsystem I/System.out: We have been granted. 
10-14 01:10:27.641 14485-14485/com.android.wy.parkingauthoritytickingsystem I/System.out: Location1: 40.4868602 -74.4388156 
+0

你能更具體至於您希望何時發送位置更改消息?問題是,一旦您收到第一次位置更新,在應用程序打開時您沒有收到額外的更新(但手機已被移動)?當您的活動暫停時,您正在禁用更新,因此您不會在後臺獲取它們。 –

+0

@MykWillis如代碼所述,我希望每5-10秒收到一次更新。是的,問題是我沒有收到第一個更新後的更新(是的,手機確實移動)。我不希望應用程序在後臺或任何其他工作,我只是希望它顯示更新,而應用程序在前臺。 – Shameed

回答

0

我看不出有什麼明顯的錯誤與您的代碼,但它正在它的API,可以通過deprecated versions of the location APIs而非new FusedLocationProviderClient interface調用。

當你宣佈一個新的風格FusedLocationProviderClient

private FusedLocationProviderClient mFusedLocationClient; 

你永遠不初始化或在運行時使用它;而你通過FusedLocationApi調用(舊法):

LocationServices.FusedLocationApi.requestLocationUpdates(
      mGoogleApiClient, mLocationRequest, this); 

您可以嘗試使用新的API,它有一個稍微強大的接口,來闡明你的問題的一些情況。你可以得到新的API接口:

mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this); 

然後你只需要調整你的類連接你的聽衆前添加onLocationAvailability回調按the documentation

mFusedLocationClient.requestLocationUpdates(mLocationRequest, 
      mLocationCallback, 
      null /* Looper */); 
+0

謝謝你指着我在正確的方向。我會仔細看看的。 :) – Shameed

相關問題