2016-04-25 6 views
0

Привет всем, я внедряю функцию geofencing в приложении для Android, чтобы отправлять уведомления о тостах. Дело в том, что когда я внутри (где я делаю забор), забор, который я создал, тогда увольнение увольняется, но когда я пытаюсь снова стрелять событие, повторный ввод намерения местоположения не стреляя вот мой кодGeofencing Intent Not Firing

protected override void OnHandleIntent (Intent intent) 
    { 
     Intent broadcastIntent = new Intent(); 


     var geofencingEvent = GeofencingEvent.FromIntent (intent); 
     if (geofencingEvent.HasError) { 
      var errorMessage = GeofenceErrorMessages.GetErrorString (this, geofencingEvent.ErrorCode); 
      Log.Error (TAG, errorMessage); 
      return; 
     } 

     int geofenceTransition = geofencingEvent.GeofenceTransition; 

     if (geofenceTransition == Geofence.GeofenceTransitionEnter || 
      geofenceTransition == Geofence.GeofenceTransitionExit) { 
       Toast.MakeText(this, "Service Started", ToastLength.Long).Show(); 

      IList<IGeofence> triggeringGeofences = geofencingEvent.TriggeringGeofences; 

      string geofenceTransitionDetails = GetGeofenceTransitionDetails (this, geofenceTransition, triggeringGeofences); 

      SendNotification (geofenceTransitionDetails); 
      Log.Info (TAG, geofenceTransitionDetails); 
     } else { 
      // Log the error. 
      Log.Error (TAG, GetString (Resource.String.geofence_transition_invalid_type, new [] { new Java.Lang.Integer (geofenceTransition) })); 
     } 
    } 

    string GetGeofenceTransitionDetails (Context context, int geofenceTransition, IList<IGeofence> triggeringGeofences) 
    { 
     string geofenceTransitionString = GetTransitionString (geofenceTransition); 

     var triggeringGeofencesIdsList = new List<string>(); 
     foreach (IGeofence geofence in triggeringGeofences) { 
      triggeringGeofencesIdsList.Add (geofence.RequestId); 
     } 
     var triggeringGeofencesIdsString = string.Join (", ", triggeringGeofencesIdsList); 

     return geofenceTransitionString + ": " + triggeringGeofencesIdsString; 
    } 

    void SendNotification (string notificationDetails) 
    { 
     var notificationIntent = new Intent (ApplicationContext, typeof(MainActivity)); 

     var stackBuilder = Android.Support.V4.App.TaskStackBuilder.Create (this); 
     stackBuilder.AddParentStack (Java.Lang.Class.FromType (typeof(MainActivity))); 
     stackBuilder.AddNextIntent (notificationIntent); 

     var notificationPendingIntent = stackBuilder.GetPendingIntent (0, (int)PendingIntentFlags.UpdateCurrent); 

     var builder = new NotificationCompat.Builder (this); 
     builder.SetSmallIcon (Resource.Drawable.icon) 
      .SetLargeIcon (BitmapFactory.DecodeResource (Resources, Resource.Drawable.icon)) 
      .SetColor (Color.Red) 
      .SetContentTitle (notificationDetails) 
      .SetContentText (GetString (Resource.String.geofence_transition_notification_text)) 
      .SetContentIntent (notificationPendingIntent); 

     builder.SetAutoCancel (true); 

     var mNotificationManager = (NotificationManager)GetSystemService (Context.NotificationService); 
     mNotificationManager.Notify (0, builder.Build()); 
    } 

    string GetTransitionString (int transitionType) 
    { 
     switch (transitionType) { 
     case Geofence.GeofenceTransitionEnter: 
      return GetString (Resource.String.geofence_transition_entered); 
     case Geofence.GeofenceTransitionExit: 
      return GetString (Resource.String.geofence_transition_exited); 
     default: 
      return GetString (Resource.String.unknown_geofence_transition); 
     } 
    } 

и моя основная деятельность

