2015-03-27 7 views
0

Когда я запустил sample codes для android geofence, он работает хорошо. Однако для того, чтобы реализовать геозонность в моем собственном проекте, я попытался настроить его самостоятельно. Во-первых, я добавляю некоторые коды в файл build.gradle и файл манифеста, как сообщает documentation. Затем я получил ключ SHA1 своего приложения и добавлю его на страницу console.developers.google.com для создания ключа API. В конце я включил API Google Android Android API версии 2 и Google Play Android. Когда я запускаю код ниже, даже если Google Api Client создан, функция mGoogleApiClient.isConnecting() возвращает значение true, но функция mGoogleApiClient.isConnected() возвращает false.onConnected не отвечает на Android Geofence

Может ли кто-нибудь сказать мне, где я могу поступать неправильно?

public class MainActivity extends ActionBarActivity implements 
    GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, ResultCallback<Status> { 
protected ArrayList<Geofence> mGeofenceList; 
protected GoogleApiClient mGoogleApiClient; 
private PendingIntent mGeofencePendingIntent; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    buildGoogleApiClient(); 
    mGeofenceList = new ArrayList<Geofence>(); 

    mGeofenceList.add(new Geofence.Builder().setRequestId("ITU_Tekno_kent").setCircularRegion(41.107993, 29.032625, 1609).setExpirationDuration(100000).setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | 
      Geofence.GEOFENCE_TRANSITION_EXIT).build()); 
    mGoogleApiClient.connect(); 
    if (mGoogleApiClient.isConnecting()) { 
     Toast.makeText(this, "connecting", Toast.LENGTH_SHORT).show(); 

    } 
    if (!mGoogleApiClient.isConnected()) { 
     Toast.makeText(this, "not connected", Toast.LENGTH_SHORT).show(); 
     return; 
    } 

    try { 
     LocationServices.GeofencingApi.addGeofences(
       mGoogleApiClient, 
       // The GeofenceRequest object. 
       getGeofencingRequest(), 
       // A pending intent that that is reused when calling removeGeofences(). This 
       // pending intent is used to generate an intent when a matched geofence 
       // transition is observed. 
       getGeofencePendingIntent() 
     ).setResultCallback(this); // Result processed in onResult(). 
    } catch (SecurityException securityException) { 
     Log.i("catch","d"); 
     // logSecurityException(securityException); 
    } 
} 

private PendingIntent getGeofencePendingIntent() { 
    // Reuse the PendingIntent if we already have it. 
    if (mGeofencePendingIntent != null) { 
     return mGeofencePendingIntent; 
    } 
    Intent intent = new Intent(this, GeofenceTransitionsIntentService.class); 
    // We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when calling 
    // addGeofences() and removeGeofences(). 
    return PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); 
} 
private GeofencingRequest getGeofencingRequest() { 
    GeofencingRequest.Builder builder = new GeofencingRequest.Builder(); 

    // The INITIAL_TRIGGER_ENTER flag indicates that geofencing service should trigger a 
    // GEOFENCE_TRANSITION_ENTER notification when the geofence is added and if the device 
    // is already inside that geofence. 
    builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER); 

    // Add the geofences to be monitored by geofencing service. 
    builder.addGeofences(mGeofenceList); 

    // Return a GeofencingRequest. 
    return builder.build(); 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.menu_main, menu); 
    return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    // Handle action bar item clicks here. The action bar will 
    // automatically handle clicks on the Home/Up button, so long 
    // as you specify a parent activity in AndroidManifest.xml. 
    int id = item.getItemId(); 

    //noinspection SimplifiableIfStatement 
    if (id == R.id.action_settings) { 
     return true; 
    } 

    return super.onOptionsItemSelected(item); 
} 
protected synchronized void buildGoogleApiClient() { 
    mGoogleApiClient = new GoogleApiClient.Builder(this) 
      .addConnectionCallbacks(this) 
      .addOnConnectionFailedListener(this) 
      .addApi(LocationServices.API) 
      .build() ; 
} 
protected void onStart() { 
    super.onStart(); 
    mGoogleApiClient.connect(); 
} 
@Override 
public void onConnected(Bundle bundle) { 

} 

@Override 
public void onConnectionSuspended(int i) { 

} 

@Override 
public void onConnectionFailed(ConnectionResult connectionResult) { 

} 

@Override 
public void onResult(Status status) { 

} 

}

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
package="hangaar.geofencingtest2" > 
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> 
<application 
    android:allowBackup="true" 
    android:icon="@drawable/ic_launcher" 
    android:label="@string/app_name" 
    android:theme="@style/AppTheme" > 
    <activity 
     android:name=".MainActivity" 
     android:label="@string/app_name" > 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 

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

    <service android:name=".GeofenceTransitionsIntentService"/> 
    <meta-data android:name="com.google.android.gms.version" 
     android:value="@integer/google_play_services_version" /> 
</application> 

+0

Можете ли вы опубликовать код в манифесте? – bwegs

ответ

0

соединение, как большая часть сетевых процессов является асинхронным и ваш mGoogleApiClient.connect() не происходит сразу. Вы должны использовать прослушиватель, чтобы узнать, когда подключен GoogleApiClient. Как я вижу, вы добавили интерфейсы ConnectionCallbacks и OnConnectionFailedListener, но не использовали их по мере необходимости. Ваш код, который должен выполняться после того, как соединение происходит, должны быть реализованы в методе ConnectionCallbacks.onConnected (Bundle), который переопределен в вашей деятельности, как показано ниже:

@Override 
public void onConnected(Bundle bundle) { 
    Toast.makeText(this, "Connected!", Toast.LENGTH_SHORT).show(); 
} 

Кроме того, чтобы активировать Geofencing вам нужно вызов LocationServices.GeofencingApi.addGeofences (GoogleApiClient , GeofencingRequest, PendingIntent) после подключения GoogleApiclient, то есть в onConnected (Bundle). И не забудьте установить ResultCallback для результата Geofencing (LocationServices.GeofencingApi.addGeofences (...). SetResultCallback (resultCallback) - интерфейс прослушивателя тоже).

Смежные вопросы