【问题标题】:I want to make service which broadcast notification if I am in geo-fence or Not如果我在地理围栏中,我想提供广播通知的服务
【发布时间】:2017-07-19 13:12:53
【问题描述】:
    h.postDelayed(new Runnable(){
        public void run(){

这是射线投射算法检查当前用户位置是否在点内

            if (PolyUtil.containsLocation(latLngchangeloc, arrayPoints, true)==true) {
                //Intent intent=new Intent();
                //intent.setAction("MyBroadcast");
                //intent.putExtra("values","enter");
                //sendBroadcast(intent);
               // sendNotification("enter");
                //Toast.makeText(this, "enter", Toast.LENGTH_SHORT).show();
            } else {
                //Intent intent=new Intent();
                //intent.setAction("MyBroadcast");
                //intent.putExtra("values","leave");
               //sendBroadcast(intent);
               // sendNotification("leave");
                //Toast.makeText(this, "leave", Toast.LENGTH_SHORT).show();
                   }
            h.postDelayed(this, 3000);
        }
    }, delay);


}

这工作正常,正在检查地理围栏中的当前位置。 现在我想把它作为服务,所以当我进入那个地理围栏时它会广播消息。我正在为此制作定制围栏。

【问题讨论】:

    标签: android google-maps-android-api-2 android-geofence


    【解决方案1】:

    此代码适用于我的地理围栏,您也可以尝试一下。

    在地图上点击你可以添加一个标记,如:

     @Override
    public void onMapClick(LatLng latLng) {
        markerForGeofence(latLng);
    }
    
    private Marker geoFenceMarker;
    
    //create marker for geo fence
    private void markerForGeofence(LatLng model) {
        MarkerOptions markerOptions = new MarkerOptions()
                .position(model)
                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
    
        if ( map!=null ) {
            if (geoFenceMarker != null)
                geoFenceMarker.remove();
    
            geoFenceMarker = map.addMarker(markerOptions);
        }
    }
    

    围绕这个标记开始地理围栏:

    // Start Geofence creation process
    private void startGeofence() {
        if( geoFenceMarker != null ) {
            Geofence geofence = createGeofence( geoFenceMarker.getPosition(), GEOFENCE_RADIUS );
            GeofencingRequest geofenceRequest = createGeofenceRequest( geofence );
            addGeofence( geofenceRequest );
        }
    }
    
    
    private static final long GEO_DURATION = 60 * 60 * 1000;
    private static final String GEOFENCE_REQ_ID = "firstGeoFence";
    private static final float GEOFENCE_RADIUS = 2000.0f; // in meters
    
    // Create a Geofence Request
    private GeofencingRequest createGeofenceRequest(Geofence geofence ) {
        return new GeofencingRequest.Builder()
                .setInitialTrigger( GeofencingRequest.INITIAL_TRIGGER_ENTER )
                .addGeofence( geofence )
                .build();
    }
    
    // Create a Geo fence
    private Geofence createGeofence(LatLng latLng, float radius ) {
        return new Geofence.Builder()
                .setRequestId(GEOFENCE_REQ_ID)
                .setCircularRegion( latLng.latitude, latLng.longitude, radius)
                .setExpirationDuration( GEO_DURATION )
                .setTransitionTypes( Geofence.GEOFENCE_TRANSITION_ENTER
                        | Geofence.GEOFENCE_TRANSITION_EXIT )
                .build();
    }
    
    public void addGeofence(GeofencingRequest request) {
            LocationServices.GeofencingApi.addGeofences(
                    mGoogleApiClient,
                    request,
                    createGeofencePendingIntent()
            ).setResultCallback(this);
    }
    
    @Override
    public void onResult(@NonNull Result result) {
        if ( result.getStatus().isSuccess() ) {
            drawGeofence();
        }
    }
    
    private final int GEOFENCE_REQ_CODE = 0;
    
    private PendingIntent createGeofencePendingIntent() {
            if ( geoFencePendingIntent != null )
                return geoFencePendingIntent;
    
            Intent intent = new Intent( this, GeofenceTrasitionService.class);
            return PendingIntent.getService(
                    this, GEOFENCE_REQ_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT );
    }
    

    在谷歌地图上画圈:

        // Draw Geofence circle on GoogleMap
    private Circle geoFenceLimits;
    private void drawGeofence() {
        if ( geoFenceLimits != null )
            geoFenceLimits.remove();
    
        CircleOptions circleOptions = new CircleOptions()
                .center( geoFenceMarker.getPosition())
                .strokeColor(Color.argb(50, 70,70,70))
                .fillColor( Color.argb(100, 150,150,150) )
                .radius( GEOFENCE_RADIUS );
        geoFenceLimits = map.addCircle( circleOptions );
    }
    

    您还必须在将覆盖 onResult 方法的活动中实现 ResultCallback

    这个类将处理通知:

    public class GeofenceTrasitionService extends IntentService {
    
    private static final String TAG = GeofenceTrasitionService.class.getSimpleName();
    public static final int GEOFENCE_NOTIFICATION_ID = 0;
    
    public GeofenceTrasitionService() {
        super(TAG);
    }
    
    @Override
    protected void onHandleIntent(Intent intent) {
        // Retrieve the Geofencing intent
        GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
    
        // Handling errors
        if ( geofencingEvent.hasError() ) {
            String errorMsg = getErrorString(geofencingEvent.getErrorCode() );
            return;
        }
    
        // Retrieve GeofenceTrasition
        int geoFenceTransition = geofencingEvent.getGeofenceTransition();
        // Check if the transition type
        if ( geoFenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER ||
                geoFenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT ) {
            // Get the geofence that were triggered
            List<Geofence> triggeringGeofences = geofencingEvent.getTriggeringGeofences();
            // Create a detail message with Geofences received
            String geofenceTransitionDetails = getGeofenceTrasitionDetails(geoFenceTransition, triggeringGeofences );
            // Send notification details as a String
            sendNotification( geofenceTransitionDetails );
        }
    }
    
    // Create a detail message with Geofences received
    private String getGeofenceTrasitionDetails(int geoFenceTransition, List<Geofence> triggeringGeofences) {
        // get the ID of each geofence triggered
        ArrayList<String> triggeringGeofencesList = new ArrayList<>();
        for ( Geofence geofence : triggeringGeofences ) {
            triggeringGeofencesList.add( geofence.getRequestId() );
        }
    
        String status = null;
        if ( geoFenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER )
            status = "Entering ";
        else if ( geoFenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT )
            status = "Exiting ";
        return status + TextUtils.join( ", ", triggeringGeofencesList);
    }
    
    // Send a notification
    private void sendNotification( String msg ) {
        // Intent to start the main Activity
    
        Intent notificationIntent = new Intent(getApplicationContext(), MapActivity.class);
    
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(MapActivity.class);
        stackBuilder.addNextIntent(notificationIntent);
        PendingIntent notificationPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    
        // Creating and sending Notification
        NotificationManager notificatioMng =
                (NotificationManager) getSystemService( Context.NOTIFICATION_SERVICE );
        notificatioMng.notify(
                GEOFENCE_NOTIFICATION_ID,
                createNotification(msg, notificationPendingIntent));
    }
    
    // Create a notification
    private Notification createNotification(String msg, PendingIntent notificationPendingIntent) {
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
        notificationBuilder
                .setSmallIcon(R.mipmap.ic_launcher)
                .setColor(Color.RED)
                .setContentTitle(msg)
                .setContentText("Geofence Notification!")
                .setContentIntent(notificationPendingIntent)
                .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND)
                .setAutoCancel(true);
        return notificationBuilder.build();
    }
    
    // Handle errors
    private static String getErrorString(int errorCode) {
        switch (errorCode) {
            case GeofenceStatusCodes.GEOFENCE_NOT_AVAILABLE:
                return "GeoFence not available";
            case GeofenceStatusCodes.GEOFENCE_TOO_MANY_GEOFENCES:
                return "Too many GeoFences";
            case GeofenceStatusCodes.GEOFENCE_TOO_MANY_PENDING_INTENTS:
                return "Too many pending intents";
            default:
                return "Unknown error.";
        }
    }
    }
    

    在清单文件中:

    <service android:name="com.jaspreet.mapdemo.geoFence.GeofenceTrasitionService" />
    

    【讨论】:

    • 我明白这一点。但我想检查用户的当前位置是否在地理围栏中。这是我想在服务中执行的操作,然后用户会收到通知他是否在地理围栏中。 .请记住,我通过在地图上标记点来创建地理围栏,然后通过射线投射算法检查用户是否处于地理围栏中...... .
    • 您可以做什么,您可以在地图点击上添加一个标记,并通过创建一个 createGeofence 区域在此位置周围开始地理围栏。
    • @DaniyalIrfan 检查新答案!!
    • 是的,兄弟,我知道做地理围栏的方法。但我的要求是在地图上任何形状的运行时创建地理围栏。不仅在圆圈中,这就是为什么我必须在 mmy 上实现每一件事拥有..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-18
    • 2023-04-02
    相关资源
    最近更新 更多