idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
35,400
private static String resolveSibling ( String fromPath , String toPath ) { if ( toPath . startsWith ( "/" ) ) { return toPath ; } List < String > fromPathParts = new ArrayList < > ( Arrays . asList ( fromPath . split ( "/" ) ) ) ; List < String > toPathParts = new ArrayList < > ( Arrays . asList ( toPath . split ( "/" ) ) ) ; if ( ! fromPathParts . isEmpty ( ) ) { fromPathParts . remove ( fromPathParts . size ( ) - 1 ) ; } while ( ! fromPathParts . isEmpty ( ) && ! toPathParts . isEmpty ( ) ) { if ( toPathParts . get ( 0 ) . equals ( "." ) ) { toPathParts . remove ( 0 ) ; } else if ( toPathParts . get ( 0 ) . equals ( ".." ) ) { toPathParts . remove ( 0 ) ; fromPathParts . remove ( fromPathParts . size ( ) - 1 ) ; } else { break ; } } fromPathParts . addAll ( toPathParts ) ; return String . join ( "/" , fromPathParts ) ; }
Simplistic implementation of the java . nio . file . Path resolveSibling method that works with GWT .
35,401
private void addHeaderCode ( Node script ) { script . addChildToFront ( createConditionalObjectDecl ( JS_INSTRUMENTATION_OBJECT_NAME , script ) ) ; script . addChildToFront ( compiler . parseSyntheticCode ( "if (!self.window) { self.window = self; self.window.top = self; }" ) . removeFirstChild ( ) . useSourceInfoIfMissingFromForTree ( script ) ) ; }
Creates the js code to be added to source . This code declares and initializes the variables required for collection of coverage data .
35,402
public WaitOptions withDuration ( Duration duration ) { checkNotNull ( duration ) ; checkArgument ( duration . toMillis ( ) >= 0 , "Duration value should be greater or equal to zero" ) ; this . duration = duration ; return this ; }
Set the wait duration .
35,403
public LongPressOptions withDuration ( Duration duration ) { checkNotNull ( duration ) ; checkArgument ( duration . toMillis ( ) >= 0 , "Duration value should be greater or equal to zero" ) ; this . duration = duration ; return this ; }
Set the long press duration .
35,404
public static Map . Entry < String , Map < String , ? > > getPerformanceDataCommand ( String packageName , String dataType , int dataReadTimeout ) { String [ ] parameters = new String [ ] { "packageName" , "dataType" , "dataReadTimeout" } ; Object [ ] values = new Object [ ] { packageName , dataType , dataReadTimeout } ; return new AbstractMap . SimpleEntry < > ( GET_PERFORMANCE_DATA , prepareArguments ( parameters , values ) ) ; }
returns the resource usage information of the application . the resource is one of the system state which means cpu memory network traffic and battery .
35,405
public void connect ( URI endpoint ) { if ( endpoint . equals ( this . getEndpoint ( ) ) && isListening ) { return ; } OkHttpClient client = new OkHttpClient . Builder ( ) . readTimeout ( 0 , TimeUnit . MILLISECONDS ) . build ( ) ; Request request = new Request . Builder ( ) . url ( endpoint . toString ( ) ) . build ( ) ; client . newWebSocket ( request , this ) ; client . dispatcher ( ) . executorService ( ) . shutdown ( ) ; setEndpoint ( endpoint ) ; }
Connects web socket client .
35,406
public ScreenshotState verifyChanged ( Duration timeout , double minScore ) { return checkState ( ( x ) -> x < minScore , timeout ) ; }
Verifies whether the state of the screenshot provided by stateProvider lambda function is changed within the given timeout .
35,407
public ScreenshotState verifyNotChanged ( Duration timeout , double minScore ) { return checkState ( ( x ) -> x >= minScore , timeout ) ; }
Verifies whether the state of the screenshot provided by stateProvider lambda function is not changed within the given timeout .
35,408
public IOSTouchAction doubleTap ( PointOption doubleTapOption ) { ActionParameter action = new ActionParameter ( "doubleTap" , doubleTapOption ) ; parameterBuilder . add ( action ) ; return this ; }
Double taps using coordinates .
35,409
@ SuppressWarnings ( "unchecked" ) public static < T > T getEnhancedProxy ( Class < T > requiredClazz , Class < ? > [ ] params , Object [ ] values , MethodInterceptor interceptor ) { Enhancer enhancer = new Enhancer ( ) ; enhancer . setSuperclass ( requiredClazz ) ; enhancer . setCallback ( interceptor ) ; return ( T ) enhancer . create ( params , values ) ; }
It returns some proxies created by CGLIB .
35,410
protected static Capabilities substituteMobilePlatform ( Capabilities originalCapabilities , String newPlatform ) { DesiredCapabilities dc = new DesiredCapabilities ( originalCapabilities ) ; dc . setCapability ( PLATFORM_NAME , newPlatform ) ; return dc ; }
Changes platform name and returns new capabilities .
35,411
public List < WebElement > findElements ( ) { if ( cachedElementList != null && shouldCache ) { return cachedElementList ; } List < WebElement > result ; try { result = waitFor ( ( ) -> { List < WebElement > list = searchContext . findElements ( getBy ( by , searchContext ) ) ; return list . size ( ) > 0 ? list : null ; } ) ; } catch ( TimeoutException | StaleElementReferenceException e ) { result = new ArrayList < > ( ) ; } if ( shouldCache ) { cachedElementList = result ; } return result ; }
Find the element list .
35,412
public void writeTo ( Appendable appendable ) throws IOException { try ( JsonOutput json = new Json ( ) . newOutput ( appendable ) ) { json . beginObject ( ) ; Map < String , Object > first = getOss ( ) ; if ( first == null ) { first = ( Map < String , Object > ) stream ( ) . findFirst ( ) . orElse ( new ImmutableCapabilities ( ) ) . asMap ( ) ; } json . name ( DESIRED_CAPABILITIES ) ; json . write ( first ) ; if ( ! forceMobileJSONWP ) { json . name ( CAPABILITIES ) ; json . beginObject ( ) ; json . name ( FIRST_MATCH ) ; json . beginArray ( ) ; getW3C ( ) . forEach ( json :: write ) ; json . endArray ( ) ; json . endObject ( ) ; } writeMetaData ( json ) ; json . endObject ( ) ; } }
Writes json capabilities to some appendable object .
35,413
public MultiTouchAction perform ( ) { List < TouchAction > touchActions = actions . build ( ) ; checkArgument ( touchActions . size ( ) > 0 , "MultiTouch action must have at least one TouchAction added before it can be performed" ) ; if ( touchActions . size ( ) > 1 ) { performsTouchActions . performMultiTouchAction ( this ) ; return this ; } performsTouchActions . performTouchAction ( touchActions . get ( 0 ) ) ; return this ; }
Perform the multi - touch action on the mobile performsTouchActions .
35,414
public void runAppInBackground ( Duration duration ) { execute ( RUN_APP_IN_BACKGROUND , prepareArguments ( "seconds" , prepareArguments ( "timeout" , duration . toMillis ( ) ) ) ) ; }
Runs the current app as a background app for the number of seconds or minimizes the app .
35,415
public Capabilities getCapabilities ( ) { MutableCapabilities capabilities = ( MutableCapabilities ) super . getCapabilities ( ) ; if ( capabilities != null ) { capabilities . setCapability ( PLATFORM_NAME , IOS_PLATFORM ) ; } return capabilities ; }
Returns capabilities that were provided on instantiation .
35,416
public Point getCenter ( ) { Point upperLeft = this . getLocation ( ) ; Dimension dimensions = this . getSize ( ) ; return new Point ( upperLeft . getX ( ) + dimensions . getWidth ( ) / 2 , upperLeft . getY ( ) + dimensions . getHeight ( ) / 2 ) ; }
Method returns central coordinates of an element .
35,417
public void setValue ( String value ) { ImmutableMap . Builder < String , Object > builder = ImmutableMap . builder ( ) ; builder . put ( "id" , id ) . put ( "value" , value ) ; execute ( MobileCommand . SET_VALUE , builder . build ( ) ) ; }
This method sets the new value of the attribute value .
35,418
public void start ( ) throws AppiumServerHasNotBeenStartedLocallyException { lock . lock ( ) ; try { if ( isRunning ( ) ) { return ; } try { process = new CommandLine ( this . nodeJSExec . getCanonicalPath ( ) , nodeJSArgs . toArray ( new String [ ] { } ) ) ; process . setEnvironmentVariables ( nodeJSEnvironment ) ; process . copyOutputTo ( stream ) ; process . executeAsync ( ) ; ping ( startupTimeout , timeUnit ) ; } catch ( Throwable e ) { destroyProcess ( ) ; String msgTxt = "The local appium server has not been started. " + "The given Node.js executable: " + this . nodeJSExec . getAbsolutePath ( ) + " Arguments: " + nodeJSArgs . toString ( ) + " " + "\n" ; if ( process != null ) { String processStream = process . getStdOut ( ) ; if ( ! StringUtils . isBlank ( processStream ) ) { msgTxt = msgTxt + "Process output: " + processStream + "\n" ; } } throw new AppiumServerHasNotBeenStartedLocallyException ( msgTxt , e ) ; } } finally { lock . unlock ( ) ; } }
Starts the defined appium server .
35,419
public void stop ( ) { lock . lock ( ) ; try { if ( process != null ) { destroyProcess ( ) ; } process = null ; } finally { lock . unlock ( ) ; } }
Stops this service is it is currently running . This method will attempt to block until the server has been fully shutdown .
35,420
public void addOutPutStreams ( List < OutputStream > outputStreams ) { checkNotNull ( outputStreams , "outputStreams parameter is NULL!" ) ; for ( OutputStream stream : outputStreams ) { addOutPutStream ( stream ) ; } }
Adds other output streams which should accept server output data .
35,421
public Rectangle getRect ( ) { verifyPropertyPresence ( RECT ) ; return mapToRect ( ( Map < String , Object > ) getCommandResult ( ) . get ( RECT ) ) ; }
Returns rectangle of partial image occurrence .
35,422
public KeyEvent withMetaModifier ( KeyEventMetaModifier keyEventMetaModifier ) { if ( this . metaState == null ) { this . metaState = 0 ; } this . metaState |= keyEventMetaModifier . getValue ( ) ; return this ; }
Adds the meta modifier .
35,423
public KeyEvent withFlag ( KeyEventFlag keyEventFlag ) { if ( this . flags == null ) { this . flags = 0 ; } this . flags |= keyEventFlag . getValue ( ) ; return this ; }
Adds the flag .
35,424
public Map < String , Object > build ( ) { final ImmutableMap . Builder < String , Object > builder = ImmutableMap . builder ( ) ; final int keyCode = ofNullable ( this . keyCode ) . orElseThrow ( ( ) -> new IllegalStateException ( "The key code must be set" ) ) ; builder . put ( "keycode" , keyCode ) ; ofNullable ( this . metaState ) . ifPresent ( x -> builder . put ( "metastate" , x ) ) ; ofNullable ( this . flags ) . ifPresent ( x -> builder . put ( "flags" , x ) ) ; return builder . build ( ) ; }
Builds a map which is ready to be used by the downstream API .
35,425
public List < Point > getPoints1 ( ) { verifyPropertyPresence ( POINTS1 ) ; return ( ( List < Map < String , Object > > ) getCommandResult ( ) . get ( POINTS1 ) ) . stream ( ) . map ( ComparisonResult :: mapToPoint ) . collect ( Collectors . toList ( ) ) ; }
Returns a list of matching points on the first image .
35,426
public Rectangle getRect1 ( ) { verifyPropertyPresence ( RECT1 ) ; return mapToRect ( ( Map < String , Object > ) getCommandResult ( ) . get ( RECT1 ) ) ; }
Returns a rect for the points1 list .
35,427
public List < Point > getPoints2 ( ) { verifyPropertyPresence ( POINTS2 ) ; return ( ( List < Map < String , Object > > ) getCommandResult ( ) . get ( POINTS2 ) ) . stream ( ) . map ( ComparisonResult :: mapToPoint ) . collect ( Collectors . toList ( ) ) ; }
Returns a list of matching points on the second image .
35,428
public Rectangle getRect2 ( ) { verifyPropertyPresence ( RECT2 ) ; return mapToRect ( ( Map < String , Object > ) getCommandResult ( ) . get ( RECT2 ) ) ; }
Returns a rect for the points2 list .
35,429
public double getLevel ( ) { final Object value = getInput ( ) . get ( "level" ) ; if ( value instanceof Long ) { return ( ( Long ) value ) . doubleValue ( ) ; } return ( double ) value ; }
Returns battery level .
35,430
protected void verifyPropertyPresence ( String propertyName ) { if ( ! commandResult . containsKey ( propertyName ) ) { throw new IllegalStateException ( String . format ( "There is no '%s' attribute in the resulting command output %s. " + "Did you set the options properly?" , propertyName , commandResult ) ) ; } }
Verifies if the corresponding property is present in the commend result and throws an exception if not .
35,431
public byte [ ] getVisualization ( ) { verifyPropertyPresence ( VISUALIZATION ) ; return ( ( String ) getCommandResult ( ) . get ( VISUALIZATION ) ) . getBytes ( StandardCharsets . UTF_8 ) ; }
Returns the visualization of the matching result .
35,432
public void storeVisualization ( File destination ) throws IOException { final byte [ ] data = Base64 . decodeBase64 ( getVisualization ( ) ) ; try ( OutputStream stream = new FileOutputStream ( destination ) ) { stream . write ( data ) ; } }
Stores visualization image into the given file .
35,433
private static int toSeleniumCoordinate ( Object openCVCoordinate ) { if ( openCVCoordinate instanceof Long ) { return ( ( Long ) openCVCoordinate ) . intValue ( ) ; } if ( openCVCoordinate instanceof Double ) { return ( ( Double ) openCVCoordinate ) . intValue ( ) ; } return ( int ) openCVCoordinate ; }
Converts float OpenCV coordinates to Selenium - compatible format .
35,434
public AppiumServiceBuilder withArgument ( ServerArgument argument , String value ) { String argName = argument . getArgument ( ) . trim ( ) . toLowerCase ( ) ; if ( "--port" . equals ( argName ) || "-p" . equals ( argName ) ) { usingPort ( Integer . valueOf ( value ) ) ; } else if ( "--address" . equals ( argName ) || "-a" . equals ( argName ) ) { withIPAddress ( value ) ; } else if ( "--log" . equals ( argName ) || "-g" . equals ( argName ) ) { withLogFile ( new File ( value ) ) ; } else { serverArguments . put ( argName , value ) ; } return this ; }
Adds a server argument .
35,435
public AppiumServiceBuilder withCapabilities ( DesiredCapabilities capabilities ) { if ( this . capabilities == null ) { this . capabilities = capabilities ; } else { DesiredCapabilities desiredCapabilities = new DesiredCapabilities ( ) ; desiredCapabilities . merge ( this . capabilities ) . merge ( capabilities ) ; this . capabilities = desiredCapabilities ; } return this ; }
Adds a desired capabilities .
35,436
public AppiumServiceBuilder withStartUpTimeOut ( long time , TimeUnit timeUnit ) { checkNotNull ( timeUnit ) ; checkArgument ( time > 0 , "Time value should be greater than zero" , time ) ; this . startupTimeout = time ; this . timeUnit = timeUnit ; return this ; }
Sets start up timeout .
35,437
public static ImmutableMap < String , Object > prepareArguments ( String param , Object value ) { ImmutableMap . Builder < String , Object > builder = ImmutableMap . builder ( ) ; builder . put ( param , value ) ; return builder . build ( ) ; }
Prepares single argument .
35,438
public static ImmutableMap < String , Object > prepareArguments ( String [ ] params , Object [ ] values ) { ImmutableMap . Builder < String , Object > builder = ImmutableMap . builder ( ) ; for ( int i = 0 ; i < params . length ; i ++ ) { if ( ! StringUtils . isBlank ( params [ i ] ) && ( values [ i ] != null ) ) { builder . put ( params [ i ] , values [ i ] ) ; } } return builder . build ( ) ; }
Prepares collection of arguments .
35,439
public T moveTo ( PointOption moveToOptions ) { ActionParameter action = new ActionParameter ( "moveTo" , moveToOptions ) ; parameterBuilder . add ( action ) ; return ( T ) this ; }
Moves current touch to a new position .
35,440
public T tap ( TapOptions tapOptions ) { ActionParameter action = new ActionParameter ( "tap" , tapOptions ) ; parameterBuilder . add ( action ) ; return ( T ) this ; }
Tap on an element .
35,441
public T tap ( PointOption tapOptions ) { ActionParameter action = new ActionParameter ( "tap" , tapOptions ) ; parameterBuilder . add ( action ) ; return ( T ) this ; }
Tap on a position .
35,442
public T waitAction ( WaitOptions waitOptions ) { ActionParameter action = new ActionParameter ( "wait" , waitOptions ) ; parameterBuilder . add ( action ) ; return ( T ) this ; }
Waits for specified amount of time to pass before continue to next touch action .
35,443
protected Map < String , List < Object > > getParameters ( ) { List < ActionParameter > actionList = parameterBuilder . build ( ) ; return ImmutableMap . of ( "actions" , actionList . stream ( ) . map ( ActionParameter :: getParameterMap ) . collect ( toList ( ) ) ) ; }
Get the mjsonwp parameters for this Action .
35,444
public static byte [ ] computeMultipartBoundary ( ) { ThreadLocalRandom random = ThreadLocalRandom . current ( ) ; byte [ ] bytes = new byte [ 35 ] ; for ( int i = 0 ; i < bytes . length ; i ++ ) { bytes [ i ] = MULTIPART_CHARS [ random . nextInt ( MULTIPART_CHARS . length ) ] ; } return bytes ; }
a fixed size of 35
35,445
public void scheduleAfterBackgroundWakeup ( Context context , List < ScanResult > scanResults ) { if ( scanResults != null ) { mBackgroundScanResultQueue . addAll ( scanResults ) ; } synchronized ( this ) { if ( System . currentTimeMillis ( ) - mScanJobScheduleTime > MIN_MILLIS_BETWEEN_SCAN_JOB_SCHEDULING ) { LogManager . d ( TAG , "scheduling an immediate scan job because last did " + ( System . currentTimeMillis ( ) - mScanJobScheduleTime ) + "seconds ago." ) ; mScanJobScheduleTime = System . currentTimeMillis ( ) ; } else { LogManager . d ( TAG , "Not scheduling an immediate scan job because we just did recently." ) ; return ; } } ScanState scanState = ScanState . restore ( context ) ; schedule ( context , scanState , true ) ; }
must exist on another branch until the SDKs are released .
35,446
@ SuppressWarnings ( "unused" ) @ RequiresApi ( 21 ) public void enablePowerCycleOnFailures ( Context context ) { initializeWithContext ( context ) ; if ( this . mLocalBroadcastManager != null ) { this . mLocalBroadcastManager . registerReceiver ( this . mBluetoothEventReceiver , new IntentFilter ( "onScanFailed" ) ) ; this . mLocalBroadcastManager . registerReceiver ( this . mBluetoothEventReceiver , new IntentFilter ( "onStartFailure" ) ) ; LogManager . d ( TAG , "Medic monitoring for transmission and scan failure notifications with receiver: " + this . mBluetoothEventReceiver ) ; } }
If set to true bluetooth will be power cycled on any tests run that determine bluetooth is in a bad state .
35,447
public static void d ( String tag , String message , Object ... args ) { sLogger . d ( tag , message , args ) ; }
Send a debug log message to the logger .
35,448
public static void i ( String tag , String message , Object ... args ) { sLogger . i ( tag , message , args ) ; }
Send a info log message to the logger .
35,449
public static void w ( String tag , String message , Object ... args ) { sLogger . w ( tag , message , args ) ; }
Send a warning log message to the logger .
35,450
public static void e ( String tag , String message , Object ... args ) { sLogger . e ( tag , message , args ) ; }
Send a error log message to the logger .
35,451
public IBinder onBind ( Intent intent ) { LogManager . i ( TAG , "binding" ) ; return mMessenger . getBinder ( ) ; }
When binding to the service we return an interface to our messenger for sending messages to the service .
35,452
public boolean onUnbind ( Intent intent ) { LogManager . i ( TAG , "unbinding so destroying self" ) ; this . stopForeground ( true ) ; this . stopSelf ( ) ; return false ; }
called when the last bound client calls unbind
35,453
public void startRangingBeaconsInRegion ( Region region , Callback callback ) { synchronized ( mScanHelper . getRangedRegionState ( ) ) { if ( mScanHelper . getRangedRegionState ( ) . containsKey ( region ) ) { LogManager . i ( TAG , "Already ranging that region -- will replace existing region." ) ; mScanHelper . getRangedRegionState ( ) . remove ( region ) ; } mScanHelper . getRangedRegionState ( ) . put ( region , new RangeState ( callback ) ) ; LogManager . d ( TAG , "Currently ranging %s regions." , mScanHelper . getRangedRegionState ( ) . size ( ) ) ; } if ( mScanHelper . getCycledScanner ( ) != null ) { mScanHelper . getCycledScanner ( ) . start ( ) ; } }
methods for clients
35,454
public static Identifier parse ( String stringValue , int desiredByteLength ) { if ( stringValue == null ) { throw new NullPointerException ( "Identifiers cannot be constructed from null pointers but \"stringValue\" is null." ) ; } if ( HEX_PATTERN . matcher ( stringValue ) . matches ( ) ) { return parseHex ( stringValue . substring ( 2 ) , desiredByteLength ) ; } if ( UUID_PATTERN . matcher ( stringValue ) . matches ( ) ) { return parseHex ( stringValue . replace ( "-" , "" ) , desiredByteLength ) ; } if ( DECIMAL_PATTERN . matcher ( stringValue ) . matches ( ) ) { int value = - 1 ; try { value = Integer . valueOf ( stringValue ) ; } catch ( Throwable t ) { throw new IllegalArgumentException ( "Unable to parse Identifier in decimal format." , t ) ; } if ( desiredByteLength <= 0 || desiredByteLength == 2 ) { return fromInt ( value ) ; } else { return fromLong ( value , desiredByteLength ) ; } } if ( HEX_PATTERN_NO_PREFIX . matcher ( stringValue ) . matches ( ) ) { return parseHex ( stringValue , desiredByteLength ) ; } throw new IllegalArgumentException ( "Unable to parse Identifier." ) ; }
Variant of the parse method that allows specifying the byte length of the identifier .
35,455
public static Identifier fromLong ( long longValue , int desiredByteLength ) { if ( desiredByteLength < 0 ) { throw new IllegalArgumentException ( "Identifier length must be > 0." ) ; } byte [ ] newValue = new byte [ desiredByteLength ] ; for ( int i = desiredByteLength - 1 ; i >= 0 ; i -- ) { newValue [ i ] = ( byte ) ( longValue & 0xff ) ; longValue = longValue >> 8 ; } return new Identifier ( newValue ) ; }
Creates an Identifer backed by an array of length desiredByteLength
35,456
@ TargetApi ( Build . VERSION_CODES . GINGERBREAD ) public static Identifier fromBytes ( byte [ ] bytes , int start , int end , boolean littleEndian ) { if ( bytes == null ) { throw new NullPointerException ( "Identifiers cannot be constructed from null pointers but \"bytes\" is null." ) ; } if ( start < 0 || start > bytes . length ) { throw new ArrayIndexOutOfBoundsException ( "start < 0 || start > bytes.length" ) ; } if ( end > bytes . length ) { throw new ArrayIndexOutOfBoundsException ( "end > bytes.length" ) ; } if ( start > end ) { throw new IllegalArgumentException ( "start > end" ) ; } byte [ ] byteRange = Arrays . copyOfRange ( bytes , start , end ) ; if ( littleEndian ) { reverseArray ( byteRange ) ; } return new Identifier ( byteRange ) ; }
Creates an Identifier from the specified byte array .
35,457
@ TargetApi ( Build . VERSION_CODES . GINGERBREAD ) public byte [ ] toByteArrayOfSpecifiedEndianness ( boolean bigEndian ) { byte [ ] copy = Arrays . copyOf ( mValue , mValue . length ) ; if ( ! bigEndian ) { reverseArray ( copy ) ; } return copy ; }
Converts identifier to a byte array
35,458
public UUID toUuid ( ) { if ( mValue . length != 16 ) { throw new UnsupportedOperationException ( "Only Identifiers backed by a byte array with length of exactly 16 can be UUIDs." ) ; } LongBuffer buf = ByteBuffer . wrap ( mValue ) . asLongBuffer ( ) ; return new UUID ( buf . get ( ) , buf . get ( ) ) ; }
Gives you the Identifier as a UUID if possible .
35,459
public int compareTo ( Identifier that ) { if ( mValue . length != that . mValue . length ) { return mValue . length < that . mValue . length ? - 1 : 1 ; } for ( int i = 0 ; i < mValue . length ; i ++ ) { if ( mValue [ i ] != that . mValue [ i ] ) { return mValue [ i ] < that . mValue [ i ] ? - 1 : 1 ; } } return 0 ; }
Compares two identifiers . When the Identifiers don t have the same length the Identifier having the shortest array is considered smaller than the other .
35,460
public int matchScore ( AndroidModel otherModel ) { int score = 0 ; if ( this . mManufacturer . equalsIgnoreCase ( otherModel . mManufacturer ) ) { score = 1 ; } if ( score == 1 && this . mModel . equals ( otherModel . mModel ) ) { score = 2 ; } if ( score == 2 && this . mBuildNumber . equals ( otherModel . mBuildNumber ) ) { score = 3 ; } if ( score == 3 && this . mVersion . equals ( otherModel . mVersion ) ) { score = 4 ; } LogManager . d ( TAG , "Score is %s for %s compared to %s" , score , toString ( ) , otherModel ) ; return score ; }
Calculates a qualitative match score between two different Android device models for the purposes of how likely they are to have similar Bluetooth signal level responses
35,461
public List < Identifier > getIdentifiers ( ) { if ( mIdentifiers . getClass ( ) . isInstance ( UNMODIFIABLE_LIST_OF_IDENTIFIER ) ) { return mIdentifiers ; } else { return Collections . unmodifiableList ( mIdentifiers ) ; } }
Returns the list of identifiers transmitted with the advertisement
35,462
public double getDistance ( ) { if ( mDistance == null ) { double bestRssiAvailable = mRssi ; if ( mRunningAverageRssi != null ) { bestRssiAvailable = mRunningAverageRssi ; } else { LogManager . d ( TAG , "Not using running average RSSI because it is null" ) ; } mDistance = calculateDistance ( mTxPower , bestRssiAvailable ) ; } return mDistance ; }
Provides a calculated estimate of the distance to the beacon based on a running average of the RSSI and the transmitted power calibration value included in the beacon advertisement . This value is specific to the type of Android device receiving the transmission .
35,463
public void writeToParcel ( Parcel out , int flags ) { out . writeInt ( mIdentifiers . size ( ) ) ; for ( Identifier identifier : mIdentifiers ) { out . writeString ( identifier == null ? null : identifier . toString ( ) ) ; } out . writeDouble ( getDistance ( ) ) ; out . writeInt ( mRssi ) ; out . writeInt ( mTxPower ) ; out . writeString ( mBluetoothAddress ) ; out . writeInt ( mBeaconTypeCode ) ; out . writeInt ( mServiceUuid ) ; out . writeInt ( mDataFields . size ( ) ) ; for ( Long dataField : mDataFields ) { out . writeLong ( dataField ) ; } out . writeInt ( mExtraDataFields . size ( ) ) ; for ( Long dataField : mExtraDataFields ) { out . writeLong ( dataField ) ; } out . writeInt ( mManufacturer ) ; out . writeString ( mBluetoothName ) ; out . writeString ( mParserIdentifier ) ; out . writeByte ( ( byte ) ( mMultiFrameBeacon ? 1 : 0 ) ) ; out . writeValue ( mRunningAverageRssi ) ; out . writeInt ( mRssiMeasurementCount ) ; out . writeInt ( mPacketCount ) ; }
Required for making object Parcelable . If you override this class you must override this method if you add any additional fields .
35,464
public boolean matchesBeacon ( Beacon beacon ) { for ( int i = mIdentifiers . size ( ) ; -- i >= 0 ; ) { final Identifier identifier = mIdentifiers . get ( i ) ; Identifier beaconIdentifier = null ; if ( i < beacon . mIdentifiers . size ( ) ) { beaconIdentifier = beacon . getIdentifier ( i ) ; } if ( ( beaconIdentifier == null && identifier != null ) || ( beaconIdentifier != null && identifier != null && ! identifier . equals ( beaconIdentifier ) ) ) { return false ; } } if ( mBluetoothAddress != null && ! mBluetoothAddress . equalsIgnoreCase ( beacon . mBluetoothAddress ) ) { return false ; } return true ; }
Checks to see if an Beacon object is included in the matching criteria of this Region
35,465
public Beacon fromScanData ( byte [ ] scanData , int rssi , BluetoothDevice device ) { return fromScanData ( scanData , rssi , device , new Beacon ( ) ) ; }
Construct a Beacon from a Bluetooth LE packet collected by Android s Bluetooth APIs including the raw Bluetooth device info
35,466
public void startAdvertising ( Beacon beacon , AdvertiseCallback callback ) { mBeacon = beacon ; mAdvertisingClientCallback = callback ; startAdvertising ( ) ; }
Starts advertising with fields from the passed beacon
35,467
public void startAdvertising ( ) { if ( mBeacon == null ) { throw new NullPointerException ( "Beacon cannot be null. Set beacon before starting advertising" ) ; } int manufacturerCode = mBeacon . getManufacturer ( ) ; int serviceUuid = - 1 ; if ( mBeaconParser . getServiceUuid ( ) != null ) { serviceUuid = mBeaconParser . getServiceUuid ( ) . intValue ( ) ; } if ( mBeaconParser == null ) { throw new NullPointerException ( "You must supply a BeaconParser instance to BeaconTransmitter." ) ; } byte [ ] advertisingBytes = mBeaconParser . getBeaconAdvertisementData ( mBeacon ) ; String byteString = "" ; for ( int i = 0 ; i < advertisingBytes . length ; i ++ ) { byteString += String . format ( "%02X" , advertisingBytes [ i ] ) ; byteString += " " ; } LogManager . d ( TAG , "Starting advertising with ID1: %s ID2: %s ID3: %s and data: %s of size " + "%s" , mBeacon . getId1 ( ) , mBeacon . getIdentifiers ( ) . size ( ) > 1 ? mBeacon . getId2 ( ) : "" , mBeacon . getIdentifiers ( ) . size ( ) > 2 ? mBeacon . getId3 ( ) : "" , byteString , advertisingBytes . length ) ; try { AdvertiseData . Builder dataBuilder = new AdvertiseData . Builder ( ) ; if ( serviceUuid > 0 ) { byte [ ] serviceUuidBytes = new byte [ ] { ( byte ) ( serviceUuid & 0xff ) , ( byte ) ( ( serviceUuid >> 8 ) & 0xff ) } ; ParcelUuid parcelUuid = parseUuidFrom ( serviceUuidBytes ) ; dataBuilder . addServiceData ( parcelUuid , advertisingBytes ) ; dataBuilder . addServiceUuid ( parcelUuid ) ; dataBuilder . setIncludeTxPowerLevel ( false ) ; dataBuilder . setIncludeDeviceName ( false ) ; } else { dataBuilder . addManufacturerData ( manufacturerCode , advertisingBytes ) ; } AdvertiseSettings . Builder settingsBuilder = new AdvertiseSettings . Builder ( ) ; settingsBuilder . setAdvertiseMode ( mAdvertiseMode ) ; settingsBuilder . setTxPowerLevel ( mAdvertiseTxPowerLevel ) ; settingsBuilder . setConnectable ( mConnectable ) ; mBluetoothLeAdvertiser . startAdvertising ( settingsBuilder . build ( ) , dataBuilder . build ( ) , getAdvertiseCallback ( ) ) ; LogManager . d ( TAG , "Started advertisement with callback: %s" , getAdvertiseCallback ( ) ) ; } catch ( Exception e ) { LogManager . e ( e , TAG , "Cannot start advertising due to exception" ) ; } }
Starts this beacon advertising
35,468
public void stopAdvertising ( ) { if ( ! mStarted ) { LogManager . d ( TAG , "Skipping stop advertising -- not started" ) ; return ; } LogManager . d ( TAG , "Stopping advertising with object %s" , mBluetoothLeAdvertiser ) ; mAdvertisingClientCallback = null ; try { mBluetoothLeAdvertiser . stopAdvertising ( getAdvertiseCallback ( ) ) ; } catch ( IllegalStateException e ) { LogManager . w ( TAG , "Bluetooth is turned off. Transmitter stop call failed." ) ; } mStarted = false ; }
Stops this beacon from advertising
35,469
public static int checkTransmissionSupported ( Context context ) { int returnCode = SUPPORTED ; if ( android . os . Build . VERSION . SDK_INT < 21 ) { returnCode = NOT_SUPPORTED_MIN_SDK ; } else if ( ! context . getApplicationContext ( ) . getPackageManager ( ) . hasSystemFeature ( PackageManager . FEATURE_BLUETOOTH_LE ) ) { returnCode = NOT_SUPPORTED_BLE ; } else { try { if ( ( ( BluetoothManager ) context . getSystemService ( Context . BLUETOOTH_SERVICE ) ) . getAdapter ( ) . getBluetoothLeAdvertiser ( ) == null ) { if ( ! ( ( BluetoothManager ) context . getSystemService ( Context . BLUETOOTH_SERVICE ) ) . getAdapter ( ) . isMultipleAdvertisementSupported ( ) ) { returnCode = NOT_SUPPORTED_CANNOT_GET_ADVERTISER_MULTIPLE_ADVERTISEMENTS ; } else { returnCode = NOT_SUPPORTED_CANNOT_GET_ADVERTISER ; } } } catch ( Exception e ) { returnCode = NOT_SUPPORTED_CANNOT_GET_ADVERTISER ; } } return returnCode ; }
Checks to see if this device supports beacon advertising
35,470
public void commitMeasurements ( ) { if ( ! getFilter ( ) . noMeasurementsAvailable ( ) ) { double runningAverage = getFilter ( ) . calculateRssi ( ) ; mBeacon . setRunningAverageRssi ( runningAverage ) ; mBeacon . setRssiMeasurementCount ( getFilter ( ) . getMeasurementCount ( ) ) ; LogManager . d ( TAG , "calculated new runningAverageRssi: %s" , runningAverage ) ; } else { LogManager . d ( TAG , "No measurements available to calculate running average" ) ; } mBeacon . setPacketCount ( packetCount ) ; packetCount = 0 ; }
Done at the end of each cycle before data are sent to the client
35,471
public void setScanPeriods ( long scanPeriod , long betweenScanPeriod , boolean backgroundFlag ) { LogManager . d ( TAG , "Set scan periods called with %s, %s Background mode must have changed." , scanPeriod , betweenScanPeriod ) ; if ( mBackgroundFlag != backgroundFlag ) { mRestartNeeded = true ; } mBackgroundFlag = backgroundFlag ; mScanPeriod = scanPeriod ; mBetweenScanPeriod = betweenScanPeriod ; if ( mBackgroundFlag ) { LogManager . d ( TAG , "We are in the background. Setting wakeup alarm" ) ; setWakeUpAlarm ( ) ; } else { LogManager . d ( TAG , "We are not in the background. Cancelling wakeup alarm" ) ; cancelWakeUpAlarm ( ) ; } long now = SystemClock . elapsedRealtime ( ) ; if ( mNextScanCycleStartTime > now ) { long proposedNextScanStartTime = ( mLastScanCycleEndTime + betweenScanPeriod ) ; if ( proposedNextScanStartTime < mNextScanCycleStartTime ) { mNextScanCycleStartTime = proposedNextScanStartTime ; LogManager . i ( TAG , "Adjusted nextScanStartTime to be %s" , new Date ( mNextScanCycleStartTime - SystemClock . elapsedRealtime ( ) + System . currentTimeMillis ( ) ) ) ; } } if ( mScanCycleStopTime > now ) { long proposedScanStopTime = ( mLastScanCycleStartTime + scanPeriod ) ; if ( proposedScanStopTime < mScanCycleStopTime ) { mScanCycleStopTime = proposedScanStopTime ; LogManager . i ( TAG , "Adjusted scanStopTime to be %s" , mScanCycleStopTime ) ; } } }
Tells the cycler the scan rate and whether it is in operating in background mode . Background mode flag is used only with the Android 5 . 0 scanning implementations to switch between LOW_POWER_MODE vs . LOW_LATENCY_MODE
35,472
protected void setWakeUpAlarm ( ) { long milliseconds = 1000l * 60 * 5 ; if ( milliseconds < mBetweenScanPeriod ) { milliseconds = mBetweenScanPeriod ; } if ( milliseconds < mScanPeriod ) { milliseconds = mScanPeriod ; } AlarmManager alarmManager = ( AlarmManager ) mContext . getSystemService ( Context . ALARM_SERVICE ) ; alarmManager . set ( AlarmManager . ELAPSED_REALTIME_WAKEUP , SystemClock . elapsedRealtime ( ) + milliseconds , getWakeUpOperation ( ) ) ; LogManager . d ( TAG , "Set a wakeup alarm to go off in %s ms: %s" , milliseconds , getWakeUpOperation ( ) ) ; }
off the scan cycle again
35,473
PendingIntent getScanCallbackIntent ( ) { Intent intent = new Intent ( mContext , StartupBroadcastReceiver . class ) ; intent . putExtra ( "o-scan" , true ) ; return PendingIntent . getBroadcast ( mContext , 0 , intent , PendingIntent . FLAG_UPDATE_CURRENT ) ; }
Low power scan results in the background will be delivered via Intent
35,474
public void disable ( ) { if ( disabled ) { return ; } disabled = true ; try { for ( Region region : regions ) { beaconManager . stopMonitoringBeaconsInRegion ( region ) ; } } catch ( RemoteException e ) { LogManager . e ( e , TAG , "Can't stop bootstrap regions" ) ; } beaconManager . unbind ( beaconConsumer ) ; }
Used to disable additional bootstrap callbacks after the first is received . Unless this is called your application will be get additional calls as the supplied regions are entered or exited .
35,475
public void addRegion ( Region region ) { if ( ! regions . contains ( region ) ) { if ( serviceConnected ) { try { beaconManager . startMonitoringBeaconsInRegion ( region ) ; } catch ( RemoteException e ) { LogManager . e ( e , TAG , "Can't add bootstrap region" ) ; } } else { LogManager . w ( TAG , "Adding a region: service not yet Connected" ) ; } regions . add ( region ) ; } }
Add a new region
35,476
public void removeRegion ( Region region ) { if ( regions . contains ( region ) ) { if ( serviceConnected ) { try { beaconManager . stopMonitoringBeaconsInRegion ( region ) ; } catch ( RemoteException e ) { LogManager . e ( e , TAG , "Can't stop bootstrap region" ) ; } } else { LogManager . w ( TAG , "Removing a region: service not yet Connected" ) ; } regions . remove ( region ) ; } }
Remove a given region
35,477
public synchronized Collection < Beacon > finalizeBeacons ( ) { Map < Beacon , RangedBeacon > newRangedBeacons = new HashMap < Beacon , RangedBeacon > ( ) ; ArrayList < Beacon > finalizedBeacons = new ArrayList < Beacon > ( ) ; synchronized ( mRangedBeacons ) { for ( Beacon beacon : mRangedBeacons . keySet ( ) ) { RangedBeacon rangedBeacon = mRangedBeacons . get ( beacon ) ; if ( rangedBeacon != null ) { if ( rangedBeacon . isTracked ( ) ) { rangedBeacon . commitMeasurements ( ) ; if ( ! rangedBeacon . noMeasurementsAvailable ( ) ) { finalizedBeacons . add ( rangedBeacon . getBeacon ( ) ) ; } } if ( ! rangedBeacon . noMeasurementsAvailable ( ) == true ) { if ( ! sUseTrackingCache || rangedBeacon . isExpired ( ) ) rangedBeacon . setTracked ( false ) ; newRangedBeacons . put ( beacon , rangedBeacon ) ; } else { LogManager . d ( TAG , "Dumping beacon from RangeState because it has no recent measurements." ) ; } } } mRangedBeacons = newRangedBeacons ; } return finalizedBeacons ; }
be there for the next cycle
35,478
private boolean initialzeScanHelper ( ) { mScanHelper = new ScanHelper ( this ) ; mScanState = ScanState . restore ( ScanJob . this ) ; mScanState . setLastScanStartTimeMillis ( System . currentTimeMillis ( ) ) ; mScanHelper . setMonitoringStatus ( mScanState . getMonitoringStatus ( ) ) ; mScanHelper . setRangedRegionState ( mScanState . getRangedRegionState ( ) ) ; mScanHelper . setBeaconParsers ( mScanState . getBeaconParsers ( ) ) ; mScanHelper . setExtraDataBeaconTracker ( mScanState . getExtraBeaconDataTracker ( ) ) ; if ( mScanHelper . getCycledScanner ( ) == null ) { try { mScanHelper . createCycledLeScanner ( mScanState . getBackgroundMode ( ) , null ) ; } catch ( OutOfMemoryError e ) { LogManager . w ( TAG , "Failed to create CycledLeScanner thread." ) ; return false ; } } return true ; }
Returns false if cycle thread cannot be allocated
35,479
public static void setDebug ( boolean debug ) { if ( debug ) { LogManager . setLogger ( Loggers . verboseLogger ( ) ) ; LogManager . setVerboseLoggingEnabled ( true ) ; } else { LogManager . setLogger ( Loggers . empty ( ) ) ; LogManager . setVerboseLoggingEnabled ( false ) ; } }
Set to true if you want to show library debugging .
35,480
public static void setRegionExitPeriod ( long regionExitPeriod ) { sExitRegionPeriod = regionExitPeriod ; BeaconManager instance = sInstance ; if ( instance != null ) { instance . applySettings ( ) ; } }
Set region exit period in milliseconds
35,481
@ TargetApi ( 18 ) public boolean checkAvailability ( ) throws BleNotAvailableException { if ( ! isBleAvailableOrSimulated ( ) ) { throw new BleNotAvailableException ( "Bluetooth LE not supported by this device" ) ; } return ( ( BluetoothManager ) mContext . getSystemService ( Context . BLUETOOTH_SERVICE ) ) . getAdapter ( ) . isEnabled ( ) ; }
Check if Bluetooth LE is supported by this Android device and if so make sure it is enabled .
35,482
public void setBackgroundMode ( boolean backgroundMode ) { if ( ! isBleAvailableOrSimulated ( ) ) { LogManager . w ( TAG , "Method invocation will be ignored." ) ; return ; } mBackgroundModeUninitialized = false ; if ( backgroundMode != mBackgroundMode ) { mBackgroundMode = backgroundMode ; try { this . updateScanPeriods ( ) ; } catch ( RemoteException e ) { LogManager . e ( TAG , "Cannot contact service to set scan periods" ) ; } } }
This method notifies the beacon service that the application is either moving to background mode or foreground mode . When in background mode BluetoothLE scans to look for beacons are executed less frequently in order to save battery life . The specific scan rates for background and foreground operation are set by the defaults below but may be customized . When ranging in the background the time between updates will be much less frequent than in the foreground . Updates will come every time interval equal to the sum total of the BackgroundScanPeriod and the BackgroundBetweenScanPeriod .
35,483
public void setEnableScheduledScanJobs ( boolean enabled ) { if ( isAnyConsumerBound ( ) ) { LogManager . e ( TAG , "ScanJob may not be configured because a consumer is" + " already bound." ) ; throw new IllegalStateException ( "Method must be called before calling bind()" ) ; } if ( enabled && android . os . Build . VERSION . SDK_INT < Build . VERSION_CODES . LOLLIPOP ) { LogManager . e ( TAG , "ScanJob may not be configured because JobScheduler is not" + " availble prior to Android 5.0" ) ; return ; } if ( ! enabled && android . os . Build . VERSION . SDK_INT >= Build . VERSION_CODES . O ) { LogManager . w ( TAG , "Disabling ScanJobs on Android 8+ may disable delivery of " + "beacon callbacks in the background unless a foreground service is active." ) ; } if ( ! enabled && android . os . Build . VERSION . SDK_INT >= Build . VERSION_CODES . LOLLIPOP ) { ScanJobScheduler . getInstance ( ) . cancelSchedule ( mContext ) ; } mScheduledScanJobsEnabled = enabled ; }
Configures using a ScanJob run with the JobScheduler to perform scans rather than using a long - running BeaconService to do so .
35,484
public void setRegionStatePersistenceEnabled ( boolean enabled ) { mRegionStatePersistenceEnabled = enabled ; if ( ! isScannerInDifferentProcess ( ) ) { if ( enabled ) { MonitoringStatus . getInstanceForApplication ( mContext ) . startStatusPreservation ( ) ; } else { MonitoringStatus . getInstanceForApplication ( mContext ) . stopStatusPreservation ( ) ; } } this . applySettings ( ) ; }
Turns off saving the state of monitored regions to persistent storage so it is retained over app restarts . Defaults to enabled . When enabled there will not be an extra region entry event when the app starts up and a beacon for a monitored region was previously visible within the past 15 minutes . Note that there is a limit to 50 monitored regions that may be persisted . If more than 50 regions are monitored state is not persisted for any .
35,485
public void applySettings ( ) { if ( determineIfCalledFromSeparateScannerProcess ( ) ) { return ; } if ( ! isAnyConsumerBound ( ) ) { LogManager . d ( TAG , "Not synchronizing settings to service, as it has not started up yet" ) ; } else if ( isScannerInDifferentProcess ( ) ) { LogManager . d ( TAG , "Synchronizing settings to service" ) ; syncSettingsToService ( ) ; } else { LogManager . d ( TAG , "Not synchronizing settings to service, as it is in the same process" ) ; } }
Call this method if you are running the scanner service in a different process in order to synchronize any configuration settings including BeaconParsers to the scanner
35,486
public void enableForegroundServiceScanning ( Notification notification , int notificationId ) throws IllegalStateException { if ( isAnyConsumerBound ( ) ) { throw new IllegalStateException ( "May not be called after consumers are already bound." ) ; } if ( notification == null ) { throw new NullPointerException ( "Notification cannot be null" ) ; } setEnableScheduledScanJobs ( false ) ; mForegroundServiceNotification = notification ; mForegroundServiceNotificationId = notificationId ; }
Configures the library to use a foreground service for bacon scanning . This allows nearly constant scanning on most Android versions to get around background limits and displays an icon to the user to indicate that the app is doing something in the background even on Android 8 + . This will disable the user of the JobScheduler on Android 8 to do scans . Note that this method does not by itself enable constant scanning . The scan intervals will work as normal and must be configurd to specific values depending on how often you wish to scan .
35,487
public double calculateDistance ( int txPower , double rssi ) { if ( rssi == 0 ) { return - 1.0 ; } LogManager . d ( TAG , "calculating distance based on mRssi of %s and txPower of %s" , rssi , txPower ) ; double ratio = rssi * 1.0 / txPower ; double distance ; if ( ratio < 1.0 ) { distance = Math . pow ( ratio , 10 ) ; } else { distance = ( mCoefficient1 ) * Math . pow ( ratio , mCoefficient2 ) + mCoefficient3 ; } LogManager . d ( TAG , "avg mRssi: %s distance: %s" , rssi , distance ) ; return distance ; }
Calculated the estimated distance in meters to the beacon based on a reference rssi at 1m and the known actual rssi at the current location
35,488
@ TargetApi ( 18 ) public void notifyScannedDevice ( BluetoothDevice device , BluetoothAdapter . LeScanCallback scanner ) { int oldSize , newSize ; oldSize = distinctBluetoothAddresses . size ( ) ; synchronized ( distinctBluetoothAddresses ) { distinctBluetoothAddresses . add ( device . getAddress ( ) ) ; } newSize = distinctBluetoothAddresses . size ( ) ; if ( oldSize != newSize && newSize % 100 == 0 ) { LogManager . d ( TAG , "Distinct Bluetooth devices seen: %s" , distinctBluetoothAddresses . size ( ) ) ; } if ( distinctBluetoothAddresses . size ( ) > getCrashRiskDeviceCount ( ) ) { if ( PREEMPTIVE_ACTION_ENABLED && ! recoveryInProgress ) { LogManager . w ( TAG , "Large number of Bluetooth devices detected: %s Proactively " + "attempting to clear out address list to prevent a crash" , distinctBluetoothAddresses . size ( ) ) ; LogManager . w ( TAG , "Stopping LE Scan" ) ; BluetoothAdapter . getDefaultAdapter ( ) . stopLeScan ( scanner ) ; startRecovery ( ) ; processStateChange ( ) ; } } }
Call this method from your BluetoothAdapter . LeScanCallback method . Doing so is optional but if you do this class will be able to count the number of distinct Bluetooth devices scanned and prevent crashes before they happen .
35,489
public Beacon fromScanData ( byte [ ] scanData , int rssi , BluetoothDevice device ) { return fromScanData ( scanData , rssi , device , new AltBeacon ( ) ) ; }
Construct an AltBeacon from a Bluetooth LE packet collected by Android s Bluetooth APIs including the raw Bluetooth device info
35,490
public byte [ ] getTelemetryBytes ( Beacon beacon ) { if ( beacon . getExtraDataFields ( ) . size ( ) >= 5 ) { Beacon telemetryBeacon = new Beacon . Builder ( ) . setDataFields ( beacon . getExtraDataFields ( ) ) . build ( ) ; BeaconParser telemetryParser = new BeaconParser ( ) . setBeaconLayout ( BeaconParser . EDDYSTONE_TLM_LAYOUT ) ; byte [ ] telemetryBytes = telemetryParser . getBeaconAdvertisementData ( telemetryBeacon ) ; Log . d ( TAG , "Rehydrated telemetry bytes are :" + byteArrayToString ( telemetryBytes ) ) ; return telemetryBytes ; } else { return null ; } }
Extracts the raw Eddystone telemetry bytes from the extra data fields of an associated beacon . This is useful for passing the telemetry to Google s backend services .
35,491
@ TargetApi ( Build . VERSION_CODES . FROYO ) public String getBase64EncodedTelemetry ( Beacon beacon ) { byte [ ] bytes = getTelemetryBytes ( beacon ) ; if ( bytes != null ) { String base64EncodedTelemetry = Base64 . encodeToString ( bytes , Base64 . DEFAULT ) ; Log . d ( TAG , "Base64 telemetry bytes are :" + base64EncodedTelemetry ) ; return base64EncodedTelemetry ; } else { return null ; } }
Extracts the raw Eddystone telemetry bytes from the extra data fields of an associated beacon and base64 encodes them . This is useful for passing the telemetry to Google s backend services .
35,492
public boolean call ( Context context , String dataName , Bundle data ) { boolean useLocalBroadcast = BeaconManager . getInstanceForApplication ( context ) . isMainProcess ( ) ; boolean success = false ; if ( useLocalBroadcast ) { String action = null ; if ( dataName == "rangingData" ) { action = BeaconLocalBroadcastProcessor . RANGE_NOTIFICATION ; } else { action = BeaconLocalBroadcastProcessor . MONITOR_NOTIFICATION ; } Intent intent = new Intent ( action ) ; intent . putExtra ( dataName , data ) ; LogManager . d ( TAG , "attempting callback via local broadcast intent: %s" , action ) ; success = LocalBroadcastManager . getInstance ( context ) . sendBroadcast ( intent ) ; } else { Intent intent = new Intent ( ) ; intent . setComponent ( new ComponentName ( context . getPackageName ( ) , "org.altbeacon.beacon.BeaconIntentProcessor" ) ) ; intent . putExtra ( dataName , data ) ; LogManager . d ( TAG , "attempting callback via global broadcast intent: %s" , intent . getComponent ( ) ) ; try { context . startService ( intent ) ; success = true ; } catch ( Exception e ) { LogManager . e ( TAG , "Failed attempting to start service: " + intent . getComponent ( ) . flattenToString ( ) , e ) ; } } return success ; }
Tries making the callback first via messenger then via intent
35,493
@ TargetApi ( Build . VERSION_CODES . GINGERBREAD ) public static Pdu parse ( byte [ ] bytes , int startIndex ) { Pdu pdu = null ; if ( bytes . length - startIndex >= 2 ) { byte length = bytes [ startIndex ] ; if ( length > 0 ) { byte type = bytes [ startIndex + 1 ] ; int firstIndex = startIndex + 2 ; if ( firstIndex < bytes . length ) { pdu = new Pdu ( ) ; pdu . mEndIndex = startIndex + length ; if ( pdu . mEndIndex >= bytes . length ) { pdu . mEndIndex = bytes . length - 1 ; } pdu . mType = type ; pdu . mDeclaredLength = length ; pdu . mStartIndex = firstIndex ; pdu . mBytes = bytes ; } } } return pdu ; }
Parse a PDU from a byte array looking offset by startIndex
35,494
public static String replaceAllEmojis ( String str , final String replacementString ) { EmojiParser . EmojiTransformer emojiTransformer = new EmojiParser . EmojiTransformer ( ) { public String transform ( EmojiParser . UnicodeCandidate unicodeCandidate ) { return replacementString ; } } ; return parseFromUnicode ( str , emojiTransformer ) ; }
Replace all emojis with character
35,495
public static String removeAllEmojis ( String str ) { EmojiTransformer emojiTransformer = new EmojiTransformer ( ) { public String transform ( UnicodeCandidate unicodeCandidate ) { return "" ; } } ; return parseFromUnicode ( str , emojiTransformer ) ; }
Removes all emojis from a String
35,496
public static String removeEmojis ( String str , final Collection < Emoji > emojisToRemove ) { EmojiTransformer emojiTransformer = new EmojiTransformer ( ) { public String transform ( UnicodeCandidate unicodeCandidate ) { if ( ! emojisToRemove . contains ( unicodeCandidate . getEmoji ( ) ) ) { return unicodeCandidate . getEmoji ( ) . getUnicode ( ) + unicodeCandidate . getFitzpatrickUnicode ( ) ; } return "" ; } } ; return parseFromUnicode ( str , emojiTransformer ) ; }
Removes a set of emojis from a String
35,497
public static String removeAllEmojisExcept ( String str , final Collection < Emoji > emojisToKeep ) { EmojiTransformer emojiTransformer = new EmojiTransformer ( ) { public String transform ( UnicodeCandidate unicodeCandidate ) { if ( emojisToKeep . contains ( unicodeCandidate . getEmoji ( ) ) ) { return unicodeCandidate . getEmoji ( ) . getUnicode ( ) + unicodeCandidate . getFitzpatrickUnicode ( ) ; } return "" ; } } ; return parseFromUnicode ( str , emojiTransformer ) ; }
Removes all the emojis in a String except a provided set
35,498
protected static UnicodeCandidate getNextUnicodeCandidate ( char [ ] chars , int start ) { for ( int i = start ; i < chars . length ; i ++ ) { int emojiEnd = getEmojiEndPos ( chars , i ) ; if ( emojiEnd != - 1 ) { Emoji emoji = EmojiManager . getByUnicode ( new String ( chars , i , emojiEnd - i ) ) ; String fitzpatrickString = ( emojiEnd + 2 <= chars . length ) ? new String ( chars , emojiEnd , 2 ) : null ; return new UnicodeCandidate ( emoji , fitzpatrickString , i ) ; } } return null ; }
Finds the next UnicodeCandidate after a given starting index
35,499
public Matches isEmoji ( char [ ] sequence ) { if ( sequence == null ) { return Matches . POSSIBLY ; } Node tree = root ; for ( char c : sequence ) { if ( ! tree . hasChild ( c ) ) { return Matches . IMPOSSIBLE ; } tree = tree . getChild ( c ) ; } return tree . isEndOfEmoji ( ) ? Matches . EXACTLY : Matches . POSSIBLY ; }
Checks if sequence of chars contain an emoji .