2017-10-14 76 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

相关问题