地理栅栏没有触发 [英] Geofence not triggering

查看:145
本文介绍了地理栅栏没有触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图实施地理栅栏我的应用程序,问题是,当我在我所标示的地方,没有触发。

I'm trying to implement Geofence on my APP and the problem is that is not triggering when I'm on the place that I've marked.

这是我做的是我设置了天气预报&放的东西; 经度地点选择器

The thing that I do is I set the Latitude & Longitude from a Place Picker.

是我得到的数值都很好,因为我把它放在 谷歌图 和地点是正确的,因为我读过很多答案,人们从纬度设置错误值/长的。

我有两个类: GeofenceSingleton.class GeofenceTransitionsIntentService

GeofenceSingleton.class 是这样的:

public class GeofenceSingleton implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, ResultCallback<Status> {

private GoogleApiClient googleApiClient;
private static GeofenceSingleton _singleInstance;
private static Context appContext;
private static final String ERR_MSG = "Application Context is not set!! " +
        "Please call GeofenceSngleton.init() with proper application context";
private PendingIntent mGeofencePendingIntent;
private static ArrayList<Geofence> mGeofenceList;


private GeofenceSingleton() {
    if (appContext == null)
        throw new IllegalStateException(ERR_MSG);

    this.googleApiClient = new GoogleApiClient.Builder(this.appContext)
            .addApi(LocationServices.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();
    this.googleApiClient.connect();
    mGeofenceList = new ArrayList<Geofence>();
}

/**
 * @param applicationContext
 */
public static void init(Context applicationContext) {
    appContext = applicationContext;
}

public static GeofenceSingleton getInstance() {
    if (_singleInstance == null)
        synchronized (GeofenceSingleton.class) {
            if (_singleInstance == null)
                _singleInstance = new GeofenceSingleton();
        }
    return _singleInstance;
}

@Override
public void onConnected(Bundle bundle) {

}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

}

public void addGeofence(Location location, String uid) {
    mGeofenceList.add(new Geofence.Builder()
            .setRequestId(uid)
            .setCircularRegion(
                    location.getLatitude(),
                    location.getLongitude(),
                    500
            )
            .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER)
            .setExpirationDuration(1000000)
            .build());
}

private GeofencingRequest getGeofencingRequest() {
    GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
    builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);
    builder.addGeofences(mGeofenceList);
    return builder.build();
}

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

public void startGeofencing() {
    if (!googleApiClient.isConnected()) {
        Toast.makeText(appContext, "API client not connected", Toast.LENGTH_SHORT).show();
        return;
    }

    LocationServices.GeofencingApi.addGeofences(
            googleApiClient,
     // 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().
    Toast.makeText(appContext,"Geofencing started", Toast.LENGTH_LONG).show();
}



public void removeGeofence(){
    LocationServices.GeofencingApi.removeGeofences(
            googleApiClient,
// This is the same pending intent that was used in addGeofences().
            getGeofencePendingIntent()
    );
}

@Override
public void onResult(Status status) {
    if (status.isSuccess()) {
// Update state and save in shared preferences.

        Toast.makeText(
                appContext,
                "YO",
                Toast.LENGTH_SHORT
        ).show();
    } else {
        Toast.makeText(
                appContext,
                "NOO",
                Toast.LENGTH_SHORT
        ).show();
    }
}
}

GeofenceTransitionsIntentService

public class GeofenceTransitionsIntentService extends IntentService {

private static final String TAG = "Geofence-Service";
private Handler handler;
SharedPreferences sp;
SharedPreferences.Editor editor;
String EmailName, MessageEmail;
Context mContext;
Boolean EmailSent = false;

public GeofenceTransitionsIntentService() {
    super(TAG);
}

@Override
public void onCreate() {
    super.onCreate();
    this.mContext = this;
    sp = PreferenceManager.getDefaultSharedPreferences(this);
    handler = new Handler();
}

@Override
protected void onHandleIntent(Intent intent) {

    final GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
    if (geofencingEvent.hasError()) {
        Log.e(TAG, "Error in geofencing event");
        return;
    }

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

      // Test that the reported transition was of interest.
    if (geofenceTransition == 1) {

        handler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), "Entered", Toast.LENGTH_SHORT).show();
                sendNotification();
            }
        });
        Log.i(TAG, "Entered");


    }

    else {
        // Log the error.
        handler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), "Sorry you are out", Toast.LENGTH_SHORT).show();
            }
        });
        Log.e(TAG, String.valueOf(geofenceTransition));
    }

}

private void sendNotification() {
    Toast.makeText(GeofenceTransitionsIntentService.this, "HEEEEEEEY I'M IN", Toast.LENGTH_SHORT).show();



}

在我的 MainActivity 我有这样的:

GeofenceSingleton.init(this); //If I don't call this the class doesn't work
this.geofenceSingleton = GeofenceSingleton.getInstance();

然后,我建立一个地理栅栏如下:

Location geofence = new Location("");
geofence.setLatitude(Double.parseDouble(latitude));
geofence.setLongitude(Double.parseDouble(longitude));
geofenceSingleton.addGeofence(geofence, GeofenceKey);
geofenceSingleton.startGeofencing();

注意

我添加&LT;使用-权限的Andr​​oid:名称=android.permission.ACCESS_FINE_LOCATION/&GT; 我的的manifest.xml

我声明了服务&LT;服务机器人:名称=。GeofenceTransitionsIntentService/&GT;

和我说这行我的 build.gradle 编译com.google.android.gms:玩-服务:7.8.0

那只能说明 Toast.makeText(appContext,YO,Toast.LENGTH_SHORT).show(); 这是因为状态是成功的,也显示了 Toast.makeText(appContext,地理围栏开始,Toast.LENGTH_LONG).show(); 意味着它开始

It only shows Toast.makeText(appContext,"YO",Toast.LENGTH_SHORT).show(); that's because status is success, and also shows the Toast.makeText(appContext,"Geofencing started", Toast.LENGTH_LONG).show(); means that it's started.

为什么我的 IntentService 从不叫什么名字?

Why my IntentService is never called?

我测试了它当头我的家,因为纬度 / 长,我就应该被触发,是不是?

I tested it putting a Lat/Long of my home and since I'm on it should be triggered, isn't it?

推荐答案

它永远都不会工作,因为你正在做的事情是

It will never work because what you are doing is

Intent intent = new Intent(appContext, GeofenceSingleton.class);

传递意图GeofenceSingleton?

passing intent to GeofenceSingleton ?

您需要做的是

Intent intent = new Intent(appContext, GeofenceTransitionsIntentService.class);

这篇关于地理栅栏没有触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