2017-01-28 3 views
1

Я новичок в разработке Android, и я пытаюсь настроить геозонность, которая использует ожидающее намерения уведомить пользователя, что они вошли в геозонность, и выиграл значок. Я использую Службы Google Play Games для создания значков/достижений. Я хочу сделать уведомление кликабельным, чтобы оно дошло до вашей страницы достижений. Это мой IntentService:Подключиться к GoogleApiClient от IntentService

public class GeofenceService extends IntentService { 
private NotificationManager mNotificationManager; 
public static final String TAG = "GeofenceService"; 
private GoogleApiClient mGoogleApiClient; 

public GeofenceService() { 
    super(TAG); 
} 

@Override 
protected void onHandleIntent(Intent intent) { 
    GeofencingEvent event = GeofencingEvent.fromIntent(intent); 

    mGoogleApiClient = new GoogleApiClient.Builder(this) 
      .addApi(Games.API) 
      .addScope(Games.SCOPE_GAMES) 
      .build(); 
    mGoogleApiClient.connect(); 

    if (event.hasError()) { 
     //TODO handle error 
    } else { 
     int transition = event.getGeofenceTransition(); 
     List<Geofence> geofences = event.getTriggeringGeofences(); 
     Geofence geofence = geofences.get(0); 
     String requestId = geofence.getRequestId(); 

     if (transition == Geofence.GEOFENCE_TRANSITION_ENTER) { 
      Log.d(TAG, "onHandleIntent: Entering geofence - " + requestId); 

      if (mGoogleApiClient.isConnected()){ 
       sendNotification("+ 100"); 
      } 

     } else if (transition == Geofence.GEOFENCE_TRANSITION_EXIT) { 
      Log.d(TAG, "onHandleIntent: Exiting Geofence - " + requestId); 
     } 
    } 
} 


private String getTransitionString(int transitionType) { 
    switch (transitionType) { 
     case Geofence.GEOFENCE_TRANSITION_ENTER: 
      return getString(R.string.geofence_transition_entered); 
     case Geofence.GEOFENCE_TRANSITION_EXIT: 
      return getString(R.string.geofence_transition_exited); 
     default: 
      return getString(R.string.unknown_geofence_transition); 
    } 
} 

private void sendNotification(String details){ 
    mNotificationManager = (NotificationManager) 
      this.getSystemService(Context.NOTIFICATION_SERVICE); 

    Intent gamesIntent = Games.Achievements.getAchievementsIntent(mGoogleApiClient); 
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, 
      gamesIntent, 0); 


    NotificationCompat.Builder mBuilder = 
      new NotificationCompat.Builder(this) 
        .setContentTitle("You got a badge") 
        .setStyle(new NotificationCompat.BigTextStyle() 
          .bigText(details)) 
        .setContentText(details) 
        .setSmallIcon(R.drawable.tour); 

    mBuilder.setContentIntent(contentIntent); 
    mNotificationManager.notify(1, mBuilder.build()); 
} 

}

Этот код дает мне следующее сообщение об ошибке и не может подключиться к GoogleApiClient:

E/PopUpManager: Нет вид содержимого полезной для отображения всплывающих окон , Всплывающие окна не будут отображаться в ответ на вызовы этого клиента. Используйте setViewForPopups(), чтобы настроить просмотр содержимого.

Как подключиться к GoogleApiClient из ожидающего намерения или как можно сделать кликабельным, чтобы он застал меня в целях достижения целей Игр в Google Play Games?

ответ

0

Я понял проблему. Я не давал экземпляру GoogleApiClient достаточно времени для подключения. Таким образом, после построения GoogleApiClient и вызова метода Connect(), я добавил эту строку:

ConnectionResult connectionResult = mGoogleApiClient.blockingConnect(30, TimeUnit.SECONDS); 

Это решило его для меня. Надеюсь, это поможет кому угодно!

+0

Возможно, было бы лучше слушать GoogleApiClient.ConnectionCallbacks. Вы получите уведомление, когда соединение будет установлено. – Lancelot

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