大家好我正在我的Android应用程序中实现地理围栏功能来发送吐司通知。事情就是当我在里面(我正在制作围栏)我创建的围栏然后意图被解雇但当我尝试开火再次通过重新输入位置意图而不是在这里触发的事件是我的代码
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 :(得分:0)
我看到您的代码看起来与您从Google开发者页面中提取的样本完全一样,并且是很多人最初使用的代码。我自己也遇到了准确性方面的问题,也缺少了围栏过渡。我读到手动添加先前位置请求包(LocationManager)的实例并在高更新模式下明确指定GPS作为提供者可以使其更准确。这就是我现在的工作方式。你也可以试着让你的栅栏的半径更宽,这样你就会考虑到最小的Wi-Fi精度,据说这个精度大约是50米而不考虑漂移。