2016-03-06 107 views
1

我試圖讓使用谷歌播放Services.I在我gradle.Here添加compile 'com.google.android.gms:play-services:8.4.0'我的位置是我使用的代碼:java.lang.IllegalArgumentException異常:GoogleApiClient參數是必需

import android.Manifest; 
import android.app.Activity; 
import android.content.pm.PackageManager; 
import android.os.Build; 
import android.os.Bundle; 

import android.location.Location; 
import android.util.Log; 
import android.view.View; 
import android.widget.Button; 
import android.widget.TextView; 
import android.widget.Toast; 

import com.google.android.gms.common.ConnectionResult; 
import com.google.android.gms.common.GooglePlayServicesUtil; 
import com.google.android.gms.common.api.GoogleApiClient; 
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks; 
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener; 
import com.google.android.gms.location.LocationListener; 
import com.google.android.gms.location.LocationRequest; 
import com.google.android.gms.location.LocationServices; 


public class TestActivity extends Activity implements ConnectionCallbacks, 
     OnConnectionFailedListener, LocationListener { 

    // LogCat tag 
    // private static final String TAG = TestActivity.class.getSimpleName(); 

    private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000; 


    // Google client to interact with Google API 
    private GoogleApiClient mGoogleApiClient; 

    private Location mLastLocation = LocationServices.FusedLocationApi 
      .getLastLocation(mGoogleApiClient); 

    // boolean flag to toggle periodic location updates 
    private boolean mRequestingLocationUpdates = false; 

    private LocationRequest mLocationRequest; 

    // Location updates intervals in sec 
    private static int UPDATE_INTERVAL = 10000; // 10 sec 
    private static int FATEST_INTERVAL = 5000; // 5 sec 
    private static int DISPLACEMENT = 10; // 10 meters 

    // UI elements 
    private TextView lblLocation; 
    private Button btnShowLocation, btnStartLocationUpdates; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     lblLocation = (TextView) findViewById(R.id.lblLocation); 
     btnShowLocation = (Button) findViewById(R.id.btnShowLocation); 
     btnStartLocationUpdates = (Button) findViewById(R.id.btnLocationUpdates); 

     // First we need to check availability of play services 
     if (checkPlayServices()) { 

      // Building the GoogleApi client 
      buildGoogleApiClient(); 

      createLocationRequest(); 
     } 

     // Show location button click listener 
     btnShowLocation.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 

       displayLocation(); 
      } 
     }); 

     // Toggling the periodic location updates 
     btnStartLocationUpdates.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       togglePeriodicLocationUpdates(); 
      } 
     }); 

    } 

    @Override 
    protected void onStart() { 
     super.onStart(); 
     if (mGoogleApiClient != null) { 
      mGoogleApiClient.connect(); 
     } 
    } 

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

     checkPlayServices(); 

     // Resuming the periodic location updates 
     if (mGoogleApiClient.isConnected() && mRequestingLocationUpdates) { 
      startLocationUpdates(); 
     } 
    } 

    @Override 
    protected void onStop() { 
     super.onStop(); 
     if (mGoogleApiClient.isConnected()) { 
      mGoogleApiClient.disconnect(); 
     } 
    } 

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

    /** 
    * Method to display the location on UI 
    * */ 

    private void displayLocation() { 

     if (Build.VERSION.SDK_INT > 22) { 

      if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 

       return; 
      } 

     } 
     mLastLocation = LocationServices.FusedLocationApi 
       .getLastLocation(mGoogleApiClient); 

     if (mLastLocation != null) { 
      double latitude = mLastLocation.getLatitude(); 
      double longitude = mLastLocation.getLongitude(); 

      lblLocation.setText(latitude + ", " + longitude); 

     } else { 

      lblLocation 
        .setText("(Couldn't get the location. Make sure location is enabled on the device)"); 
     } 
    } 

    /** 
    * Method to toggle periodic location updates 
    * */ 
    private void togglePeriodicLocationUpdates() { 
     if (!mRequestingLocationUpdates) { 
      // Changing the button text 
      btnStartLocationUpdates 
        .setText(getString(R.string.btn_stop_location_updates)); 

      mRequestingLocationUpdates = true; 

      // Starting the location updates 
      startLocationUpdates(); 

      Log.d("TAG ", "Periodic location updates started!"); 

     } else { 
      // Changing the button text 
      btnStartLocationUpdates 
        .setText(getString(R.string.btn_start_location_updates)); 

      mRequestingLocationUpdates = false; 

      // Stopping the location updates 
      stopLocationUpdates(); 

      Log.d("TAG", "Periodic location updates stopped!"); 
     } 
    } 

    /** 
    * Creating google api client object 
    * */ 
    protected synchronized void buildGoogleApiClient() { 
     mGoogleApiClient = new GoogleApiClient.Builder(this) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .addApi(LocationServices.API).build(); 
    } 

    /** 
    * Creating location request object 
    * */ 
    protected void createLocationRequest() { 
     mLocationRequest = new LocationRequest(); 
     mLocationRequest.setInterval(UPDATE_INTERVAL); 
     mLocationRequest.setFastestInterval(FATEST_INTERVAL); 
     mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 
     mLocationRequest.setSmallestDisplacement(DISPLACEMENT); 
    } 

    /** 
    * Method to verify google play services on the device 
    * */ 
    private boolean checkPlayServices() { 
     int resultCode = GooglePlayServicesUtil 
       .isGooglePlayServicesAvailable(this); 
     if (resultCode != ConnectionResult.SUCCESS) { 
      if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) { 
       GooglePlayServicesUtil.getErrorDialog(resultCode, this, 
         PLAY_SERVICES_RESOLUTION_REQUEST).show(); 
      } else { 
       Toast.makeText(getApplicationContext(), 
         "This device is not supported.", Toast.LENGTH_LONG) 
         .show(); 
       finish(); 
      } 
      return false; 
     } 
     return true; 
    } 

    /** 
    * Starting the location updates 
    * */ 
    protected void startLocationUpdates() { 

     if (Build.VERSION.SDK_INT > 22) { 

      if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 

       return; 
      } 

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

    } 

    /** 
    * Stopping location updates 
    */ 
    protected void stopLocationUpdates() { 
     LocationServices.FusedLocationApi.removeLocationUpdates(
       mGoogleApiClient, this); 
    } 

    /** 
    * Google api callback methods 
    */ 
    @Override 
    public void onConnectionFailed(ConnectionResult result) { 
     Log.i("TAG", "Connection failed: ConnectionResult.getErrorCode() = " 
       + result.getErrorCode()); 
    } 

    @Override 
    public void onConnected(Bundle arg0) { 

     // Once connected with google api, get the location 
     displayLocation(); 

     if (mRequestingLocationUpdates) { 
      startLocationUpdates(); 
     } 
    } 

    @Override 
    public void onConnectionSuspended(int arg0) { 
     mGoogleApiClient.connect(); 
    } 

    @Override 
    public void onLocationChanged(Location location) { 
     // Assign the new location 
     mLastLocation = location; 

     Toast.makeText(getApplicationContext(), "Location changed!", 
       Toast.LENGTH_SHORT).show(); 

     // Displaying the new location on UI 
     displayLocation(); 
    } 

} 

