Android facilities
Not logged in

borg command

Name

borg - control and interact with the Android OS.

Synopsis

package require Borg
borg cmd ?arg ...?

Description

This command integrates the capabilities of Tcl/Tk with Android by way of several subcommands. These allow Tcl/Tk to go where it has never gone before by querying and controlling Bluetooth functionality, OS notifications (including device vibration and even speech), location information, etc.

Bluetooth-Related Commands

borg bluetooth devices

Returns a list suited for array set or dict create commands containing the Bluetooth address and friendly name of all paired Bluetooth devices.

borg bluetooth state

Returns the current Bluetooth state: off, on, turning_off, or turning_on.

borg bluetooth scanmode

Returns the current Bluetooth scan mode: connectable, off, passive, or visible.

borg bluetooth myaddress

Returns the Bluetooth address of the local default Bluetooth adapter.

borg bluetooth remoteaddress address

Returns the friendly name for the given Bluetooth address.

borg bluetooth on

Quote from Android documentation: do not use without explicit user action to turn on Bluetooth. Tries to turn the Bluetooth adapter on. Returns 1 if the adapter is already or going to be turned on, 0 otherwise.

borg bluetooth off

Quote from Android documentation: do not use without explicit user action to turn off Bluetooth. Tries to turn the Bluetooth adapter off. Returns 1 if the adapter is already or going to be turned off, 0 otherwise.

For communication over Bluetooth see the description of the rfcomm command. For handling of Bluetooth Low Energy (Bluetooth Smart) devices see the description of the ble command.

USB-Related Commands

borg usbdevices ?extended?

If extended is omitted or false, a list suitable for the array set or dict create commands containing the USB device name and vendor/product identifier of all currently connected USB devices is returned. Otherwise, i.e. extended is true, three elements per USB device are returned: USB device name, product/vendor identifier, and USB interface information as in udev.

borg usbpermission devname ?ask?

Queries permission for the USB device devname and returns 1 if the device is usable, 0 if not, and a negative number on error. If the optional boolean argument ask is specified as true, a system dialog is shown allowing the user to grant or deny permission for the USB device.

For communication over USB serial converters see the description of the usbserial command.

Network-Related Commands

borg networkinfo

Returns the current state of the network: none, wifi, mobile gsm, etc. An update of this information is indicated by the <<NetworkInfo>> virtual event sent to all toplevel widgets.

borg tetherinfo

Returns the current state of tethering as a list suited for array set or dict create with zero or three entries active, available, and error which usually contain interface names. An update of this information is indicated by the <<TetherInfo>> virtual event sent to all toplevel widgets.

Desktop-Related Commands

borg shortcut add name-of-shortcut script-to-run ?png-icon-as-base-64-string?

