首页 > 解决方案 > 如何创建正确的“this”对象作为参数?

问题描述

我正在尝试编写一个函数,我必须将一个 Activity 对象传递给一个需要这样一个参数的方法。通常在这种情况下,我应该只输入“this”,它会自动识别它应该创建的对象类型。但有时这不起作用,并且无论出于何种原因,它都会重新评估与所需对象不同类型的对象。例如,我实际上在这两种情况下都使用了完全相同的方法:

if (checkLocationPermission(this)){

在第一个中,程序自动将“this”识别为 Activity 对象。这是第二个:

@Override
            public void onSuccess(Location location) {
                if (location == null || !checkLocationPermission(this)){

在这种情况下,完全相同的方法将“this”识别为 OnSuccessListener 而不是 Activity。我在同一个程序中的另一个示例是“this”对象应该是 Looper,但它再次被识别为 OnSuccessListener:

fusedLocationClient.requestLocationUpdates(locationRequest,new LocationCallback(),this);

我不知道如何为“this”参数实际选择正确的对象类型,因为我只能输入同一个该死的词。


编辑:

这是完整的代码。我使用 Looper.this 只是为了让你更容易找到它。我也尝试过 MapsActivity.this 但它不起作用:

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

private GoogleMap mMap;
private GoogleApiClient googleApiClient;
public static final String TAG = MapsActivity.class.getSimpleName();
private FusedLocationProviderClient fusedLocationClient;
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000; //Request code to send to Google Play Services
private LocationRequest locationRequest;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    setUpMapIfNeeded();
    googleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
    locationRequest = LocationRequest.create().setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY).setInterval(10*1000).setFastestInterval(1*1000);
}

private void setUpMapIfNeeded(){
    if (mMap==null){
        SupportMapFragment mapFragment = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map));
        mapFragment.getMapAsync(this);
    }
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    //setUpMap();

    // Add a marker in Sydney and move the camera
    LatLng sydney = new LatLng(-34, 151);
    mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}

@Override
public void onConnected(Bundle bundle) {
    Log.i(TAG,"Location Services Connected");
    fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
    if (checkLocationPermission(this)){
        fusedLocationClient.getLastLocation().addOnSuccessListener(this, new OnSuccessListener<Location>() {
            @Override
            public void onSuccess(Location location) {
                if (location == null || !checkLocationPermission(MapsActivity.this)){
                    fusedLocationClient.requestLocationUpdates(locationRequest,new LocationCallback(),Looper.this);
                }
                else{
                    handleNewLocation(location);
                }
            }
        });
    }

}
public static boolean checkLocationPermission(Activity activity){
    if(ActivityCompat.checkSelfPermission(activity, android.Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED
            || ActivityCompat.checkSelfPermission(activity, android.Manifest.permission.ACCESS_COARSE_LOCATION)
            != PackageManager.PERMISSION_GRANTED){

        ActivityCompat.requestPermissions(activity, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION,
                android.Manifest.permission.ACCESS_COARSE_LOCATION},0);
        return false;
    }
    return true;
}

private void handleNewLocation(Location location){
    Log.d(TAG,location.toString());
}

@Override
public void onConnectionSuspended(int i) {
    Log.i(TAG,"Location Services suspended. Please reconnect.");
}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    if (connectionResult.hasResolution()){
        //Starts an Activity that tries to resolve the error
        try {
            connectionResult.startResolutionForResult(this,CONNECTION_FAILURE_RESOLUTION_REQUEST);
        } catch (IntentSender.SendIntentException e) {
            e.printStackTrace();
        }
    }
    else{
        Log.i(TAG,"Location services connection failed code: " + connectionResult.getErrorCode());
    }
}

@Override
protected void onResume(){
    super.onResume();
    setUpMapIfNeeded();
    googleApiClient.connect();
}

@Override
protected void onPause(){
    super.onPause();
    if (googleApiClient.isConnected()){
        googleApiClient.disconnect();
    }
}

@Override
public void onLocationChanged(Location location) {
    handleNewLocation(location);
}
}

标签: javaandroid

解决方案


this对应于使用它的对象。onSuccessOnSuccessListener类的方法,因此this指的是OnSuccessListener. 你需要使用ActivityName.this. 例如,如果您的活动名称是MainActivity,那么

@Override
public void onSuccess(Location location) {
    if (location == null || !checkLocationPermission(MainActivity.this)){

推荐阅读