java.lang.ClassCastException:com.example.android.hereiam.MapsActivity无法强制转换为com.google.android.gms.location.LocationListener

时间:2017-11-21 15:17:14

标签: java android google-maps

请在我的主要活动中找到代码。

package com.example.android.hereiam;

import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.os.Build;
import android.os.Bundle;

import com.google.android.gms.common.api.GoogleApiClient;

import android.support.v4.content.ContextCompat;
import android.support.v4.app.FragmentActivity;

import com.google.android.gms.gcm.GcmListenerService;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.SupportMapFragment;

import android.content.pm.PackageManager;
import android.location.Location;

import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;

// Since it’s the easiest way of adding a map to your project, I’m going to stick with using




// a MapFragment//

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,



        GoogleApiClient.ConnectionCallbacks {
    private GoogleMap mMap;




    GoogleApiClient mGoogleApiClient;




    Marker mLocationMarker;
    Location mLastLocation;




    LocationRequest mLocationRequest;


    @RequiresApi(api = Build.VERSION_CODES.M)




    @Override




    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            checkLocationPermission();
        }


        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }


    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 1;

    @RequiresApi(api = Build.VERSION_CODES.M)




    public boolean checkLocationPermission() {



// In Android 6.0 and higher you need to request permissions at runtime, and the user has
        // the ability to grant or deny each permission. Users can also revoke a previously-granted
        // permission at any time, so your app must always check that it has access to each
        // permission, before trying to perform actions that require that permission. Here, we’re using
        // ContextCompat.checkSelfPermission to check whether this app currently has the
        // ACCESS_COARSE_LOCATION permission

        if (ContextCompat.checkSelfPermission(this,
                android.Manifest.permission.ACCESS_COARSE_LOCATION)




                // If your app does have access to COARSE_LOCATION, then this method will return
                // PackageManager.PERMISSION_GRANTED//




                != PackageManager.PERMISSION_GRANTED) {
            // If your app doesn’t have this permission, then you’ll need to request it by calling
// the ActivityCompat.requestPermissions method//
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    android.Manifest.permission.ACCESS_COARSE_LOCATION))
                requestPermissions(new String[]{
                                android.Manifest.permission.ACCESS_COARSE_LOCATION
                        },
                        MY_PERMISSIONS_REQUEST_LOCATION);
            else {
                // Request the permission by launching Android’s standard permissions dialog.
                // If you want to provide any additional information, such as why your app requires this
                // particular permission, then you’ll need to add this information before calling
                // requestPermission //
                requestPermissions(new String[]{
                                android.Manifest.permission.ACCESS_COARSE_LOCATION
                        },
                        MY_PERMISSIONS_REQUEST_LOCATION);
            }
            return false;
        } else {
            return true;
        }
    }

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

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        // Specify what kind of map you want to display. In this example I’m sticking with the
        // classic, “Normal” map

        mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) ;
        {
            if (ContextCompat.checkSelfPermission(this,
                    android.Manifest.permission.ACCESS_COARSE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED) {
                buildGoogleApiClient();
                // Although the user’s location will update automatically on a regular basis, you can also
                // give your users a way of triggering a location update manually. Here, we’re adding a
                // ‘My Location’ button to the upper-right corner of our app; when the user taps this button,
                // the camera will update and center on the user’s current location//

                mMap.setMyLocationEnabled(true);
            } else {
                buildGoogleApiClient();
                mMap.setMyLocationEnabled(true);
            }
        }
    }

    protected synchronized void buildGoogleApiClient() {
        // Use the GoogleApiClient.Builder class to create an instance of the
        // Google Play Services API client//
        mGoogleApiClient = new GoogleApiClient.Builder(this)



                .addConnectionCallbacks(this)
                .addApi(LocationServices.API)
                .build();

        // Connect to Google Play Services, by calling the connect() method//
        mGoogleApiClient.connect();
    }

    @Override
    // If the connect request is completed successfully, the onConnected(Bundle) method
    // will be invoked and any queued items will be executed//
    public void onConnected(Bundle bundle) {




        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(2000);
        if (ContextCompat.checkSelfPermission(this,
                android.Manifest.permission.ACCESS_COARSE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            // Retrieve the user’s last known location//
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, (LocationListener) this);
        }
    }

    @Override
    public void onConnectionSuspended(int i) {
    }

    // Displaying multiple ‘current location’ markers is only going to confuse your users!
    // To make sure there’s only ever one marker onscreen at a time, I’m using
    // mLocationMarker.remove to clear all markers whenever the user’s location changes.
    public class MyGcmListenerService extends GcmListenerService {

        @Override
        public void onMessageReceived(String from, Bundle data) {
            String message = data.getString("message");
        }

        public void onLocationChanged(Location location) {
            mLastLocation = location;
            if (mLocationMarker != null) {
                mLocationMarker.remove();
            }

            // To help preserve the device’s battery life, you’ll typically want to use
            // removeLocationUpdates to suspend location updates when your app is no longer
            // visible onscreen//
            if (mGoogleApiClient != null) {
                LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, (LocationListener) this);
            }
        }

        // Once the user has granted or denied your permission request, the Activity’s
        // onRequestPermissionsResult method will be called, and the system will pass
        // the results of the ‘grant permission’ dialog, as an int//


        public void onRequestPermissionsResult(int requestCode,
                                               String permissions[], int[] grantResults) {
            switch (requestCode) {
                case MY_PERMISSIONS_REQUEST_LOC`enter code here`ATION: {

                    // If the request is cancelled, the result array will be empty (0)//
                    if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                        // If the user has granted your permission request, then your app can now perform all its
                        // location-related tasks, including displaying the user’s location on the map//
                        if (ContextCompat.checkSelfPermission(this,
                                android.Manifest.permission.ACCESS_COARSE_LOCATION)
                                == PackageManager.PERMISSION_GRANTED) {
                            if (mGoogleApiClient == null) {
                                buildGoogleApiClient();
                            }
                            mMap.setMyLocationEnabled(true);
                        }
                    } else {
                        // If the user has denied your permission request, then at this point you may want to
                        // disable any functionality that depends on this permission//
                    }
                    return;
                }
            }
        }
    }
}

