无法构建Google Api客户端

时间:2016-04-01 14:20:55

标签: android google-maps

我正在开发一个需要在许多活动中获取当前位置的应用程序,为了使事情更容易,我创建了一个包含所有要求的类,并通过Method get location获取位置。不幸的是,我不断收到大量错误,这里是活动代码,类和错误消息。

这是活动

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class Acceuil extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_acceuil);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }
    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
        public void onMapReady(GoogleMap googleMap) {
            mMap = googleMap;
        Locate Obj = new Locate(getParent());
        LatLng Loc=Obj.GetLocation();
            // Add a Marker Containing Last Known Location Provided By The Main Fragment
            LatLng Current = new LatLng(34.0132500,-6.8325500);
            mMap.addMarker(new MarkerOptions().position(Current).title("Your Current Location"));
            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(Current, 15));
        }
}

这是班级

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.model.LatLng;

/**
 * Created by Otmane on 26/03/2016.
 */
public class Locate  implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

    private final static int Play_services_resolution_request = 1000;
    private Location mLocation;
    private Location UpdatedLocation;
    private GoogleApiClient mGoogleApiClient;
    private boolean mRequestingLocationUpdates = false;
    private LocationRequest mLocationRequest;
    private static int Update_Interval = 10000; // 10 Seconds
    private static int Fastest_Interval = 5000; // 5 Seconds
    private static int Displacement = 10; // 10 meters
    private Context mContext;
    private boolean toggleUpdate= false;

    public Locate(Context context) {
        this.mContext = context;
        try {
            buildGoogleApiClient();
        }
        catch (Exception e )
        {
            /*AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mContext);
            alertDialogBuilder.setMessage("Unable To Connect To Location Services");
            alertDialogBuilder.show();*/
        }
        createLocationRequest();
        GetLocation();
    }
    public void setUpdate(boolean State)
    {
        this.toggleUpdate=State;
    }

    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(mContext)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
    }

    protected void createLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(Update_Interval);
        mLocationRequest.setFastestInterval(Fastest_Interval);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setSmallestDisplacement(Displacement);
    }

    protected void StartLocationUpdates() {
        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }

    protected void StopLocationUpdates() {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
    }


    public LatLng GetLocation() {
        buildGoogleApiClient();
        try{
            if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.*
                LatLng Temp= new LatLng(0.0,0.0);
                return Temp;
            }
        }
        catch (Exception e)
        {
            //Toast.makeText(this,"Permissions Error",Toast.LENGTH_LONG).show();
        }
        mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (mLocation!=null){
            LatLng Current = new LatLng(mLocation.getLatitude(),mLocation.getLongitude());
            return  Current;
        }
        LatLng Current = new LatLng(34.0132500,-6.8325500);
        return Current;
    }
    public void onConnected(@Nullable Bundle bundle) {
        GetLocation();
        if (toggleUpdate== true ){
            StartLocationUpdates();
        }
    }

    @Override
    public void onConnectionSuspended(int i) {
        mGoogleApiClient.connect();
    }
    public LatLng GetUpdatedLocation(LatLng Loc){
        return Loc;
    }

    @Override
    public void onLocationChanged(Location location) {
        UpdatedLocation=location;
        if (UpdatedLocation != null){
            LatLng temp =  new LatLng(UpdatedLocation.getLatitude(),UpdatedLocation.getLongitude());
            GetUpdatedLocation(temp);
        }
        else
        {
            LatLng temp =  new LatLng(0.0,0.0);
            GetUpdatedLocation(temp);
        }

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Toast.makeText(mContext,"Connection Failed",Toast.LENGTH_SHORT).show();
    }
}

这是错误讯息

53:41.486 14944-14944/otmos.pfe E/AndroidRuntime: FATAL EXCEPTION: main
                                                           Process: otmos.pfe, PID: 14944
                                                           java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Looper android.content.Context.getMainLooper()' on a null object reference
                                                               at com.google.android.gms.common.api.GoogleApiClient$Builder.<init>(Unknown Source)
                                                               at otmos.pfe.Locate.buildGoogleApiClient(Locate.java:56)
                                                               at otmos.pfe.Locate.GetLocation(Locate.java:90)
                                                               at otmos.pfe.Locate.<init>(Locate.java:48)
                                                               at otmos.pfe.Acceuil.onMapReady(Acceuil.java:38)
                                                               at com.google.android.gms.maps.SupportMapFragment$zza$1.zza(Unknown Source)
                                                               at com.google.android.gms.maps.internal.zzo$zza.onTransact(Unknown Source)
                                                               at android.os.Binder.transact(Binder.java:387)
                                                               at com.google.android.gms.maps.internal.v$a$a.a(:com.google.android.gms.alldynamite:82)
                                                               at maps.ei.bu$6.run(Unknown Source)
                                                               at android.os.Handler.handleCallback(Handler.java:739)
                                                               at android.os.Handler.dispatchMessage(Handler.java:95)
                                                               at android.os.Looper.loop(Looper.java:148)
                                                               at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                               at java.lang.reflect.Method.invoke(Native Method)
                                                               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

1 个答案:

答案 0 :(得分:0)

我认为您可以找到使用com.google.android.gms的任何库都可能出现此问题。

如果您在android / app / build.gradle中引用了com.google.android.gms。 尝试为关联的库提供当前已安装的新版本。

我通过导航到[YOUR_ANDROID_SDK] / extras / google / m2repository / com / google / android / gms找到了我正在使用的库的版本号 然后找到可能导致问题的库,例如play-services-auth。

在那里你会看到所有的版本。将最新应用于build.gradle。 编译'com.google.android.gms:play-services:10.2.1'

还添加(GoogleApiClient Builder中需要gcm) 编译'com.google.android.gms:play-services-gcm:10.2.1'