2015-10-24 2 views
2

Я хочу реализовать автозаполнение сайта google API в android. Для этого мне нужно создать объект GoogleApiClient. Я использовал следующий код для этого ...Ошибка создания объекта GoogleApiClient, дает java.lang.IllegalStateException: уже управляет GoogleApiClient с идентификатором 0

private GoogleApiClient mGoogleApiClient; 

mGoogleApiClient = new GoogleApiClient.Builder(getActivity()) 
       .addApi(Drive.API) 
       .addScope(Drive.SCOPE_FILE) 
       .enableAutoManage(getActivity(), 0 /* clientId */, this) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .build(); 

Но когда начинается фрагмент, он бросает следующее исключение и приложение разбилось.

java.lang.IllegalStateException: Уже управление GoogleApiClient с идентификатором 0

Примечание: это выполняется в ФРАГМЕНТ.

Ниже манифеста конфигурационный файл ..

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 
    <uses-permission android:name="android.permission.INTERNET" /> 
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> 
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" /> 
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 
    <uses-permission android:name="com.example.permission.MAPS_RECEIVE"/> 

    <application 
     android:allowBackup="true" 
     android:icon="@drawable/ic_launcher" 
     android:label="@string/app_name" 
     android:theme="@style/AppTheme" 
     android:name="com.example.bluehorsesoftkol.ekplatevendor.Utils.EkPlateVendorApplication"> 


     <activity 
      android:name="com.example.bluehorsesoftkol.ekplatevendor.activity.registration.ActivitySplashScreen" 
      android:label="@string/app_name" 
      android:screenOrientation="landscape"> 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 
       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 
     <activity 
      android:name="com.example.bluehorsesoftkol.ekplatevendor.activity.registration.ActivityLogin" 
      android:screenOrientation="landscape"> 
     </activity> 
     <activity 
      android:name=".activity.vendor.ActivityHome" 
      android:screenOrientation="landscape"> 
     </activity> 
     <activity   android:name="com.example.bluehorsesoftkol.ekplatevendor.activity.vendor.ActivityAddVendor" 
      android:screenOrientation="landscape"> 
     </activity> 
     <activity 
      android:name=".activity.vendor.CustomGalleryActivity" 
      android:screenOrientation="landscape"> 
      <intent-filter> 
       <action android:name="ekplatevendor.ACTION_PICK" /> 
       <action android:name="ekplatevendor.ACTION_MULTIPLE_PICK" /> 

       <category android:name="android.intent.category.DEFAULT" /> 
      </intent-filter> 
     </activity> 

     <uses-feature 
      android:glEsVersion="0x00020000" 
      android:required="true"/> 

     <meta-data 
      android:name="com.google.android.geo.API_KEY" 
      android:value="@string/TEST_API_KEY"/> 

    </application> 

Так, пожалуйста, помогите решить эту проблему ..

Спасибо.

ответ

12

попробовать это в вашем коде

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

@Override 
public void onStop() { 
    super.onStop(); 
    if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) { 
     mGoogleApiClient.stopAutoManage((Activity) context); 
     mGoogleApiClient.disconnect(); 
    } 
} 

Примечание: от playstore версии 10 вы не должны использовать

mGoogleApiClient.stopAutoManage((Activity) context);

, как это будет позаботилась библиотекой это сам.

0

Это, как я сделал это для моего фрагмента:

Код для фрагмента:

private synchronized void buildGoogleApiClient() { 
    mGoogleApiClient = new GoogleApiClient.Builder(getActivity()) 
      .enableAutoManage(getActivity(), this) 
      .addConnectionCallbacks(this) 
      .addApi(LocationServices.API) 
      .build(); 
    createLocaitonRequest(); 
} 

private void createLocaitonRequest() { 
    mLocationRequest = new LocationRequest(); 
    mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS); 
    mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS); 
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 
} 

OnStart для фрагмента:

@Override 
public void onStart() { 
    super.onStart(); 
    mGoogleApiClient.connect(); 
} 

OnDestroy для фрагмента:

@Override 
public void onDestroy() { 
    super.onDestroy(); 
    mGoogleApiClient.stopAutoManage(getActivity()); 
    mGoogleApiClient.disconnect(); 
} 

Я бегу buildGoogleApiClient() метод в OnCreate()

Затем я использую MapView в моем XML для моего фрагмента следующим образом:

<com.google.android.gms.maps.MapView 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:id="@+id/map" /> 

Тогда в моем фрагменте, когда onCreateView я следующее:

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
    mView = inflater.inflate(R.layout.fragment_maps, container, false); 
    setRetainInstance(true); 
    setupMapsFragment(mView); 

    mMapView = (MapView) mView.findViewById(R.id.map); 
    if (mMapView != null) { 
     mMapView.onCreate(null); 
     mMapView.onResume(); 
     mMapView.getMapAsync(this); 
    } 

    return mView; 
} 

Если навигация выполнена с помощью навигатора, я столкнулся с вашей проблемой, когда загрузил фрагмент а затем снова нажал на пункт меню навигации, а затем он разбился так, чтобы решить, что я сделал это:

if (id == R.id.nav_map) { 

     if(checkMapsFragment == true){ 
      Toast.makeText(this,"map is already loaded",Toast.LENGTH_LONG).show(); 
     } 
     if(checkMapsFragment == false){ 
      fragment = new MapsFragment(); 
      checkMapsFragment = true; 
     } 
Смежные вопросы