getLastLocation()。addOnSuccessListener在按钮中不起作用

时间:2018-04-13 06:59:19

标签: java android google-maps android-fusedlocation

我想设置一个按钮,当我按下按钮,然后获取位置。

FusedLocationProviderClient userLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

这可以在 onCreate 中使用,但我想设置一个按钮,当我按下按钮时, 然后告诉我用户位置。它不能工作。有我的代码,我该如何解决?

public class MainActivity extends AppCompatActivity{

final private int userAgreePermissionCode = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //  Check permission and go "onRequestPermissionsResult"
    int currentPermission = ActivityCompat.checkSelfPermission(this,android.Manifest.permission.ACCESS_FINE_LOCATION);
    if( currentPermission!=PackageManager.PERMISSION_GRANTED ) ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, userAgreePermissionCode);



    findViewById(R.id.Locate).setOnClickListener(new View.OnClickListener() {
        @SuppressLint("MissingPermission")
        @Override
        public void onClick(View v) {
            //  can't work
            FusedLocationProviderClient userLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);  //  Error in here!!
            userLocationProviderClient.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
                @Override
                public void onSuccess(Location location) {
                    Log.i("Longitude:", location.getLongitude()+"");
                    Log.i("Latitude:", location.getLatitude()+"");
                }
            });
        }
    });
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode) {
        case userAgreePermissionCode:
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted
                Log.i("Status:","Granted");
            } else {
                // Permission Denied
                finish();
            }
            break;
        default:
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

}

}

2 个答案:

答案 0 :(得分:1)

它不起作用,因为该范围中的this引用View.OnClientListener的实例。

您可以通过添加MainActivity.this来修复它,或者您可以将FusedLocationProviderClient作为成员字段,在onCreate中实例化,然后在您的点击侦听器中使用它。

答案 1 :(得分:0)

只改变这件事..

 FusedLocationProviderClient userLocationProviderClient = LocationServices.getFusedLocationProviderClient(Location.this);  //  hear give your activity name