但來自Logcat我有這個錯誤,這對我來說沒有意義,因爲我在現有代碼的任何操作之前調用buildGoogleApiClient();。請參閱我的logcat輸出:

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.bourne.location/com.example.bourne.location.TestActivity}: java.lang.IllegalArgumentException: GoogleApiClient parameter is required. 
      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2264) 
      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390) 
      at android.app.ActivityThread.access$800(ActivityThread.java:151) 
      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321) 
      at android.os.Handler.dispatchMessage(Handler.java:110) 
      at android.os.Looper.loop(Looper.java:193) 
      at android.app.ActivityThread.main(ActivityThread.java:5299) 
      at java.lang.reflect.Method.invokeNative(Native Method) 
      at java.lang.reflect.Method.invoke(Method.java:515) 

回答

2

看起來像您使用的是它被初始化mGoogleApiClient之前。 的

private Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); 

初始化如果您對onCreate初始化mGoogleApiClient後進行。

因此改變

private Location mLastLocation; 

,並在您onCreatebuildGoogleApiClient();

0

我也得到了同樣的問題添加

mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); 

。但它得到了通過做這些以下步驟解決:

  1. 添加在Andriod的清單文件中的下列元數據標籤,注意GOOGLE_PLAY_SERVICES_VERSION給出的8487000

    <activity android:name=".MainActivity" android:label="@string/app_name" > <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version"/> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity>

  2. 在應用價值級的build.gradle中添加以下行的依賴性:

    compile 'com.google.android.gms:play-services-location:8.4.0'

+0

沒有。我已經添加了這個,但以前的解決方案爲我工作。這實際上是有道理的,爲什麼它以前沒有工作。 –

相關問題