Adds an icon to the desktop, with the label name-of-shortcut specified. The script, specified as script-to-run must use an absolute path as a file:// URI and must be readable by the user id under which the AndroWish package has been registered by the Android installer. The last (optional) parameter png-icon-as-base-64-string allows the icon graphic to be specified. If not provided, a default AndroWish icon is used. According to the guidelines on iconography icons should have an aspect ratio of 48 by 48 pixels (192 x 192 is recommended, at 4 times 48x48 pixels). Example (pseudo code):
    package require base64
    proc read_binary_file {name} { # whatever is needed to read bytes ... }
    set icondata [read_binary_file "/mnt/sdcard/appicon_48_48.png"]
    set iconbase64 [::base64::encode -maxlen 0 $icondata]
    borg shortcut add "My App" file://mnt/sdcard/speaktest.tcl $iconbase64

borg shortcut delete name-of-shortcut

Deletes an icon from desktop (depends on Android launcher support).

Notification-Related Commands

borg notification add id title ?text icon action uri type categories component arguments?

Adds a notification with title and text into the Android notification area. The integer id, specified by the caller, is used to identify the notification for later modification or deletion. The optional parameters starting from action form an activity (see borg activity ...) to be carried out when the user clicks on the notification. See the description of borg alarm set below for special treatment of the component parameter. The optional icon must be a PNG or JPG image encoded as base64 string. The size of the icon should be 24 by 24 pixels.

borg notification delete ?id?

Deletes a notification identified that was created with the id specified. If no id is provided, all notifications are deleted.

borg notification led id argb onms offms

Adds a notification controlling the device LED. The integer id, specified by the caller, is used to identify the notification for later modification or deletion. The integer parameter argb is the LED color as combined RGB value with alpha channel, onms and offms are integers, too, controlling the duty cycle of blinking.

borg vibrate ms

Turns the vibration motor on for integer ms milliseconds.

borg beep ?uri?

Plays a notification sound. If uri is specified and not an empty string, it is played as notification/ringtone/alarm sound. If given as empty string, the current playback is stopped. If omitted or unable to be resolved, the default notification sound is played. The URI typically has the pattern content://media/{internal,external}/audio/media/<id>, where id is an integer number identifying a sound file. The borg content command can be used to obtain information on notification sounds from Android's media provider.

borg speak text ?lang pitch rate?

Gets the Android to read out the string text. Optional parameter lang is the language code for the spoken language, e.g. en, en_US, de, es, etc. Optional parameters pitch and rate control the voice and speed as float values. On success an integer number >= 1000 is returned which identifies the text to be spoken in various virtual events. On error a negative number is returned. More information.

borg stopspeak

Stops speech output.

borg isspeaking

Returns a small integer indicating the state of speech output. Zero indicates initialization of speech output has been performed but no speech output is currently active. One is returned when speech output is active. A small negative number indicates an error, temporary or permanent unavailability of the text-to-speech facility. In order to start up the text-to-speech facility this command can be used. The first call usually returns -1 and calls some few hundred milliseconds later return zero, indicating availability of the text-to-speech facility.

borg endspeak

Stops speech output and releases system resources.

borg toast text ?flag? ?html?

Displays a text notification text for a short period of time. The duration of that display is somewhat longer when flag is specified as true. The text parameter is interpreted as HTML when html is specified as true.

borg spinner on|off

Displays or withdraws a spinner (rotating symbol indicating busy state) depending on argument.

Location-Related Commands

borg location start ?minrate-in-ms ?min-dist-in-m??

Begins acquiring location data via the Android OS (which may choose to use GPS, network info, etc.).

borg location stop

Ends location data acquisition.

borg location get

Returns the location data (as an array set or dict createform) where the key is the location source. Location updates trigger a virtual event <<LocationUpdate>> that is sent to all toplevel widgets. These toplevel event-handlers should, in turn, invoke borg location get to refresh their knowledge.

borg location gps

Returns GPS information in array set or dict create form with the keys state (on or off) and first_fix (time in seconds until first fix expected). Updates in GPS information are indicated by the <<GPSUpdate>> virtual event sent to all toplevel widgets.

borg location satellites

Returns GPS satellite information in array set or dict create form where the key is a numerical index and the values are per satellite information in array set or dict create form containing the fields index, azimuth, elevation, prn, snr, almanac, ephemeris, and infix. Updates in GPS information are indicated by the <<GPSUpdate>> virtual event sent to all toplevel widgets.

borg location nmea

Returns a string made up of the NMEA sentences collected over the last second. Updates in this string are indicated by the <<NMEAUpdate>> virtual event sent to all toplevel widgets.

System-Related Commands

borg displaymetrics

Returns information about the display in form suited for array set or dict create, e.g. display resolution, pixel density. The entry rotation gives the current screen rotation in degrees. The 0 degree point varies between devices, typical smart phones report 0 for portrait, tablets report 0 for landscape orientation. More information.

borg osbuildinfo

Returns information about the operating system and device in form suited for array set or dict create, e.g. Android API level, version, device name, manufacturer etc. More information.

borg queryfeatures

Returns information about features of the system (a lengthy list of strings) which is obtained from getSystemAvailableFeatures.

borg queryconsts classname

Returns a dictionary of constants of the (loaded) Java class classname. The keys are the names of the constants, the values their value. For example, the symbols of SYSTEM_UI_* flags are available when you evaluate:
    borg queryconsts android.view.View

borg queryfields classname

Returns a dictionary of constants and static fields of the (loaded) Java class classname. This is similar to borg queryconsts but allows to retrieve no-constant strings, too. Most useful in combination with the android.os.Environment class.

borg packageinfo ?name?

Returns information about installed packages or an individual package if its name is given. In the first case, a list with package names is returned, in the latter case a list of key value pairs with package information which can be used for array set or dict create.

borg providerinfo

Returns the authority names of all content providers known to the system as a list.

borg log prio tag message

Writes the message message to Android's system log with priority prio (one of verbose, debug, info, warn, error, or fatal) and a user chosen prefix tag. These log messages can be displayed using adb logcat on the development system.

borg trace message script

Evaluates script and adds message before and after that evaluation to Android's system trace buffer. This is supported only on newer Android OS versions (4.3 and above) and further described in the android.os.Trace class.

borg systemproperties ?name?

Returns a list of system properties (a lengthy list of key value pairs) or the value of a specific system property if name is given.

borg checkpermission ?name ... ask?

If no arguments are provided a (long) list of permissions known to the package manager is returned. A detailed list is described in Manifest.permission. If a single name is given, the command returns 0 or 1 depending on manifest permission name. If more than one permission is to be checked, the last parameter ask must be a boolean. If ask is true, an optional dialog is shown, if the user has to explicitely allow the respective permissions. If more than a single name is provided the result of the command is a list.

Sensor-Related Commands

borg sensor list

Returns a list of the available sensors of the device. Each item is suited for array set or dict create and contains the fields index (integer index of the sensor, used to identify it), type (sensor type, one of accelerometer, temperature, game_rotation_vector, geomagnetic_rotation_vector, gravity, gyroscope, gyroscope_uncalibrated, light, linear_acceleration, magnetic_field, magnetic_field_uncalibrated, orientation, pressure, proximity, relative_humidity, rotation_vector, step_counter, and step_detector), mindelay (minimum update interval in milliseconds), maxrange (maximum range, floating point), resolution (floating point), power (in mA, floating point), and name (name of the sensor). More information.

borg sensor enable|disable|state index

Turns the sensor identified by index on or off, or returns its state (0=off, 1=on). An enabled sensor generates <<SensorUpdate>> virtual events which are sent to toplevel windows. These events are either periodic updates or change notifications depending on the kind of sensor and its refresh rate. If a sensor is not read out using borg sensor get ... for a certain amount of time that sensor is automatically disabled to conserve battery power. If the application enters background (see virtual event <<WillEnterBackground>>) all enabled sensors are disabled and re-enabled again when the application comes back to foreground (see virtual event <<WillEnterForeground>>).

borg sensor get index

Returns the last value acquired from the sensor identified by index as a list suited for array set or dict create containing the fields index (integer), enabled (sensor state, 0 or 1), maxrange (see above), resolution (see above), accuracy (the accuracy of this value), values (the sensor value, zero or more floating point numbers). When both accelerometer and magnetic_field sensors are turned on, the information for the magnetic_field sensor has two additional entries orientation (3 element list of azimuth, pitch, roll) and inclination. The pressure sensor has an additional entry altitude (meters above sea level). More information.

Android Content (shared databases)

borg content query uri ?columns ?where ?whereargs ?orderby????

Performs a query on an Android content provider given by uri and returns a cursor token (a Tcl command which deals with that cursor). The optional columns are a list of database columns to appear in the result set, e.g.
    set cursor [borg content query content://contacts/people {display_name _id}]
where an empty list of database columns works like the SQL statement "SELECT *".
The optional where and whereargs parameters form the SQL WHERE clause of the query. Question mark parameter markers in where are positionally substituted by the information from the whereargs list. If the where parameter does not use a question mark parameter marker, an empty parameter string is obligatory as in
    set cursor [borg content query content://contacts/people {} "_id=810" {}]
which is equivalent to
    set cursor [borg content query content://contacts/people {} "_id=?" 810]
The optional orderby forms the SQL ORDERBY part of the query.
Here's another example demonstrating how data is retrieved:
    set cursor [borg content query content://settings/system]
    # initially, cursor points before first row
    while {[$cursor move 1]} {
        puts [$cursor getrow]
    }

borg content delete uri selection ?value ...?

Deletes rows from an Android content provider given by uri and returns the number of deleted rows. selection forms the SQL WHERE clause of the deletion where question mark parameter markers are substituted by value. Example:
    borg content delete content://settings/system name=? my_item

borg content insert uri key value ...

Inserts a row into an Android content provider given by uri and returns another URI which identifies the inserted row. key and value are pairs of column name and column value for the SQL INSERT operation. Example:
    borg content insert content://settings/system name my_item value "Some value"
    -> content://settings/system/4711

borg content update uri values ?selection ?args??

Updates zero or more rows of an Android content provider given by uri and returns the number of updated rows. values is a list made up of a sequence of column names and column values. selection is the optional SQL WHERE clause with question mark parameter markers. The parameter markers are substituted by the values from args. Example:
    # system settings wants the name in the URI
    borg content update content://settings/system/my_item {value {New Value}}

Cursors from Android Content queries

When a borg content query returned a cursor token, this token is a Tcl command to deal with the query's result set:

$cursor close

Finishes the query and deletes the Tcl command.

$cursor columnnames

Returns a list of column names of the result set.

$cursor count

Returns the number of rows of the result set.

$cursor getblob index

Returns the indexth column (zero-based) of the current row of the result set as a base64 encoded string.

$cursor getdouble index

Returns the indexth column (zero-based) of the current row of the result set as a floating point number.

$cursor getint index

Returns the indexth column (zero-based) of the current row of the result set as a integer number.

$cursor getpos

Returns the index of the current row (zero-based).

$cursor getrow

Returns the current row as a Tcl list made up of column names and values, like {name1 value1 name2 value2} in the order specified by the cursor's constructor. Blobs from the result set are converted into base64 encoded strings.

$cursor getstring index

Returns the indexth column (zero-based) of the current row of the result set as a string.

$cursor isnull index

Returns true when the indexth column (zero-based) of the current row of the result set is an SQL NULL value.

$cursor move pos

Relative move of the current row index. Negative pos goes backward.

$cursor moveto pos

Absolute move of the current row index.

Speech Recognition

borg speechrecognition intent args cmd

Use the speech recognition service. args is a parameter list to control the speech recognition (more information). cmd is invoked when the speech recognition is complete. That procedure receives the parameters retcode and data as in the callback for borg activity. data is a list of key value pairs suited for array set or dict create.

borg speechrecognition callback cmd

Establishes cmd as global callback procedure receiving speech recognition events as described by the RecognitionListener interface (more information). That procedure receives the parameters retcode and data as in the callback for borg activity. data is a list of key value pairs suited for array set or dict create. There are up to two special keys present in data: type giving the event type (one of result, partialresult, ready, event. rms, end, begin) and value giving numeric values for certain event types (error code for error, audio level for rms).

borg speechrecognition start args

Starts the speech recognition. For args see the description in borg speechrecognition intent .....

borg speechrecognition cancel

Immediately cancels the speech recognition. No further events are reported through the global callback procedure.

borg speechrecognition stop

Stops the speech recognition. Events can be still reported through the global callback procedure.

Telephone-Related Commands

borg phoneinfo

Returns information about the current state of the telephone as a list suited for array set or dict create. This information is only available when the application manifest has the android.permission.READ_PHONE_STATE permission (which is left out in current AndroWish releases). For further information see the Android documentation on the classes TelephonyManager, PhoneStateListener, and SignalStrength.

borg sendsms phonenumber msg ?action_send action_delivered smsc?

Sends an SMS text message msg to phonenumber. The optional arguments action_send and action_delivered are the action names of broadcast intents which are generated on state changes regarding the SMS message and can be captured by a broadcast listener callback (see borg broadcast register et.al.). The optional argument smsc is the SMS message center. The command returns 1 on successful start of the send operation, 0 otherwise. It is only available when the application manifest has the android.permission.SEND_SMS permission (which is left out in current AndroWish releases). For further information see the Android documentation on the class SmsManager.

Broadcast

borg broadcast list ?action?

Returns a list of all registered broadcast handlers in the interpreter when action is omitted. Otherwise it returns the command to be invoked when the broadcast action is received.

borg broadcast register action cmd

Registers the command cmd to be invoked when the broadcast action is received.

borg broadcast unregister action

Unregisters the command bound to the reception of the broadcast action.

borg broadcast send action ?uri type categories arguments?

Sends the broadcast action with the optional properties/arguments uri, type, categories, and arguments. For the optional items see the description in borg activity.

Locale

borg locale ?default?

Returns information about the current default locale of the JVM. The result is in a form suitable for array set or dict get and contains the fields country, display_country, display_language, display_name, display_variant, iso3_country, iso3_language, language, and variant.

borg locale lang

Returns information about the locale identified by lang, which must be specified as a two letter code with an optional variant and an optional encoding part, e.g. de, fr_BE, or en_GB.UTF-8.

borg locale tts

Returns information about the locale used for text-to-speech. If text-to-speech facilities weren't used when the command is invoked, the returned information is identical with borg locale default.

borg locale set lang

Changes the current locale of the JVM to the language code lang. If the locale change succeeded, the environment variable env(LANG) is changed accordingly.

Camera-Related Commands

Camera support is available on devices with Android 3.0 or newer.

borg camera close

Close the camera. Returns non-zero on success, zero otherwise, e.g. when the camera was already closed.

borg camera current

Returns the currently opened camera number or -1 when the camera is not opened. On many tablets camera 0 is the back-facing camera, and camera 1 the front-facing one.

borg camera grayimage ?photo?
borg camera greyimage ?photo?

Copies the most recent camera preview as grey image into the photo image identified by photo. Returns non-zero on success or zero if no data transfer has taken place. If photo is omitted, a four element list is returned with the first element being the image width, the second the image height, the third the number of bytes per pixel, and the last the image's grey values with 1 byte per pixel as a byte array. In this case an error is indicated by throwing an exception. An experimental feature is direct rendering into a widget. In this case the photo parameter must be the path name of a Tk window which should be a frame or toplevel widget. When the camera is started the background color of the widget should be set to an empty string so that no drawing calls from Tk are carried out. When the camera is stopped, it should be set to black.

borg camera image ?photo?

Copies the most recent camera preview as color image into the photo image identified by photo. Returns non-zero on success or zero if no data transfer has taken place. If photo is omitted, a four element list is returned with the first element being the image width, the second the image height, the third the number of bytes per pixel, and the last the image's RGB values with 3 bytes per pixel in red, green, blue order as a byte array. In this case an error is indicated by throwing an exception. An experimental feature is direct rendering into a widget. In this case the photo parameter must be the path name of a Tk window which should be a frame or toplevel widget. When the camera is started the background color of the widget should be set to an empty string so that no drawing calls from Tk are carried out. When the camera is stopped, it should be set to black.

borg camera info

Returns information about the currently opened camera as a two element list made up of integer numbers. The first is the rotation of the camera relative to the screen, the second an indication for front-facing (1) or back-facing (0) view of the camera relative to the screen. If no camera is opened the result is an empty list.

borg camera jpeg

Returns a JPEG image of the camera as a byte array after preview has been started using borg camera start and JPEG capture has been initiated with borg camera takejpeg. In contrast to borg camera image ... this command consumes the image. If no JPEG picture is available when the command is invoked, an error is thrown.

borg camera mirror ?x y?

Controls mirroring of preview images which are mirrored along the X axis when x is one and along the Y axis when y is one. borg camera mirror 0 1 is useful to mirror the preview image of a front-facing camera.

borg camera numcameras

Returns the number of available cameras.

borg camera open ?num?

Opens camera number num and returns non-zero on success. Only one camera can be opened at any one time. On error or when a camera is already opened, zero is returned. When num is omitted the first camera is opened (usually the back-facing if two cameras are available).

borg camera orientation ?degrees?

Returns the current orientation of the preview image relative to the screen or changes it to degrees.

borg camera parameters ?key value ...?

Returns or changes camera parameters given as key-value pairs, e.g. preview-size 320x240 will change the size of preview images to width 320 and height 240. The command returns the current camera parameters (after the potential change, when keys and values where given) as a key-value list which can be processed with array set or dict get.

borg camera start

Starts the camera. Acquired preview images are reported by the virtual event <<ImageCapture>>. Returns non-zero on success, zero when the camera is already started or an error has been detected. When the acquisition of camera preview images is running borg camera image or borg camera greyimage must be invoked within 5 seconds, otherwise image acquisition is automatically stopped and needs to be restarted with another borg camera start command.

borg camera state

Returns the current camera state as string: unknown, closed, stopped, or capture.

borg camera stop

Stops the camera, i.e. no more images are acquired. Returns non-zero on success, zero when the camera is already stopped or an error has been detected.

borg camera takejpeg

Requests the camera to take a JPEG image. It is required that the camera is capturing, i.e. borg camera start has been called already. The point in time when acquisition of the JPEG image starts is indicated by the virtual event <<Shutter>>. When the JPEG image is ready for processing the virtual event <<PictureTaken>> is sent. The command returns a non-zero value when JPEG capture is in progress, zero on error.

NFC Related

Many devices have hardware support for NFC (Near Field Communication) tags. In order to deal with such items, a callback command for the broadcast tk.tcl.wish.nfc must be registered. The callback's arguments contain information on the NFC tag in these keys:

android.nfc.extra.ID

The the base64 encoded ID of the tag.

android.nfc.extra.TAG

The underlying/supported technologies of the tag as a string. Currently only android.nfc.tech.Ndef and android.nfc.tech.NdefFormatable are detected and handled.

android.nfc.extra.NDEF_MESSAGES

If present contains the NDEF formatted information contained in the tag encoded in base64.

The last read tag ID is remembered and can be dealt with using these borg subcommands:

borg ndefread tagid ?cached?

Returns the current or cached NDEF formatted information contained in the tag given tagid as base64 encoded string.

borg ndefwrite tagid ndefmsg

Writes the NDEF formatted information (one or more NDEF records) in ndefmsg which must be base64 encoded into the tag given tagid.

borg ndefformat tagid ndefmsg

Formats an empty tag and like borg ndefwrite writes NDEF formatted information into the tag. An unformatted tag can be detected in the tk.tcl.wish.nfc callback procedure by inspecting the technology information: The string android.nfc.tech.Ndef is absent but the string android.nfc.tech.NdefFormatable is present.

OS Environment

Information provided by the android.os.Environment class.

borg osenvironment datadir

Return the user data directory (see getDataDirectory).

borg osenvironment downloadcachedir

Return the download/cache content directory (see getDownloadCacheDirectory).

borg osenvironment externalstoragedir

Return the primary shared/external storage directory (see getExternalStorageDirectory).

borg osenvironment externalstoragepublicdir ?type?

Get a top-level shared/external storage directory for placing files of a particular type (see getExternalStoragePublicDirectory). The parameter type can be obtained by using information returned from borg queryfields android.os.Environment.

borg osenvironment externalstoragestate

Returns the current state of the primary shared/external storage media (see getExternalStorageState).

borg osenvironment isexternalstorageemulated

Returns whether the primary shared/external storage media is emulated (see isExternalStorageEmulated).

borg osenvironment isexternalstorageremovable

Returns whether the primary shared/external storage media is physically removable (see isExternalStorageRemovable).

borg osenvironment rootdir

Return root of the "system" partition holding the core Android OS (see getRootDirectory).

Shared Preferences

An interface to android.content.SharedPreferences is provided using the borg sharedpreferences subcommand. This allows to load/store typed values of an application in a key-value store which does not require extra file permissions.

borg sharedpreferences file getboolean key default

Return a boolean value (using default if not present) from the shared preference file identified by file stored under the name key.

borg sharedpreferences file getfloat key default

Return a floating point value (using default if not present) from the shared preference file identified by file stored under the name key.

borg sharedpreferences file getint key default

Return an integer value (using default if not present) from the shared preference file identified by file stored under the name key.

borg sharedpreferences file getlong key default

Return a 64 bit integer value (using default if not present) from the shared preference file identified by file stored under the name key.

borg sharedpreferences file getstring key default

Return a string value (using default if not present) from the shared preference file identified by file stored under the name key.

borg sharedpreferences file setboolean key value

Store the boolean value into the shared preference file identified by file under the name key.

borg sharedpreferences file setfloat key value

Store the floating point value into the shared preference file identified by file under the name key.

borg sharedpreferences file setint key value

Store the integer value into the shared preference file identified by file under the name key.

borg sharedpreferences file setlong key value

Store the 64 bit integer value into the shared preference file identified by file under the name key.

borg sharedpreferences file setstring key value

Store the string value into the shared preference file identified by file under the name key.

borg sharedpreferences file remove key

Remove the value stored under the name key from the shared preference file identified by file.

borg sharedpreferences file clear

Remove all key-value pairs stored in the shared preference file identified by file.

borg sharedpreferences file all

Return a Tcl list suitable for array set of all key-value pairs from the shared preference file identified by file.

borg sharedpreferences file alltypes

Return a Tcl list suitable for array set of all keys and their respective value types from the shared preference file identified by file.

borg sharedpreferences file keys

Return a Tcl list of all keys from the shared preference file identified by file.

General

borg withdraw

Hides the application window by putting it to the end of Android's activity stack. Can be useful when bound to the Back key (<Key-Break> in AndroWish). There's no opposite command, i.e. the application can be brought to front again only by user interaction.

borg brightness ?percent?

Sets or gets the screen brightness. If the percentage is negative, the default value is restored.

borg onintent ?command?

Sets or gets the callback command which is evaluated when the application received an Android intent. When evaluating that command, the parameters action name, URI, MIME type, categories, arguments from the intent are appended. When the callback is set for the first time, it gets immediately evaluated with the parameters of the current (startup) intent.

borg queryactivites action ?uri type categories component?

Queries Android's activity manager for activities on the given intent parameters. categories and component are optional lists. The latter when non-empty must contain the two elements package name and class name.

borg queryservices action ?uri type categories component?

Queries Android's activity manager for services on the given intent parameters, similar to borg queryactivities.

borg querybroadcastreceivers action ?uri type categories component?

Queries Android's activity manager for broadcast receivers on the given intent parameters, similar to borg queryactivities.

borg screenorientation ?orient?

Queries or switches the screen orientation, orient can be one of unspecified, landscape, portrait, user, behind, sensor, nosensor, sensorlandscape, sensorportrait, reverselandscape, reverseportrait, fullsensor, userlandscape, userportrait, fulluser, or locked.

borg keyboardinfo

Returns information about the current keyboard configuration as a list suited for array set or dict create with these fields: keyboard with possible values none, 12key, and qwerty, hidden and hard_hidden with values 0 (not hidden), 1, (hidden), and -1 (unknown). This can be read out any time. An update in keyboard configuration state is indicated by the virtual event <<KeyboardInfo>>.

borg alarm clear action ?uri type categories component?

Clears an alarm whose pattern matches the given intent parameters.

borg alarm set when repeat action ?uri type categories component arg ...?

Sets an alarm to fire at when (UN*X epoch, seconds) with repetition each repeat seconds, when repeat is greater than 0. The alarm sends an intent made up of the given intent parameters (action etc.). The component parameter is interpreted specially: when empty no component is set on the intent, when given as self the calling package/class is set as component for the intent (sending the intent to itself, i.e. the callback of borg onintent will receive it). In all other cases component must be a list with the two elements package name and class name. arg and following parameters are added to the intent as key value pairs of extra data.

borg alarm wakeup when repeat action ?uri type categories component arg ...?

Like borg alarm set but this type of alarm is able to wake up the device when suspended (device behavior depends on lock screen settings).

borg activity action uri type ?categories ?component ?arguments ?callback????

This a very flexible command that allows extensive access to the Android OS and other applications. categories, component, and arguments are optional lists. callback is the name of the procedure that is evaluated when the activity action is complete. arguments are key-value pairs where the values are mapped to Java strings by default. If the key is a 2-element list made up of a data type indicator (int, byte, short, char, long, float, double, Uri) followed by the key, the value is converted to that data type. See below for some examples of this command.

borg systemui ?flags?

Returns or sets various flags to control certain aspects of system UI elements displayed on the device's screen. This is currently supported only on Android 4.4 and newer versions. See the documentation on android.view.View for a description of the SYSTEM_UI_* flags.

Events

These events are generated for/by certain borg related commands. They are reported to toplevel widgets only.

<<LocationUpdate>>

Location information has been updated and can be read out using borg location get.

<<GPSUpdate>>

GPS related information has been updated and can be read out using borg location gps and borg location satellites.

<<NMEAUpdate>>

NMEA data has been updated and can be read out using borg location nmea.

<<NetworkInfo>>

Network state has changed and can be read out using borg networkinfo.

<<TetherInfo>>

Tethering state has changed and can be read out using borg tetherinfo.

<<Bluetooth>>

A change in Bluetooth state and/or scan mode has occured and can be read out using borg bluetooth state and/or borg bluetooth scanmode.

<<SensorUpdate>>

A sensor can be read using borg sensor get .... The field %x identifies the sensor.

<<KeyboardInfo>>

The keyboard configuration did change and can be obtained by borg keyboardinfo.

<<PhoneCallState>>

The call state of the telephone has changed and can be obtained by borg phoneinfo.

<<PhoneDataActivity>>

The state of the telephone's data state has changed and can be obtained by borg phoneinfo.

<<PhoneConnectionState>>

The state of the telephone's connectivity has changed and can be obtained by borg phoneinfo.

<<PhoneServiceState>>

The service state of the telephone has changed and can be obtained by borg phoneinfo.

<<PhoneSignalStrength>>

The signal quality of the telephone has changed and can be obtained by borg phoneinfo.

<<ImageCapture>>

A preview camera image is ready and can be obtained by borg camera image photo or borg camera greyimage photo. The field %x represents the camera capture state (true when preview images are captured, false when capture will be stopped).

<<Shutter>>

The camera is about to take a JPEG image.

<<PictureTaken>>

The camera has taken a JPEG picture which can be obtained and consumed by borg camera jpeg. When the event is reported, image capture of preview images is automatically stopped.

<<USBAttached>>

A USB device was attached. To find out information about the device, use the borg usbdevices command. This event is generated on Android 4.4 and newer.

<<USBDetached>>

An USB device was detached (opposite of <<USBAttached>>).

<<TTSInit>>

The text-to-speech facility has been started up or shut down. The %x substitution gives an indication for startup (=0), error (=-1), and unavailability (<-1). Supported in Android 4.1 and higher.

<<TTSStart>>

Speech output of a string has started. The %x substitution is equal to the integer returned by the corresponding borg speak command. Supported in Android 4.1 and higher.

<<TTSError>>

Error indication for a string to be spoken by borg speak. The %x substitution is equal to the integer returned by the corresponding borg speak command as for the <<TTSStart>> event. Supported in Android 4.1 and higher.

<<TTSDone>>

End of speech indication for a string to be spoken. The %x substitution is equal to the integer returned by the corresponding borg speak command as for the <<TTSStart>> event. Supported in Android 4.1 and higher.

borg activity Examples

Sample code to open a browser on the Tcl'ers wiki:

    borg activity android.intent.action.VIEW http://wiki.tcl.tk text/html

Sample code to launch the "wifi settings" page:

    borg activity android.settings.WIFI_SETTINGS {} {} {} {} {}

Sample code to update the Androwish application from its APK:

    borg activity android.intent.action.VIEW "file:///sdcard/androwish.apk" application/vnd.android.package-archive

Sample code to capture an image (only makes thumbnails):

    proc callback {retcode action uri mimetype categories data} {
        if {$retcode == -1} {
            # SUCCESS
            array set result $data
            if {[info exists result(data)]} {
                myphoto configure -data $result(data)
            }
        }
    }
    package require Img
    image create photo myphoto
    borg activity android.media.action.IMAGE_CAPTURE {} {} {} {} {} callback

Sample code to capture an image, which makes full size images but requires a file on for transfer:

    proc callback {filename retcode action uri mimetype categories data} {
        if {$retcode == -1} {
            # SUCCESS
            myphoto configure -file $filename
            catch {file delete -force $filename}
        }
    }
    package require Img
    image create photo myphoto
    set filename [file join $env(TMPDIR) myphoto.jpg]
    set filecontent \\
        content://[file join $env(PACKAGE_NAME).fileprovider cache myphoto.jpg]
    borg activity android.media.action.IMAGE_CAPTURE {} {} {} {} \\
        [list {Uri output} $filecontent] [list callback $filename]

Reading barcodes using the ZXing barcode scanner (which needs to be be installed on your device):

    proc barcode_read {code action uri type cat data} {
        array set result $data
        if {[info exists result(SCAN_RESULT)]} {
            # that is the barcode
            # result(SCAN_RESULT_FORMAT) is the barcode format
        }
    }

    borg activity com.google.zxing.client.android.SCAN {} {} {} {} {} barcode_read