在API级别21上进行测试时,mLastLocation为null,但在API级别25上则不是这种情况。
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
@Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
@Override
protected void onStop() {
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
super.onStop();
}
@Override
public void onConnected(@Nullable Bundle bundle) {
checkInBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (ActivityCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED)
{
// Permission is not granted
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
}
else {
createLocationRequest();
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, MainActivity.this);
} else {
progressBar.setVisibility(View.VISIBLE);
DateFormat df = new SimpleDateFormat("EEE, d MMM yyyy");
String checkInDate = df.format(Calendar.getInstance().getTime());
DateFormat df1 = new SimpleDateFormat("h: mm a");
String checkInTime = df1.format(Calendar.getInstance().getTime());
final DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Users")
.child(FirebaseAuth.getInstance().getCurrentUser().getPhoneNumber())
.child("Check_in")
.child(checkInDate).child(checkInTime);
latValue = String.valueOf(mLastLocation.getLatitude());
longValue = String.valueOf(mLastLocation.getLongitude());
String address = getCompleteAddressString(Double.parseDouble(latValue), Double.parseDouble(longValue));
ref.child("Latitude").setValue(latValue).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
ref.child("Longitude").setValue(longValue).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
progressBar.setVisibility(View.GONE);
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("isCheckedIn", true).apply();
Snackbar snackbar = Snackbar
.make(coordinatorLayoutMainActivity, "Check-in successful !", Snackbar.LENGTH_INDEFINITE);
View snackbarView = snackbar.getView();
snackbarView.setBackgroundColor(getResources().getColor(R.color.Green));
TextView tv = (TextView) snackbarView.findViewById(android.support.design.R.id.snackbar_text);
tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.snackbar_text_size));
snackbar.show();
checkInBtn.setVisibility(View.GONE);
checkOutBtn.setVisibility(View.VISIBLE);
} else {
Snackbar snackbar = Snackbar
.make(coordinatorLayoutMainActivity, "Please try again.", Snackbar.LENGTH_INDEFINITE);
View snackbarView = snackbar.getView();
snackbarView.setBackgroundColor(getResources().getColor(R.color.Red));
TextView tv = (TextView) snackbarView.findViewById(android.support.design.R.id.snackbar_text);
tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.snackbar_text_size));
snackbar.show();
}
}
});
} else {
Snackbar snackbar = Snackbar
.make(coordinatorLayoutMainActivity, "Please try again.", Snackbar.LENGTH_INDEFINITE);
View snackbarView = snackbar.getView();
snackbarView.setBackgroundColor(getResources().getColor(R.color.Red));
TextView tv = (TextView) snackbarView.findViewById(android.support.design.R.id.snackbar_text);
tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.snackbar_text_size));
snackbar.show();
}
}
});
ref.child("Address").setValue(address);
}
}
}
});
@SuppressLint({"RestrictedApi", "MissingPermission"})
protected void createLocationRequest() {
//remove location updates so that it resets
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this); //Import should not be **android.Location.LocationListener**
//import should be **import com.google.android.gms.location.LocationListener**;
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
//restart location updates with the new interval
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
@SuppressLint("MissingPermission")
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_CONTACTS: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission was granted
// Do the contacts-related task you need to do.
createLocationRequest();
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
} else {
// permission denied. Disable the
// functionality that depends on this permission.
Snackbar snackbar = Snackbar
.make(coordinatorLayoutMainActivity, "You need to allow access to location.", Snackbar.LENGTH_LONG);
View snackbarView = snackbar.getView();
snackbarView.setBackgroundColor(getResources().getColor(R.color.Red));
TextView tv = (TextView) snackbarView.findViewById(android.support.design.R.id.snackbar_text);
tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.snackbar_text_size_18sp));
snackbar.show();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request.
}
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
@Override
public void onLocationChanged(Location location) {
}
我想做的就是在用户按下按钮时获取其位置。
它可以在Android Nougat上正常工作(要求运行时权限,然后可以正常工作),但不能在Android Lollipop上正常工作(在棉花糖之前的版本中没有运行时权限的概念)。
可能是什么问题?