{ 
    protected const string TAG = "creating-and-monitoring-geofences"; 
    protected GoogleApiClient mGoogleApiClient; 
    protected IList<IGeofence> mGeofenceList; 
    bool mGeofencesAdded; 
    PendingIntent mGeofencePendingIntent; 
    ISharedPreferences mSharedPreferences; 
    Button mAddGeofencesButton; 
    Button mRemoveGeofencesButton; 

    protected override void OnCreate (Bundle savedInstanceState) 
    { 
     base.OnCreate (savedInstanceState); 
     SetContentView (Resource.Layout.main_activity); 

     mAddGeofencesButton = FindViewById<Button> (Resource.Id.add_geofences_button); 
     mRemoveGeofencesButton = FindViewById<Button> (Resource.Id.remove_geofences_button); 

     mAddGeofencesButton.Click += AddGeofencesButtonHandler; 
     mRemoveGeofencesButton.Click += RemoveGeofencesButtonHandler; 
     mGeofenceList = new List<IGeofence>(); 
     mGeofencePendingIntent = null; 

     mSharedPreferences = GetSharedPreferences (Constants.SHARED_PREFERENCES_NAME, 
      FileCreationMode.Private); 

     mGeofencesAdded = mSharedPreferences.GetBoolean (Constants.GEOFENCES_ADDED_KEY, false); 

     SetButtonsEnabledState(); 
     PopulateGeofenceList(); 
     BuildGoogleApiClient(); 
    } 

    protected void BuildGoogleApiClient() 
    { 
     mGoogleApiClient = new GoogleApiClient.Builder (this) 
      .AddConnectionCallbacks (this) 
      .AddOnConnectionFailedListener (this) 
      .AddApi (LocationServices.API) 
      .Build(); 
    } 
    private IntentFilter mIntentFilter; 

    protected override void OnResume() 
    { 
     base.OnResume(); 
     mGoogleApiClient.Connect(); 


    } 
    protected override void OnStart() 
    { 
     base.OnStart(); 
     mGoogleApiClient.Connect(); 
    } 

    protected override void OnStop() 
    { 
     base.OnStop(); 
    // mGoogleApiClient.Disconnect(); 
    } 

    public void OnConnected (Bundle connectionHint) 
    { 
     Log.Info (TAG, "Connected to GoogleApiClient"); 
    } 

    public void OnConnectionSuspended (int cause) 
    { 
     Log.Info (TAG, "Connection suspended"); 
    } 

    public void OnConnectionFailed (Android.Gms.Common.ConnectionResult result) 
    { 
     Log.Info (TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.ErrorCode); 
    } 

    GeofencingRequest GetGeofencingRequest() 
    { 
     var builder = new GeofencingRequest.Builder(); 
     builder.SetInitialTrigger (GeofencingRequest.InitialTriggerEnter); 
     builder.AddGeofences (mGeofenceList); 

     return builder.Build(); 
    } 

    public async void AddGeofencesButtonHandler (object sender, EventArgs e) 
    { 
     if (!mGoogleApiClient.IsConnected) { 
      Toast.MakeText (this, GetString (Resource.String.not_connected), ToastLength.Short).Show(); 
      return; 
     } 

     try { 
      var status = await LocationServices.GeofencingApi.AddGeofencesAsync (mGoogleApiClient, GetGeofencingRequest(), 
       GetGeofencePendingIntent()); 
      HandleResult (status); 
     } catch (SecurityException securityException) { 
      LogSecurityException(securityException); 
     } 
    } 

    public async void RemoveGeofencesButtonHandler (object sender, EventArgs e) 
    { 
     if (!mGoogleApiClient.IsConnected) { 
      Toast.MakeText (this, GetString(Resource.String.not_connected), ToastLength.Short).Show(); 
      return; 
     } 
     try { 
      var status = await LocationServices.GeofencingApi.RemoveGeofencesAsync (mGoogleApiClient, 
       GetGeofencePendingIntent()); 
      HandleResult (status); 
     } catch (SecurityException securityException) { 
      LogSecurityException (securityException); 
     } 
    } 

    void LogSecurityException (SecurityException securityException) 
    { 
     Log.Error (TAG, "Invalid location permission. " + 
      "You need to use ACCESS_FINE_LOCATION with geofences", securityException); 
    } 

    public void HandleResult (Statuses status) 
    { 
     if (status.IsSuccess) { 
      mGeofencesAdded = !mGeofencesAdded; 
      var editor = mSharedPreferences.Edit(); 
      editor.PutBoolean (Constants.GEOFENCES_ADDED_KEY, mGeofencesAdded); 
      editor.Commit(); 

      SetButtonsEnabledState(); 

      Toast.MakeText (
       this, 
       GetString (mGeofencesAdded ? Resource.String.geofences_added : 
        Resource.String.geofences_removed), 
       ToastLength.Short 
      ).Show(); 
     } else { 
      var errorMessage = GeofenceErrorMessages.GetErrorString (this, 
       status.StatusCode); 
      Log.Error (TAG, errorMessage); 
     } 
    } 

    PendingIntent GetGeofencePendingIntent() 
    { 
     if (mGeofencePendingIntent != null) { 
      return mGeofencePendingIntent; 
     } 
     //var intent = new Intent(this, typeof(Test)); 
     //SendBroadcast(intent); 
     //return PendingIntent.GetBroadcast(this, 0, intent, PendingIntentFlags.UpdateCurrent); 

     var intent = new Intent(this, typeof(GeofenceTransitionsIntentService)); 
     //SendBroadcast(intent); 
     return PendingIntent.GetService(this, 0, intent, PendingIntentFlags.UpdateCurrent); 

    } 

    public void PopulateGeofenceList() 
    { 
     foreach (var entry in Constants.BAY_AREA_LANDMARKS) { 
      mGeofenceList.Add (new GeofenceBuilder() 
       .SetRequestId (entry.Key) 
       .SetCircularRegion (
        entry.Value.Latitude, 
        entry.Value.Longitude, 
        Constants.GEOFENCE_RADIUS_IN_METERS 
       ) 
       .SetExpirationDuration (Constants.GEOFENCE_EXPIRATION_IN_MILLISECONDS) 
       .SetTransitionTypes (Geofence.GeofenceTransitionEnter | 
        Geofence.GeofenceTransitionExit) 
       .Build()); 
     } 
    } 

    void SetButtonsEnabledState() 
    { 
     if (mGeofencesAdded) { 
      mAddGeofencesButton.Enabled = false; 
      mRemoveGeofencesButton.Enabled = true; 
     } else { 
      mAddGeofencesButton.Enabled = true; 
      mRemoveGeofencesButton.Enabled = false; 
     } 
    } 
} 

}

