android fused location api,android - FusedLocationApi.getLastLocation always null - Stack Overflow

MainActivity.java

public class MainActivity extends AppCompatActivity {

private static final int REQUEST_CHECK_SETTINGS = 1;

private static final int REQUEST_GRANT_PERMISSION = 2;

private FusedLocationProviderClient fusedLocationClient;

LocationRequest locationRequest;

private Location currentLocation;

private LocationCallback locationCallback;

Button getUpdates,removeUpdates;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

createLocationRequest();

settingsCheck();

getUpdates = findViewById(R.id.button);

removeUpdates = findViewById(R.id.button2);

getUpdates.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ) {

ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_GRANT_PERMISSION);

return;

}

if(locationCallback==null)

buildLocationCallback();

if(currentLocation==null)

fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());

}

});

removeUpdates.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ) {

ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_GRANT_PERMISSION);

return;

}

if(locationCallback!=null)

fusedLocationClient.removeLocationUpdates(locationCallback);

}

});

}

protected void createLocationRequest() {

locationRequest = LocationRequest.create();

locationRequest.setInterval(10000);

locationRequest.setFastestInterval(5000);

locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

}

// Check for location settings

public void settingsCheck() {

LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()

.addLocationRequest(locationRequest);

SettingsClient client = LocationServices.getSettingsClient(this);

Task task = client.checkLocationSettings(builder.build());

task.addOnSuccessListener(this, new OnSuccessListener() {

@Override

public void onSuccess(LocationSettingsResponse locationSettingsResponse) {

// All location settings are satisfied. The client can initialize

// location requests here.

Log.d("TAG", "onSuccess: settingsCheck");

getCurrentLocation();

}

});

task.addOnFailureListener(this, new OnFailureListener() {

@Override

public void onFailure(@NonNull Exception e) {

if (e instanceof ResolvableApiException) {

// Location settings are not satisfied, but this can be fixed

// by showing the user a dialog.

Log.d("TAG", "onFailure: settingsCheck");

try {

// Show the dialog by calling startResolutionForResult(),

// and check the result in onActivityResult().

ResolvableApiException resolvable = (ResolvableApiException) e;

resolvable.startResolutionForResult(MainActivity.this,

REQUEST_CHECK_SETTINGS);

} catch (IntentSender.SendIntentException sendEx) {

// Ignore the error.

}

}

}

});

}

public void getCurrentLocation(){

if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);

return;

}

fusedLocationClient.getLastLocation()

.addOnSuccessListener(this, new OnSuccessListener() {

@Override

public void onSuccess(Location location) {

Log.d("TAG", "onSuccess: getLastLocation");

// Got last known location. In some rare situations this can be null.

if (location != null) {

currentLocation=location;

Log.d("TAG", "onSuccess:latitude "+location.getLatitude());

Log.d("TAG", "onSuccess:longitude "+location.getLongitude());

}else{

Log.d("TAG", "location is null");

buildLocationCallback();

}

}

});

}

private void buildLocationCallback() {

locationCallback = new LocationCallback() {

@Override

public void onLocationResult(LocationResult locationResult) {

if (locationResult == null) {

return;

}

for (Location location : locationResult.getLocations()) {

// Update UI with location data

currentLocation=location;

Log.d("TAG", "onLocationResult: "+currentLocation.getLatitude());

}

};

};

}

//called after user responds to location permission popup

@Override

public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

super.onRequestPermissionsResult(requestCode, permissions, grantResults);

if(requestCode==REQUEST_GRANT_PERMISSION){

getCurrentLocation();

}

}

//called after user responds to location settings popup

@Override

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

super.onActivityResult(requestCode, resultCode, data);

Log.d("TAG", "onActivityResult: ");

if(requestCode==REQUEST_CHECK_SETTINGS && resultCode==RESULT_OK)

getCurrentLocation();

if(requestCode==REQUEST_CHECK_SETTINGS && resultCode==RESULT_CANCELED)

Toast.makeText(this, "Please enable Location settings...!!!", Toast.LENGTH_SHORT).show();

}}

XML file

<?xml version="1.0" encoding="utf-8"?>

xmlns:app="http://schemas.android.com/apk/res-auto"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context="com.example.locationexample.MainActivity">

android:id="@+id/button"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_marginEnd="8dp"

android:layout_marginStart="8dp"

android:layout_marginTop="88dp"

android:text="getLocationUpdates"

app:layout_constraintEnd_toEndOf="parent"

app:layout_constraintHorizontal_bias="0.502"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintTop_toTopOf="parent" />

android:id="@+id/button2"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_marginBottom="8dp"

android:layout_marginEnd="8dp"

android:layout_marginStart="8dp"

android:layout_marginTop="8dp"

android:text="RemoveLocationUpdates"

app:layout_constraintBottom_toBottomOf="parent"

app:layout_constraintEnd_toEndOf="parent"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintTop_toBottomOf="@+id/button"

app:layout_constraintVertical_bias="0.363" /

Manifest File

<?xml version="1.0" encoding="utf-8"?>

package="com.example.locationexample">

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:roundIcon="@mipmap/ic_launcher_round"

android:supportsRtl="true"

android:theme="@style/AppTheme">

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值