Android LocationServices.GeofencingApi 示例用法

Posted

技术标签:

【中文标题】Android LocationServices.GeofencingApi 示例用法【英文标题】:Android LocationServices.GeofencingApi example usage 【发布时间】:2014-12-25 08:39:27 【问题描述】:

有人知道使用 LocationServices.GeofencingApi 的示例吗? 我发现的所有 android 地理围栏示例都使用了已弃用的 LocationClient 类。 据我所知,LocationServices 类是可以使用的类,但似乎没有任何关于如何使用它的工作示例。

我找到的最接近的是this 发布突出显示位置更新请求

更新:我找到的最接近的答案是 this git example 项目 - 但它仍然使用已弃用的 LocationClient 来触发栅栏。

【问题讨论】:

你试过在来源:d.android.com在培训部分文章标题的首字母缩写是CaMG 具体链接在这里 developer.android.com/training/location/geofencing.html 使用已弃用的 LocationClient 类 - 似乎他们还没有更新文档 【参考方案1】:

我刚刚将我的代码迁移到了新的 API。这是一个工作示例:

GitHub 上基于此答案的工作项目:https://github.com/androidfu/GeofenceExample

此帮助程序类使用 API 注册地理围栏。我使用回调接口与调用活动/片段进行通信。您可以构建适合您需求的回调。