также я пробовал сделать приемник вещания, но он не очень помог мне

+0

Как вы тестируете свой GeoFence. Если вы используете API Google, мне пришлось перенести свое текущее местоположение через провайдера ложных мест в и из забора в реалистичной манере для его стрельбы, поэтому прыжки со 100-километрового расстояния, а через секунду внутри забора не будут Огонь. Если бы я двигался с ходу или скоростью движения снаружи внутрь (и пусть он сидит внутри для нескольких звонков), тогда он срабатывает. –

+0

@MorrisonChang на самом деле я создал забор в 100 метрах от моего текущего местоположения, и я подошел к забору за 3 минуты, этого недостаточно? или должно быть больше? –

+0

@MorrisonChang есть ли надежный api для геообработки? вместо google api, который работает быстро? –

ответ

0

Я вижу, что ваш код выглядит точно так же, как образец, который вы вытаскиваете с страницы разработчика Google, и это тот, который во многих случаях используется чаще всего. У меня тоже были проблемы с точностью и отсутствием переходов забора с этим. Я прочитал, что вручную добавление экземпляра предыдущего пакета запроса местоположения (LocationManager) и явное указание GPS в качестве провайдера в режиме с высоким уровнем обновления может сделать его более точным. Вот как я работаю сейчас. Вы также можете попытаться расширить радиусы ваших ограждений, таким образом, вы учтете минимальную точность wi-fi, которая, как утверждается, составляет около 50 м, не учитывая дрейф.

+0

Я использовал широковещательный приемник вместо намерения службы, и мои результаты улучшились, и радиус, который я установил, составлял минимум 100 метров, так что также помог btw, я отправил его назад, спасибо за ответ –

+0

круто, что вы его тоже исправили ... продолжайте кодирование! :) –