2016-04-01 179 views
1

我正在開發一個應用程序,需要在許多活動中獲取當前位置,以使事情更輕鬆我創建了一個包含所有要求並通過Method獲取位置獲取位置的類。不幸的是,我不斷收到很多錯誤,這裏是活動代碼,類以及錯誤消息。無法構建Google Api客戶端

這是活動

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) 

回答

0

我認爲這個問題可以發生在任何使用com.google.android.gms的庫上。

如果您在android/app/build.gradle中引用了com.google.android.gms。 嘗試爲相關庫提供您當前已安裝的新版本。

我找到了導航到[YOUR_ANDROID_SDK]/extras/google/m2repository/com/google/android/gms的庫的版本號 然後找到可能導致您問題的庫,例如play-服務-auth的。

在那裏你會看到所有的版本。將最新的應用到您的build.gradle。 編譯「com.google.android.gms:播放服務:10.2.1」

另外補充(這似乎是必要的GoogleApiClient生成器GCM) 編譯「com.google.android.gms:播放服務 - gcm:10.2.1'