我正在尝试编写一个函数,其中我必须将Activity对象传递给需要此类参数的方法。通常在这种情况下,我应该只键入“ this”,它会自动识别应该创建的对象类型。但是有时这不起作用,并且由于某种原因,它会重新确定与所需对象不同类型的对象。例如,在这两种情况下,我实际上都使用完全相同的方法:
if (checkLocationPermission(this)){
在这第一个中,程序自动将“ this”识别为活动对象。这是第二个:
@Override
public void onSuccess(Location location) {
if (location == null || !checkLocationPermission(this)){
在这种情况下,完全相同的方法将“ this”识别为OnSuccessListener而不是Activity。 我在同一程序中的另一个示例是其中“此”对象应该是Looper的示例,但它再次被识别为OnSuccessListener:
fusedLocationClient.requestLocationUpdates(locationRequest,new LocationCallback(),this);
我不知道如何为“ 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);
}
}
答案 0 :(得分:0)
this
对应于使用它的对象。 onSuccess
是OnSuccessListener
类的方法,因此this
引用了OnSuccessListener
。您需要使用ActivityName.this
。例如,如果您的活动名称为MainActivity
,则
@Override
public void onSuccess(Location location) {
if (location == null || !checkLocationPermission(MainActivity.this)){
答案 1 :(得分:0)
当您使用匿名内部类(例如侦听器)并使用this
时,它指的是匿名内部类,因为这是您的当前位置。
例如,使用OnClickListener:
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//"this" here will refer to the OnClickListener instance you create
}
}
没有使用this
参数“创建”任何内容。它是对当前封闭类的直接引用。如果您需要引用活动,则可以使用:
ActivityClassName.this
只要您在内部类而不是静态类中即可。
如果您使用lambda(仅适用于API 24 +):
view.setOnClickListener((v) -> {
//"this" will reference your Activity because there's no inner class anymore
}
答案 2 :(得分:0)
this
是指直接封闭类的对象。因此,如果您将interface
或class
作为函数的参数,我们通常会这样:
functionThatTakesInterfaceOrClassAsArgument( new TheInterfaceOrClass {
@Override
public void someMethod () {
// if you use `this` here, it refers to the object of `TheInterfaceOrClass`
}
});
如果要使用<className>.this
因此,如果封闭的Activity
的名称为MyActivity
,则需要使用MyActivity.this
。