Class LocationButton
- All Implemented Interfaces:
Animation, Editable, StyleListener, Iterable<Component>
A button the user taps to share their precise location once.
This is the transactional half of the location API: a "find shops near
me" button, an address auto-fill, a one-time "share where I am". It is not
a replacement for LocationManager, which stays the right API for
navigation, tracking, geofencing and anything else that follows the device
over time.
The distinction is not cosmetic. Where the platform draws a location button of its own, this component uses it, and a tap grants precise location for that session only -- the app never holds a persistent grant, and the user is never asked again on the next tap. Where the platform has no such control the component is an ordinary Codename One button that asks for location the usual way, so the same code compiles and runs everywhere.
LocationButton share = new LocationButton(LocationButton.TEXT_SHARE_PRECISE_LOCATION);
share.addLocationSharedListener(loc -> {
if (loc == null) {
status.setText("Location not shared");
} else {
status.setText(loc.getLatitude() + ", " + loc.getLongitude());
}
status.getParent().revalidate();
});
form.add(share);
Android and Google Play
Google Play requires the system-rendered location button for transactional
precise-location use in apps targeting Android 17 (API 37) and later; a
persistent ACCESS_FINE_LOCATION grant is reserved for core functionality
and carries a Play Console declaration. Referencing this class is what makes
the Android build declare USE_LOCATION_BUTTON and add the platform
library, so the button is system-rendered on API 37 and later and falls back
to the standard permission prompt below it.
An app whose only use of precise location is this button should also set
the android.locationButton.exclusive=true build hint. That marks
ACCESS_FINE_LOCATION as reachable through the button alone
(usesPermissionFlags="onlyForLocationButton"), which is what removes the
need for the persistent-location declaration. Do not set it in an app that
also tracks, navigates or geofences: those calls would then be refused the
grant they need.
Other platforms
iOS has no system-rendered button, but its own permission dialog offers "Allow Once", which is the same session-scoped grant reached a different way; the fallback button is the correct behaviour there. The simulator and every other port behave the same way.
-
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final intLabelled "Near my precise location".static final intLabelled "Near your precise location".static final intNo label -- the location icon alone.static final intLabelled "Precise location".static final intLabelled "Share precise location".static final intLabelled "Use precise location".Fields inherited from class Component
BASELINE, BOTTOM, BRB_CENTER_OFFSET, BRB_CONSTANT_ASCENT, BRB_CONSTANT_DESCENT, BRB_OTHER, CENTER, CROSSHAIR_CURSOR, DEFAULT_CURSOR, DRAG_REGION_IMMEDIATELY_DRAG_X, DRAG_REGION_IMMEDIATELY_DRAG_XY, DRAG_REGION_IMMEDIATELY_DRAG_Y, DRAG_REGION_LIKELY_DRAG_X, DRAG_REGION_LIKELY_DRAG_XY, DRAG_REGION_LIKELY_DRAG_Y, DRAG_REGION_NOT_DRAGGABLE, DRAG_REGION_POSSIBLE_DRAG_X, DRAG_REGION_POSSIBLE_DRAG_XY, DRAG_REGION_POSSIBLE_DRAG_Y, E_RESIZE_CURSOR, HAND_CURSOR, LEFT, MOVE_CURSOR, N_RESIZE_CURSOR, NE_RESIZE_CURSOR, NW_RESIZE_CURSOR, RIGHT, S_RESIZE_CURSOR, SE_RESIZE_CURSOR, SW_RESIZE_CURSOR, TEXT_CURSOR, TOP, W_RESIZE_CURSOR, WAIT_CURSOR -
Constructor Summary
ConstructorsConstructorDescriptionCreates a button labelled "Precise location".LocationButton(int textType) Creates a button with the given label. -
Method Summary
Modifier and TypeMethodDescriptionvoidAdds a listener for the location this button obtains.intThe background colour override, or -1 when the platform's own is used.intThe text colour override, or -1 when the platform's own is used.intThe label the button carries.longHow long to wait for a fix after the grant, in milliseconds.static booleanTrue when this device draws the button itself, which is what makes the grant session-scoped.booleanTrue when the platform's button was drawn and then failed, so this component cannot obtain a location at all.voidRemoves a previously added listener.voidsetButtonBackgroundColor(int color) Overrides the button's background colour.voidsetButtonTextColor(int color) Overrides the button's text and icon colour.voidsetTextType(int textType) Sets the label the button carries.voidsetTimeout(long timeout) Sets how long to wait for a fix after the grant.Methods inherited from class Container
add, add, add, add, add, add, addAll, addComponent, addComponent, addComponent, addComponent, animateHierarchy, animateHierarchyAndWait, animateHierarchyFade, animateHierarchyFadeAndWait, animateLayout, animateLayoutAndWait, animateLayoutFade, animateLayoutFadeAndWait, animateUnlayout, animateUnlayoutAndWait, applyRTL, calcPreferredSize, cancelRepaints, clearClientProperties, constrainHeightWhenScrollable, constrainWidthWhenScrollable, contains, createAnimateHierarchy, createAnimateHierarchyFade, createAnimateLayout, createAnimateLayoutFade, createAnimateLayoutFadeAndWait, createAnimateMotion, createAnimateUnlayout, createReplaceTransition, dragInitiated, drop, encloseIn, encloseIn, findDropTargetAt, findFirstFocusable, fireClicked, flushReplace, forceRevalidate, getBottomGap, getChildrenAsList, getClosestComponentTo, getComponentAt, getComponentAt, getComponentCount, getComponentIndex, getGridPosX, getGridPosY, getLayout, getLayoutHeight, getLayoutWidth, getLeadComponent, getLeadParent, getResponderAt, getSafeAreaRoot, getScrollIncrement, getSideGap, getUIManager, initLaf, invalidate, isEnabled, isSafeArea, isSafeAreaRoot, isScrollableX, isScrollableY, isSelectableInteraction, isSurface, iterator, iterator, keyPressed, keyReleased, layoutContainer, morph, morphAndWait, paint, paintComponentBackground, paintGlass, paramString, pointerPressed, refreshTheme, removeAll, removeComponent, replace, replace, replaceAndWait, replaceAndWait, replaceAndWait, revalidate, revalidateLater, revalidateWithAnimationSafety, scrollComponentToVisible, setCellRenderer, setEnabled, setLayout, setLeadComponent, setSafeArea, setSafeAreaRoot, setScrollable, setScrollableX, setScrollableY, setScrollIncrement, setShouldCalcPreferredSize, setShouldLayout, setUIManager, updateTabIndicesMethods inherited from class Component
accessibilityChanged, accessibilityChanged, addContextMenuListener, addDragFinishedListener, addDragOverListener, addDropListener, addFocusListener, addLongPressListener, addMouseWheelListener, addPointerDraggedListener, addPointerPressedListener, addPointerReleasedListener, addPullToRefresh, addScrollListener, addStateChangeListener, addStylusListener, animate, announceForAccessibility, bindProperty, blocksSideSwipe, calcScrollSize, consumesRawTextInput, contains, containsOrOwns, createStyleAnimation, deinitialize, deinitializeCustomStyle, deregisterFromAnimation, dragEnter, dragExit, dragFinished, draggingOver, drawDraggedImage, focusGained, focusLost, getAbsoluteX, getAbsoluteY, getAccessibilityNode, getAccessibilityText, getAllStyles, getAnimationManager, getBaseline, getBaselineResizeBehavior, getBindablePropertyNames, getBindablePropertyTypes, getBorder, getBoundPropertyValue, getBounds, getBounds, getClientProperty, getCloudBoundProperty, getCloudDestinationProperty, getComponentForm, getComponentState, getCursor, getDefaultDragTransparency, getDirtyRegion, getDisabledStyle, getDraggedx, getDraggedy, getDragImage, getDragRegionStatus, getDragSpeed, getDragTransparency, getEditingDelegate, getHeight, getInlineAllStyles, getInlineDisabledStyles, getInlinePressedStyles, getInlineSelectedStyles, getInlineStylesTheme, getInlineUnselectedStyles, getInnerHeight, getInnerPreferredH, getInnerPreferredW, getInnerWidth, getInnerX, getInnerY, getLabelForComponent, getName, getNativeOverlay, getNextFocusDown, getNextFocusLeft, getNextFocusRight, getNextFocusUp, getOuterHeight, getOuterPreferredH, getOuterPreferredW, getOuterWidth, getOuterX, getOuterY, getOwner, getParent, getPreferredH, getPreferredSize, getPreferredSizeStr, getPreferredTabIndex, getPreferredW, getPressedStyle, getPropertyNames, getPropertyTypeNames, getPropertyTypes, getPropertyValue, getSameHeight, getSameWidth, getScrollable, getScrollAnimationSpeed, getScrollDimension, getScrollOpacity, getScrollOpacityChangeSpeed, getScrollX, getScrollY, getSelectCommandText, getSelectedRect, getSelectedStyle, getSemantics, getStyle, getTabIndex, getTensileLength, getTextSelectionSupport, getTooltip, getTopLevelContainer, getUIID, getUnselectedStyle, getVisibleBounds, getVisibleBounds, getWidth, getX, getY, growShrink, handlesInput, hasFixedPreferredSize, hasFocus, hideNativeOverlay, initComponent, initCustomStyle, initDisabledStyle, initPressedStyle, initSelectedStyle, initUnselectedStyle, installDefaultPainter, isAlwaysTensile, isBlockLead, isCellRenderer, isChildOf, isDragActivated, isDragAndDropOperation, isDraggable, isDragRegion, isDropTarget, isEditable, isEditing, isFlatten, isFocusable, isGrabsPointerEvents, isHidden, isHidden, isHideInLandscape, isHideInPortrait, isHScrollThumbGrabbed, isHScrollThumbHover, isIgnorePointerEvents, isInClippingRegion, isInitialized, isOpaque, isOwnedBy, isPinchBlocksDragAndDrop, isRippleEffect, isRTL, isScrollable, isScrollVisible, isSetCursorSupported, isSmoothScrolling, isSnapToGrid, isStickyDrag, isTactileTouch, isTactileTouch, isTensileDragEnabled, isTraversable, isVisible, isVScrollThumbGrabbed, isVScrollThumbHover, keyRepeated, laidOut, longKeyPress, longPointerPress, mouseWheel, onScrollX, onScrollY, onSetFocusable, paintBackground, paintBackgrounds, paintBorder, paintBorderBackground, paintComponent, paintComponent, paintIntersectingComponentsAbove, paintLock, paintLockRelease, paintRippleOverlay, paintScrollbars, paintScrollbarX, paintScrollbarY, paintShadows, parsePreferredSize, pinch, pinch, pinchReleased, pointerDragged, pointerDragged, pointerHover, pointerHoverPressed, pointerHoverReleased, pointerPressed, pointerReleased, pointerReleased, putClientProperty, refreshTheme, refreshTheme, registerForAnimation, remove, removeContextMenuListener, removeDragFinishedListener, removeDragOverListener, removeDropListener, removeFocusListener, removeLongPressListener, removeMouseWheelListener, removePointerDraggedListener, removePointerPressedListener, removePointerReleasedListener, removeScrollListener, removeStateChangeListener, removeStylusListener, repaint, repaint, requestFocus, resetFocusable, respondsToPointerEvents, rotation, scrollRectToVisible, scrollRectToVisible, setAccessibilityText, setAlwaysTensile, setBlockLead, setBoundPropertyValue, setCloudBoundProperty, setCloudDestinationProperty, setComponentState, setCursor, setDefaultDragTransparency, setDirtyRegion, setDisabledStyle, setDraggable, setDragTransparency, setDropTarget, setEditingDelegate, setFlatten, setFocus, setFocusable, setGrabsPointerEvents, setHandlesInput, setHeight, setHidden, setHidden, setHideInLandscape, setHideInPortrait, setHorizontalScrollBounds, setIgnorePointerEvents, setInitialized, setInlineAllStyles, setInlineDisabledStyles, setInlinePressedStyles, setInlineSelectedStyles, setInlineStylesTheme, setInlineUnselectedStyles, setIsScrollVisible, setLabelForComponent, setName, setNextFocusDown, setNextFocusLeft, setNextFocusRight, setNextFocusUp, setOpaque, setOwner, setPinchBlocksDragAndDrop, setPreferredH, setPreferredSize, setPreferredSizeStr, setPreferredTabIndex, setPreferredW, setPressedStyle, setPropertyValue, setPullToRefresh, setRippleEffect, setRTL, setSameHeight, setSameSize, setSameWidth, setScrollAnimationSpeed, setScrollOpacityChangeSpeed, setScrollSize, setScrollVisible, setScrollX, setScrollY, setSelectCommandText, setSelectedStyle, setSize, setSmoothScrolling, setSnapToGrid, setTabIndex, setTactileTouch, setTensileDragEnabled, setTensileLength, setTooltip, setTraversable, setUIID, setUIID, setUIIDFinal, setUnselectedStyle, setVerticalScrollBounds, setVisible, setWidth, setX, setY, shouldBlockSideSwipe, shouldBlockSideSwipeLeft, shouldBlockSideSwipeRight, shouldRenderComponentSelection, showNativeOverlay, startEditingAsync, stopEditing, stripMarginAndPadding, styleChanged, toImage, toString, unbindProperty, updateNativeOverlay, visibleBoundsContains
-
Field Details
-
TEXT_NONE
public static final int TEXT_NONENo label -- the location icon alone.- See Also:
-
TEXT_PRECISE_LOCATION
public static final int TEXT_PRECISE_LOCATIONLabelled "Precise location". The default.- See Also:
-
TEXT_USE_PRECISE_LOCATION
public static final int TEXT_USE_PRECISE_LOCATIONLabelled "Use precise location".- See Also:
-
TEXT_SHARE_PRECISE_LOCATION
public static final int TEXT_SHARE_PRECISE_LOCATIONLabelled "Share precise location".- See Also:
-
TEXT_NEAR_MY_PRECISE_LOCATION
public static final int TEXT_NEAR_MY_PRECISE_LOCATIONLabelled "Near my precise location".- See Also:
-
TEXT_NEAR_YOUR_PRECISE_LOCATION
public static final int TEXT_NEAR_YOUR_PRECISE_LOCATIONLabelled "Near your precise location".- See Also:
-
-
Constructor Details
-
LocationButton
public LocationButton()Creates a button labelled "Precise location". -
LocationButton
public LocationButton(int textType) Creates a button with the given label.
Parameters
textType: one of theTEXT_constants
-
-
Method Details
-
isSystemRendered
public static boolean isSystemRendered()True when this device draws the button itself, which is what makes the grant session-scoped.
Useful for explanatory copy -- there is nothing to branch on otherwise, since the component works either way.
Returns
whether a tap goes through the system's own button
-
getTextType
public int getTextType()The label the button carries.
Returns
one of the
TEXT_constants -
setTextType
public void setTextType(int textType) Sets the label the button carries.
Parameters
textType: one of theTEXT_constants
-
setButtonBackgroundColor
public void setButtonBackgroundColor(int color) Overrides the button's background colour.
Left alone by default, which is deliberate: a location button the user recognises is the point of the control, and the system's own colours are what make it recognisable. Restyle only when the default is unreadable against the surface it sits on.
Parameters
color: an RRGGBB colour, or -1 to restore the platform's own
-
getButtonBackgroundColor
public int getButtonBackgroundColor()The background colour override, or -1 when the platform's own is used. -
setButtonTextColor
public void setButtonTextColor(int color) Overrides the button's text and icon colour. See
setButtonBackgroundColor(int)on why the default is worth keeping.Parameters
color: an RRGGBB colour, or -1 to restore the platform's own
-
getButtonTextColor
public int getButtonTextColor()The text colour override, or -1 when the platform's own is used. -
getTimeout
public long getTimeout()How long to wait for a fix after the grant, in milliseconds.
Returns
the timeout, or -1 to wait indefinitely
-
setTimeout
public void setTimeout(long timeout) Sets how long to wait for a fix after the grant.
The default is 30 seconds. Waiting indefinitely is available but rarely what a transactional flow wants: a first GPS fix indoors can never arrive, and the listener would then never be called at all.
Parameters
timeout: milliseconds, or -1 to wait indefinitely
-