0

поэтому у меня этот геозонс установлен. И я могу отображать уведомление, когда кто-то входит или выходит из геолокации, но я не могу представить сообщение Toast. Я бы подумал, что вы поместите сообщение Toast в метод onHandleIntent(), но это, похоже, не работает. Надеюсь, вы, ребята, можете дать некоторое представление.Как отобразить сообщение о тосте, когда кто-то входит в геофенсион?

Вот мой класс.

public class GeofenceTransitionsIntentService extends IntentService { 
    protected static final String TAG = "geofence-transitions-service"; 

    public GeofenceTransitionsIntentService() { 
     // Use the TAG to name the worker thread. 
     super(TAG); 
    } 

    @Override 
    public void onCreate() 
    { 
     super.onCreate(); 
    } 

    @Override 
    protected void onHandleIntent(Intent intent) { 
     GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent); 
     if (geofencingEvent.hasError()) { 
      String errorMessage = GeofenceErrorMessages.getErrorString(this, 
        geofencingEvent.getErrorCode()); 
      Log.e(TAG, errorMessage); 
      return; 
     } 

     // Get the transition type. 
     int geofenceTransition = geofencingEvent.getGeofenceTransition(); 

     // Test that the reported transition was of interest. 
     if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER || 
       geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) { 

      // Get the geofences that were triggered. A single event can trigger multiple geofences. 
      List<Geofence> triggeringGeofences = geofencingEvent.getTriggeringGeofences(); 

      // Get the transition details as a String. 
      String geofenceTransitionDetails = getGeofenceTransitionDetails(
        this, 
        geofenceTransition, 
        triggeringGeofences 
      ); 

      // Send notification and log the transition details. 
      sendNotification(geofenceTransitionDetails); 
      Toast.makeText(getBaseContext(),"Entered my geoFence :D",Toast.LENGTH_SHORT).show(); 
      Log.i(TAG, geofenceTransitionDetails); 
     } else { 
      // Log the error. 
      Log.e(TAG, getString(R.string.geofence_transition_invalid_type, geofenceTransition)); 
     } 
    } 

    private String getGeofenceTransitionDetails(
      Context context, 
      int geofenceTransition, 
      List<Geofence> triggeringGeofences) { 

     String geofenceTransitionString = getTransitionString(geofenceTransition); 

     // Get the Ids of each geofence that was triggered. 
     ArrayList triggeringGeofencesIdsList = new ArrayList(); 
     for (Geofence geofence : triggeringGeofences) { 
      triggeringGeofencesIdsList.add(geofence.getRequestId()); 
     } 
     String triggeringGeofencesIdsString = TextUtils.join(", ", triggeringGeofencesIdsList); 

     return geofenceTransitionString + ": " + triggeringGeofencesIdsString; 
    } 

    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 notificationDetails) { 
     // Create an explicit content Intent that starts the main Activity. 
     Intent notificationIntent = new Intent(getApplicationContext(), Main.class); 

     // Construct a task stack. 
     TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); 

     // Add the main Activity to the task stack as the parent. 
     stackBuilder.addParentStack(Main.class); 

     // Push the content Intent onto the stack. 
     stackBuilder.addNextIntent(notificationIntent); 

     // Get a PendingIntent containing the entire back stack. 
     PendingIntent notificationPendingIntent = 
       stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); 

     // Get a notification builder that's compatible with platform versions >= 4 
     NotificationCompat.Builder builder = new NotificationCompat.Builder(this); 

     // Define the notification settings. 
     builder.setSmallIcon(R.drawable.ic_launcher) 
       // In a real app, you may want to use a library like Volley 
       // to decode the Bitmap. 
       .setLargeIcon(BitmapFactory.decodeResource(getResources(), 
         R.drawable.ic_launcher)) 
       .setColor(Color.RED) 
       .setContentTitle(notificationDetails) 
       .setContentText(getString(R.string.geofence_transition_notification_text)) 
       .setContentIntent(notificationPendingIntent); 

     // Dismiss notification once the user touches it. 
     builder.setAutoCancel(true); 

     // Get an instance of the Notification manager 
     NotificationManager mNotificationManager = 
       (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 

     // Issue the notification 
     mNotificationManager.notify(0, builder.build()); 
    } 

} 

В настоящее время я помещаю тост в инструкцию if в нижней части метода onHandleIntent(). Мой полный исходный код был непосредственно из руководства Google по геологизации: http://io2015codelabs.appspot.com/codelabs/geofences#1

ответ

1

Это IntentService, поэтому обратный вызов onHandleIntent выполняется в фоновом режиме.

Чтобы правильно отобразить его на экране, вам необходимо выполнить Toast на основном потоке пользовательского интерфейса.

Взгляните на этот ответ, чтобы увидеть, как получить доступ к основной поток от службы

Accessing UI thread handler from a service

+0

А я не знаю, что это был отдельный поток , Спасибо за совет, плохо попробуйте – TheQ

0

Попробуйте:

@Override 
protected void onHandleIntent(Intent intent) { 

    GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent); 
    if (geofencingEvent.hasError()) { 
     String errorMessage = GeofenceErrorMessages.getErrorString(this, 
       geofencingEvent.getErrorCode()); 
     Log.e(TAG, errorMessage); 
     return; 
    } 

    int geofenceTransition = geofencingEvent.getGeofenceTransition(); 


    if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER || 
      geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) { 

     // Get the geofences that were triggered. A single event can trigger multiple geofences. 
     List<Geofence> triggeringGeofences = geofencingEvent.getTriggeringGeofences(); 


     String geofenceTransitionDetails = getGeofenceTransitionDetails(
       this, 
       geofenceTransition, 
       triggeringGeofences 
     ); 

     // Showing toast for location transition 
     Handler handler = new Handler(Looper.getMainLooper()); 
     handler.post(new Runnable() { 

      @Override 
      public void run() { 
       Toast.makeText(context,geofenceTransitionDetails,Toast.LENGTH_SHORT).show(); 
      } 
     }); 


     Log.i(TAG, geofenceTransitionDetails); 
    } else { 
     // Log the error. 
     Log.e(TAG, getString(R.string.geofence_transition_invalid_type, geofenceTransition)); 
    } 
} 
Смежные вопросы