public class GeofencingRegisterer implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener 
    private Context mContext;
    private GoogleApiClient mGoogleApiClient;
    private List<Geofence> geofencesToAdd;
    private PendingIntent mGeofencePendingIntent;

    private GeofencingRegistererCallbacks mCallback;

    public final String TAG = this.getClass().getName();

    public GeofencingRegisterer(Context context)
        mContext =context;
    

    public void setGeofencingCallback(GeofencingRegistererCallbacks callback)
        mCallback = callback;
    

    public void registerGeofences(List<Geofence> geofences)
        geofencesToAdd = geofences;

        mGoogleApiClient = new GoogleApiClient.Builder(mContext)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
        mGoogleApiClient.connect();
    


    @Override
    public void onConnected(Bundle bundle) 
        if(mCallback != null)
            mCallback.onApiClientConnected();
        

        mGeofencePendingIntent = createRequestPendingIntent();
        PendingResult<Status> result = LocationServices.GeofencingApi.addGeofences(mGoogleApiClient, geofencesToAdd, mGeofencePendingIntent);
        result.setResultCallback(new ResultCallback<Status>() 
            @Override
            public void onResult(Status status) 
                if (status.isSuccess()) 
                    // Successfully registered
                    if(mCallback != null)
                        mCallback.onGeofencesRegisteredSuccessful();
                    
                 else if (status.hasResolution()) 
                    // Google provides a way to fix the issue
                    /*
                    status.startResolutionForResult(
                            mContext,     // your current activity used to receive the result
                            RESULT_CODE); // the result code you'll look for in your
                    // onActivityResult method to retry registering
                    */
                 else 
                    // No recovery. Weep softly or inform the user.
                    Log.e(TAG, "Registering failed: " + status.getStatusMessage());
                
            
        );
    

    @Override
    public void onConnectionSuspended(int i) 
        if(mCallback != null)
            mCallback.onApiClientSuspended();
        

        Log.e(TAG, "onConnectionSuspended: " + i);
    

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) 
        if(mCallback != null)
            mCallback.onApiClientConnectionFailed(connectionResult);
        

        Log.e(TAG, "onConnectionFailed: " + connectionResult.getErrorCode());
    



    /**
     * Returns the current PendingIntent to the caller.
     *
     * @return The PendingIntent used to create the current set of geofences
     */
    public PendingIntent getRequestPendingIntent() 
        return createRequestPendingIntent();
    

    /**
     * Get a PendingIntent to send with the request to add Geofences. Location
     * Services issues the Intent inside this PendingIntent whenever a geofence
     * transition occurs for the current list of geofences.
     *
     * @return A PendingIntent for the IntentService that handles geofence
     * transitions.
     */
    private PendingIntent createRequestPendingIntent() 
        if (mGeofencePendingIntent != null) 
            return mGeofencePendingIntent;
         else 
            Intent intent = new Intent(mContext, GeofencingReceiver.class);
            return PendingIntent.getService(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        
    

此类是您的地理围栏转换接收器的基类。

public abstract class ReceiveGeofenceTransitionIntentService extends IntentService 

    /**
     * Sets an identifier for this class' background thread
     */
    public ReceiveGeofenceTransitionIntentService() 
        super("ReceiveGeofenceTransitionIntentService");
    

    @Override
    protected void onHandleIntent(Intent intent) 

        GeofencingEvent event = GeofencingEvent.fromIntent(intent);
        if(event != null)

            if(event.hasError())
                onError(event.getErrorCode());
             else 
                int transition = event.getGeofenceTransition();
                if(transition == Geofence.GEOFENCE_TRANSITION_ENTER || transition == Geofence.GEOFENCE_TRANSITION_DWELL || transition == Geofence.GEOFENCE_TRANSITION_EXIT)
                    String[] geofenceIds = new String[event.getTriggeringGeofences().size()];
                    for (int index = 0; index < event.getTriggeringGeofences().size(); index++) 
                        geofenceIds[index] = event.getTriggeringGeofences().get(index).getRequestId();
                    

                    if (transition == Geofence.GEOFENCE_TRANSITION_ENTER || transition == Geofence.GEOFENCE_TRANSITION_DWELL) 
                        onEnteredGeofences(geofenceIds);
                     else if (transition == Geofence.GEOFENCE_TRANSITION_EXIT) 
                        onExitedGeofences(geofenceIds);
                    
                
            

        
    

    protected abstract void onEnteredGeofences(String[] geofenceIds);

    protected abstract void onExitedGeofences(String[] geofenceIds);

    protected abstract void onError(int errorCode);

这个类实现了抽象类并完成了地理围栏转换的所有处理

public class GeofencingReceiver extends ReceiveGeofenceTransitionIntentService 

    @Override
    protected void onEnteredGeofences(String[] geofenceIds) 
        Log.d(GeofencingReceiver.class.getName(), "onEnter");
    

    @Override
    protected void onExitedGeofences(String[] geofenceIds) 
        Log.d(GeofencingReceiver.class.getName(), "onExit");
    

    @Override
    protected void onError(int errorCode) 
        Log.e(GeofencingReceiver.class.getName(), "Error: " + i);
    

并在您的清单中添加:

<service
        android:name="**xxxxxxx**.GeofencingReceiver"
        android:exported="true"
        android:label="@string/app_name" >
</service>

回调接口

public interface GeofencingRegistererCallbacks 
    public void onApiClientConnected();
    public void onApiClientSuspended();
    public void onApiClientConnectionFailed(ConnectionResult connectionResult);

    public void onGeofencesRegisteredSuccessful();

【讨论】:

您也可以提供您的回电吗?我是android开发的新手,如果你能分享你的代码会很好:) thx 根据文档,LocationServices.GeofencingApi.addGeofences(GoogleApiClient, List&lt;Geofence&gt;, PendingIntent); 方法也已弃用。改用LocationServices.GeofencingApi.addGeofences(GoogleApiClient, GeofencingRequest, PendingIntent);,首先创建GeofencingRequestGeofencingRequest geofenceRequest = new GeofencingRequest.Builder().addGeofences(mGeofencesToAdd).build(); 很好,他们再次更改了文档.. 上周它没有被弃用 为什么要导出 GeofencingReceiver 服务? 我无法解释这一点,我在地理围栏 API 的其他文档中找到了这一点。可能是因为该服务是由google play services框架调用的。

以上是关于Android LocationServices.GeofencingApi 示例用法的主要内容,如果未能解决你的问题,请参考以下文章

我不能在 android 中使用 locationServices.getLastLocation

Android LocationServices - 如何测试 onConnectionSuspended 回调

在 Android 后台服务中使用 LocationServices.FusedLocationApi.requestLocationUpdates...onLocationChanged 从未调用

android在使用`FusedLocationApi`时在`LocationServices.API`和`Auth.GOOGLE_SIGN_IN_API`之间发生冲突

Android - 未在 IntentService 中接收位置对象 - 使用 LocationServices FusedLocationApi requestLocationUpdates 使用未

在 android studio 中无法获取华为 Map Kit 的 com.huawei.hms.location.LocationServices