主要活动代码处理谷歌api给我正确的位置地方。
但我得到了错误:

  

处理:com.example.android.hereiam,PID:15899                                                                                java.lang.ClassCastException:com.example.android.hereiam.MapsActivity   无法转换为com.google.android.gms.location.LocationListener                                                                                    在   com.example.android.hereiam.MapsActivity.onConnected(MapsActivity.java:151)                                                                                    在com.google.android.gms.common.internal.zzk.zzp(未知来源)                                                                                    在com.google.android.gms.internal.zzrd.zzn(未知来源)                                                                                    在com.google.android.gms.internal.zzrb.zzass(未知来源)                                                                                    在com.google.android.gms.internal.zzrb.onConnected(未知来源)                                                                                    在com.google.android.gms.internal.zzrf.onConnected(未知来源)                                                                                    在com.google.android.gms.internal.zzqr.onConnected(未知来源)                                                                                    在com.google.android.gms.common.internal.zzj $ 1.onConnected(未知   资源)                                                                                    在com.google.android.gms.common.internal.zze $ zzj.zzavj(未知   资源)                                                                                    在com.google.android.gms.common.internal.zze $ zza.zzc(未知来源)                                                                                    在com.google.android.gms.common.internal.zze $ zza.zzv(未知来源)                                                                                    在com.google.android.gms.common.internal.zze $ zze.zzavl(未知   资源)                                                                                    在   com.google.android.gms.common.internal.zze $ zzd.handleMessage(未知   资源)                                                                                    在android.os.Handler.dispatchMessage(Handler.java:102)                                                                                    在android.os.Looper.loop(Looper.java:154)                                                                                    在android.app.ActivityThread.main(ActivityThread.java:6692)                                                                                    at java.lang.reflect.Method.invoke(Native Method)                                                                                    在   com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:1468)                                                                                    在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)11-21   14:45:42.935 15899-15944 / com.example.android.hereiam I / System.out:   (HTTPLog)-Static:isSBSettingEnabled false 11-21 14:45:42.935   15899-15944 / com.example.android.hereiam I / System.out:   (HTTPLog)-Static:isSBSettingEnabled false 11-21 14:45:44.702   15899-15971 / com.example.android.hereiam W / DynamiteModule:本地模块   com.google.android.gms.googlecertificates的描述符类没有   找到。 11-21 14:45:44.706 15899-15971 / com.example.android.hereiam   W / DynamiteModule:无法通过V2加载模块:   java.lang.ClassNotFoundException:没找到类   " com.google.android.gms.dynamite.DynamiteModule $ DynamiteLoaderClassLoader"   在路径上:DexPathList [[zip文件   " /data/app/com.example.android.hereiam-1/base.apk" ;,zip文件   " /data/app/com.example.android.hereiam-1/split_lib_dependencies_apk.apk" ;,   zip文件   " /data/app/com.example.android.hereiam-1/split_lib_slice_0_apk.apk" ;,   zip文件   " /data/app/com.example.android.hereiam-1/split_lib_slice_1_apk.apk" ;,   zip文件   " /data/app/com.example.android.hereiam-1/split_lib_slice_2_apk.apk" ;,   zip文件   " /data/app/com.example.android.hereiam-1/split_lib_slice_3_apk.apk" ;,   zip文件   " /data/app/com.example.android.hereiam-1/split_lib_slice_4_apk.apk" ;,   zip文件   " /data/app/com.example.android.hereiam-1/split_lib_slice_5_apk.apk" ;,   zip文件   " /data/app/com.example.android.hereiam-1/split_lib_slice_6_apk.apk" ;,   zip文件   " /data/app/com.example.android.hereiam-1/split_lib_slice_7_apk.apk" ;,   zip文件   " /data/app/com.example.android.hereiam-1/split_lib_slice_8_apk.apk" ;,   zip文件   " /data/app/com.example.android.hereiam-1/split_lib_slice_9_apk.apk"],nativeLibraryDirectories = [/数据/应用/ com.example.android.hereiam-1 / LIB / arm64,   / system / lib64,/ vendor / lib64]] 11-21 14:45:44.737   15899-15971 / com.example.android.hereiam I / DynamiteModule:考虑   本地模块com.google.android.gms.googlecertificates:0和远程   模块com.google.android.gms.googlecertificates:4 11-21 14:45:44.737   15899-15971 / com.example.android.hereiam I / DynamiteModule:已选中   远程版本的com.google.android.gms.googlecertificates,版本

     
    

= 4 11-21 14:45:44.763 15899-15971 / com.example.android.hereiam W / System:ClassLoader引用未知路径:     /data/user_de/0/com.google.android.gms/app_chimera/m/00000038/n/arm64-v8a

  

2 个答案:

答案 0 :(得分:3)

您应该实现LocationListener,并且不要尝试将您的活动转换为LocationListener。

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener { 

实施LocationListener方法

并替换此

 (LocationListener) this

到此

 this

答案 1 :(得分:0)

您需要在MapsActivity类中实现LocationListener。然后你可以做流量: 替换这一行

<div class="center">
  <input type="number" name="height" placeholder="weight">
  <span>kg</span>
  <input type="number" name="weight" placeholder="height">
  <span>cm</span>
</div>

用这个:

LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, (LocationListener) this);

和这一行:

LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);

用这个:

LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, (LocationListener) this);