Copies elements from SrcArray to DestArray. SrcArray - Source array. SrcOffset - Index of first element in the source array. DestArray - Destination array. DestOffset - Index of the first element in the destination array. Count - Number of elements to copy.
Date and time related methods. DateTime is a predefined object. You should not declare it yourself. Date and time values are stored as ticks. Ticks are the number of milliseconds since January 1, 1970 00:00:00 UTC. This value is too large to be stored in an Int variable. It should only be stored in a Long variable. The methods DateTime.Date and DateTime.Time convert the ticks value to a string. You can get the current time with DateTime.Now. Example: DimnowAsLong now = DateTime.Now Msgbox("The date is: " & DateTime.Date(now) & CRLF & _
"The time is: " & DateTime.Time(now), "")
Returns a ticks value which is the result of adding the specified time spans to the given ticks value. Pass negative values if you want to subtract the values. Example: DimTomorrowAsLong Tomorrow = DateTime.Add(DateTime.Now, 0, 0, 1)
Log("Tomorrow date is: " & DateTime.Date(Tomorrow))
Date (TicksAsLong) AsString
Returns a string representation of the date (which is stored as ticks). The date format can be set with the DateFormat keyword. Example: Log("Today is: " & DateTime.Date(DateTime.Now))
DateFormatAsString
Gets or sets the format used to parse date strings. See this page for the supported patterns: formats. The default pattern is MM/dd/yyyy (04/23/2002 for example).
DateParse (DateAsString) AsLong
Parses the given date string and returns its ticks representation. An exception will be thrown if parsing fails. Example: DimSomeTimeAsLong SomeTime = DateTime.DateParse("02/23/2007")
DateTimeParse (DateAsString, TimeAsString) AsLong
Parses the given date and time strings and returns the ticks representation.
DeviceDefaultDateFormatAsString [read only]
Returns the default date format based on the device selected language.
DeviceDefaultTimeFormatAsString [read only]
Returns the default time format based on the device selected language.
GetDayOfMonth (TicksAsLong) AsInt
Returns the day of month component from the ticks value. Values are between 1 to 31.
GetDayOfWeek (TicksAsLong) AsInt
Returns the day of week component from the ticks value. Values are between 1 to 7, where 1 means Sunday. You can use the AHLocale library if you need to change the first day.
GetDayOfYear (TicksAsLong) AsInt
Returns the day of year component from the ticks value. Values are between 1 to 366.
GetHour (TicksAsLong) AsInt
Returns the hour of day component from the ticks value. Values are between 0 to 23.
GetMinute (TicksAsLong) AsInt
Returns the minutes within a hour component from the ticks value. Values are between 0 to 59.
GetMonth (TicksAsLong) AsInt
Returns the month of year component from the ticks value. Values are between 1 to 12.
GetSecond (TicksAsLong) AsInt
Returns the seconds within a minute component from the ticks value. Values are between 0 to 59.
GetTimeZoneOffsetAt (DateAsLong) AsDouble
Returns the offset measured in hours from UTC at the specified date (offset can change due to daylight saving settings).
GetYear (TicksAsLong) AsInt
Returns the year component from the ticks value.
ListenToExternalTimeChanges
Creates a dynamic broadcast receiver that listens to the "time-zone changed" event and "time set" event. By calling this method the time-zone will update automatically when the device time-zone changes. DateTime_TimeChanged event will be raised when the time-zone changes or when the time is set.
NowAsLong [read only]
Gets the current time as ticks (number of milliseconds since January 1, 1970).
SetTimeZone (OffsetHoursAsDouble)
Sets the application time zone. This setting affect the conversions of dates to ticks value and vice versa (device default settings are not changed).
TicksPerDayAsLong
TicksPerHourAsLong
TicksPerMinuteAsLong
TicksPerSecondAsLong
Time (TicksAsLong) AsString
Returns a string representation of the time (which is stored as ticks). The time format can be set with the TimeFormat keyword. Example: Log("The time now is: " & DateTime.Time(DateTime.Now))
TimeFormatAsString
Gets or sets the format used to parse time strings. See this page for the supported patterns: formats. The default pattern is HH:mm:ss (23:45:12 for example).
TimeParse (TimeAsString) AsLong
Parses the given time string and returns its ticks representation. Note that the returned value date will be today.
TimeZoneOffsetAsDouble [read only]
Returns the current offset measured in hours from UTC.
Holds a thrown exception. You can access the last thrown exception by calling LastException. For example: Try DiminAsInputStream in = File.OpenInput(File.DirInternal, "SomeMissingFile.txt")
'... Catch Log(LastException.Message)
EndTry Ifin.IsInitializedThenin.Close
Intent objects are messages which you can send to the OS in order to do some external action. The Intent object should be sent with StartActivity keyword. See this page for a list of standard constants. Example, launch YouTube application: DimIntent1AsIntent Intent1.Initialize(Intent1.ACTION_MAIN, "")
Intent1.SetComponent("com.google.android.youtube/.HomeActivity")
StartActivity(Intent1)
Adds a category describing the intent required operation.
ExtrasToStringAsString
Returns a string containing the extra items. This is useful for debugging.
FlagsAsInt
Gets or sets the flags component.
GetDataAsString
Retrieves the data component as a string.
GetExtra (NameAsString) AsObject
Returns the item value with the given key.
HasExtra (NameAsString) AsBoolean
Tests whether an item with the given key exists.
Initialize (ActionAsString, UriAsString)
Initializes the object using the given Action and data Uri. Action can be one of the action constants or any other string. Pass an empty string if a Uri is not required.
Initialize2 (UriAsString, FlagsAsInt)
Initializes the object by parsing the Uri. Flags - Additional integer value. Pass 0 if it is not required. Example: DimIntent1AsIntent Intent1.Initialize2("http://www.basic4ppc.com", 0)
StartActivity(Intent1)
IsInitializedAsBoolean
PutExtra (NameAsString, ValueAsObject)
Adds extra data to the intent.
SetComponent (ComponentAsString)
Explicitly sets the component that will handle this intent.
SetPackage (PackageNameAsString)
Explicitly sets the package name of the target application.
SetType (TypeAsString)
Sets the MIME type. Example: Intent1.SetType("text/plain")
WrapAsIntentChooser (TitleAsString)
Wraps the intent in another "chooser" intent. A dialog will be displayed to the user with the available services that can act on the intent. WrapAsIntentChooser should be the last method called before sending the intent.
Creates a single dimension array of the specified type. The syntax is: Array [As type] (list of values). If the type is ommitted then an array of objects will be created. Example: DimDays() AsString Days = ArrayAsString("Sunday", "Monday", ...)
Asc (CharAsChar) AsInt
Returns the unicode code point of the given character or first character in string.
Decodes the given bytes array as a string. Data - The bytes array. StartOffset - The first byte to read. Length - Number of bytes to read. CharSet - The name of the character set. Example: DimsAsString s = BytesToString(Buffer, 0, Buffer.Length, "UTF-8")
CallSub (ComponentAsObject, SubAsString) AsObject
Calls the given sub. CallSub can be used to call a sub which belongs to a different module. However the sub will only be called if the other module is not paused. In that case an empty string will be returned. You can use IsPaused to test whether a module is paused. This means that one activity cannot call a sub of a different activity. As the other activity will be paused for sure. CallSub allows an activity to call a service sub or a service to call an activity sub. Note that it is not possible to call subs of code modules. CallSub can also be used to call subs in the current module. Pass Me as the component in that case. Example: CallSub(Main, "RefreshData")
Similar to CallSub. Calls a sub with two arguments.
CallSubDelayed (ComponentAsObject, SubAsString)
CallSubDelayed is a combination of StartActivity, StartService and CallSub. Unlike CallSub which only works with currently running components, CallSubDelayed will first start the target component if needed. CallSubDelayed can also be used to call subs in the current module. Instead of calling these subs directly, a message will be sent to the message queue. The sub will be called when the message is processed. This is useful in cases where you want to do something "right after" the current sub (usually related to UI events). Note that if you call an Activity while the whole application is in the background (no visible activities), the sub will be executed once the target activity is resumed.
Similar to CallSubDelayed. Calls a sub with two arguments.
CancelScheduledService (ServiceAsObject)
Cancels previously scheduled tasks for this service.
Catch
Any exception thrown inside a try block will be caught in the catch block. Call LastException to get the caught exception. Syntax: Try ... Catch ... End Try
cEAsDouble
e (natural logarithm base) constant.
Ceil (NumberAsDouble) AsDouble
Returns the smallest double that is greater or equal to the specified number and is equal to an integer.
Creates a RemoteViews object based on the layout file. The compiler will generate the required XML files based on the parameters. See the widgets tutorial for more information: Widgets tutorial. Note that all parameters must be strings or numbers as they are read by the compiler. LayoutFile - The widget layout file. EventName - Sets the subs that will handle the RemoteViews events. UpdateIntervalMinutes - Sets the update interval. Pass 0 to disable automatic updates. Minimum value is 30 (or 0). WidgetName - The name of the widget as appears in the widgets list. CenterWidget - Whether to center the widget.
Continue
Stops executing the current iteration and continues with the next one.
Cos (RadiansAsDouble) AsDouble
Calculates the trigonometric cosine function. Angle measured in radians.
CosD (DegreesAsDouble) AsDouble
Calculates the trigonometric cosine function. Angle measured in degrees.
cPIAsDouble
PI constant.
CreateMap
Creates a Map with the given key / value pairs. The syntax is: CreateMap (key1: value1, key2: value2, ...) Example: DimmAsMap = CreateMap("January": 1, "February": 2)
CRLFAsString
New line character. The value of Chr(10).
DensityAsFloat
Returns the device scale, which is DPI / 160. (DPI stands for dots per inch).
Dim
Declares a variable. Syntax: Declare a single variable: Dim variable name [As type] [= expression] The default type is String.
Declare multiple variables. All variables will be of the specified type. Dim [Const] variable1 [= expression], variable2 [= expression], ..., [As type] Note that the shorthand syntax only applies to Dim keyword. Example:Dima = 1, b = 2, c = 3AsInt
Declare an array: Dim variable(Rank1, Rank2, ...) [As type] Example:DimDays(7) AsString The actual rank can be omitted for zero length arrays.
DipToCurrent (LengthAsInt) AsInt
Scales the value, which represents a specific length on a default density device (Density = 1.0), to the current device. For example, the following code will set the width value of this button to be the same physical size on all devices. Button1.Width = DipToCurrent(100)
Note that a shorthand syntax for this method is available. Any number followed by the string 'dip' will be converted in the same manner (no spaces are allowed between the number and 'dip'). So the previous code is equivalent to: Button1.Width = 100dip 'dip -> density independent pixel
DoEvents
DoEvents is deprecated. It can lead to stability issues. Consider using Sleep(0) instead.
Exit
Exits the most inner loop. Note that Exit inside a Select block will exit the Select block.
ExitApplication
Immediately ends the application and stops the process. Most applications should not use this method and prefer Activity.Finish which lets the OS decide when the process is killed.
FalseAsBoolean
FileAsFile
Files related methods.
Floor (NumberAsDouble) AsDouble
Returns the largest double that is smaller or equal to the specified number and is equal to an integer.
For
Syntax: For variable = value1 To value2 [Step interval] ... Next If the iterator variable was not declared before it will be of type Int.
Or: For Each variable As type In collection ... Next Examples: Fori = 1To10 Log(i) 'Will print 1 to 10 (inclusive). Next ForEachnAsIntInNumbers'an array Sum = Sum + n Next
Note that the loop limits will only be calculated once before the first iteration.
GetDeviceLayoutValuesAsLayoutValues
Returns the device LayoutValues.
Example: Log(GetDeviceLayoutValues)
GetType (objectAsObject) AsString
Returns a string representing the object's java type.
If
Single line: If condition Then true-statement [Else false-statement] Multiline: If condition Then statement Else If condition Then statement ... Else statement End If
Shows a modal dialog with a list of items and radio buttons. Pressing on an item will close the dialog. Returns the index of the selected item or DialogResponse.Cancel if the user pressed on the back key. It is recommended to use InputListAsync instead. List - Items to display. Title - Dialog title. CheckedItem - The index of the item that will first be selected. Pass -1 if no item should be preselected.
Shows a non-modal dialog with a list of items and radio buttons. Pressing on an item will close the dialog. Returns the index of the selected item or DialogResponse.Cancel if the user pressed on the back key. The InputList_Result event will be raised with the result. List - Items to display. Title - Dialog title. CheckedItem - The index of the item that will first be selected. Pass -1 if no item should be preselected. Cancelable - If true then the dialog can be canceled by clicking on the back key or outside the dialog. The object returned can be used as the Sender Filter parameter of Wait For. Example: DimoptionsAsList = Array("Red", "Green", "Blue")
InputListAsync(options, "Select Color", 0, False)
WaitForInputList_Result (IndexAsInt)
IfIndex <> DialogResponse.CANCELThen Log("Selected color: " & options.Get(Index))
EndIf
InputMap (ItemsAsMap, TitleAsCharSequence)
Shows a modal dialog with a list of items and checkboxes. The user can select multiple items. The dialog is closed by pressing on the "Ok" button. The InputMap_Result event will be raised. It is recommended to use InputMapAsync instead. The items displayed are the map keys. Items with a value of True will be checked. When the user checks or unchecks an item, the related item value gets updated. Items - A map object with the items as keys and their checked state as values.
Shows a non-modal dialog with a list of items and checkboxes. The user can select multiple items. The dialog is closed by pressing on the "Ok" button. The object returned can be used as the Sender Filter parameter of Wait For. The items displayed are the map keys. Items with a value of True will be checked. When the user checks or unchecks an item, the related item value gets updated. Items - A map object with the items as keys and their checked state as values. Cancelable - If true then the dialog can be closed by clicking on the back key or outside the dialog (the changes will not be canceled). Example: DimmAsMap = CreateMap("Item #1": True, "Item #2": True, "Item #3": False)
InputMapAsync(m, "Select items", True)
WaitForInputMap_Result Log(m)
Shows a modal dialog with a list of items and checkboxes. The user can select multiple items. The dialog is closed by pressing on the "Ok" button. Returns a list with the indices of the selected items. The list is sorted. Returns an empty list if the user has pressed on the back key.
Is
Tests whether the object is of the given type. Example: Fori = 0ToActivity.NumberOfViews - 1 IfActivity.GetView(i) IsButtonThen DimbAsButton b = Activity.GetView(i)
b.Color = Colors.Blue EndIf Next
Tests whether a background task, submitted by the container object and with the specified id, is running.
IsDevTool (ToolNameAsString) AsBoolean
Returns true if ToolName equals B4A.
IsNumber (TextAsString) AsBoolean
Tests whether the specified string can be safely parsed as a number.
IsPaused (ComponentAsObject) AsBoolean
Tests whether the given component is paused. Will also return true for components that were not started yet. Example: IfIsPaused(Main) = FalseThenCallSub(Main, "RefreshData")
LastExceptionAsException
Returns the last exception that was caught (if such exists).
Loads the bitmap. Note that the Android file system is case sensitive. You should consider using LoadBitmapSample if the image size is large. The actual file size is not relevant as images are usually stored compressed. Example: Activity.SetBackgroundImage(LoadBitmap(File.DirAssets, "SomeFile.jpg"))
Loads the bitmap and sets its size. The bitmap scale will be the same as the device scale. Unlike LoadBitmapSample which requires the container Gravity to be set to FILL, LoadBitmapResize provides better results when the Gravity is set to CENTER. Example: DimbdAsBitmapDrawable = Activity.SetBackgroundImage(LoadBitmapResize(File.DirAssets, "SomeFile.jpg", 100%x, 100%y, True))
bd.Gravity = Gravity.CENTER Or: Activity.SetBackgroundImage(LoadBitmapResize(File.DirAssets, "SomeFile.jpg", 100%x, 100%y, True)).Gravity = Gravity.CENTER
Loads the bitmap. The decoder will subsample the bitmap if MaxWidth or MaxHeight are smaller than the bitmap dimensions. This can save a lot of memory when loading large images. In most cases it is better to use LoadBitmapResize. Example: Activity.SetBackgroundImage(LoadBitmapSample(File.DirAssets, "SomeFile.jpg", Activity.Width, Activity.Height))
Log (MessageAsString)
Logs a message. The log can be viewed in the Logs tab.
Logarithm (NumberAsDouble, BaseAsDouble) AsDouble
LogColor (MessageAsString, ColorAsInt)
Logs a message. The message will be displayed in the IDE with the specified color.
Max (Number1AsDouble, Number2AsDouble) AsDouble
Returns the larger number between the two numbers.
MeAsObject
For classes: returns a reference to the current instance. For activities and services: returns a reference to an object that can be used with CallSub, CallSubDelayed and SubExists keywords. Cannot be used in code modules.
Min (Number1AsDouble, Number2AsDouble) AsDouble
Returns the smaller number between the two numbers.
Shows a modal message box with the specified message and title. The dialog will show one OK button. It is recommended to use MsgboxAsync instead. Note that services cannot show dialogs. Example: Msgbox("Hello world", "This is the title")
Shows a modal message box with the specified message and title. It is recommended to use Msgbox2Async instead. Message - The dialog message. Title - The dialog title. Positive - The text to show for the "positive" button. Pass "" to hide the button. Cancel - The text to show for the "cancel" button. Pass "" to hide the button. Negative - The text to show for the "negative" button. Pass "" to hide the button. Icon - A bitmap that will be drawn near the title. Pass Null to hide hide the icon. Returns one of the DialogResponse values. Example: DimresultAsInt result = Msgbox2("This is the message", "This is the title", "Good", "", "Bad", LoadBitmap(File.DirAssets, "smiley.gif"))
Ifresult = DialogResponse.PositiveThen ...
Shows a non-modal message box with the specified message and title. The Msgbox_Result event will be raised with the result. Message - The dialog message. Title - The dialog title. Positive - The text to show for the "positive" button. Pass "" to hide the button. Cancel - The text to show for the "cancel" button. Pass "" to hide the button. Negative - The text to show for the "negative" button. Pass "" to hide the button. Icon - A bitmap that will be drawn near the title. Pass Null to hide hide the icon. Cancelable - If true then the dialog can be canceled by clicking on the back key or outside the dialog. The object returned can be used as the Sender Filter parameter of Wait For. Example: Msgbox2Async("Question?", "Title", "Yes", "Cancel", "No", Null, False)
WaitForMsgbox_Result (ResultAsInt)
IfResult = DialogResponse.POSITIVEThen '... EndIf
Shows a non-modal message box with the specified message and title. The dialog will show one OK button. Note that services cannot show dialogs. You can use Wait For to wait for the Msgbox_Result event if you want to continue the code flow after the dialog is dismissed. Example: MsgboxAsync("Hello world", "This is the title")
Converts the specified number to a string. The string will include at least Minimum Integers and at most Maximum Fractions digits. Example: Log(NumberFormat(12345.6789, 0, 2)) '"12,345.68" Log(NumberFormat(1, 3 ,0)) '"001"
Converts the specified number to a string. The string will include at least Minimum Integers, at most Maximum Fractions digits and at least Minimum Fractions digits. GroupingUsed - Determines whether to group every three integers. Example: Log(NumberFormat2(12345.67, 0, 3, 3, false)) '"12345.670"
PerXToCurrent (PercentageAsFloat) AsInt
Returns the actual size of the given percentage of the activity width. Example: Button1.Width = PerXToCurrent(50) 'Button1.Width = 50% * Activity.Width
A shorthand syntax for this method is available. Any number followed by the string '%x' will be converted in the same manner (no spaces are allowed between the number and '%x'). So the previous code is equivalent to: Button1.Width = 50%x
PerYToCurrent (PercentageAsFloat) AsInt
Returns the actual size of the given percentage of the activity height. Example: Button1.Height = PerYToCurrent(50) 'Button1.Height = 50% * Activity.Height
A shorthand syntax for this method is available. Any number followed by the string '%y' will be converted in the same manner (no spaces are allowed between the number and '%y'). So the previous code is equivalent to: Button1.Height = 50%y
Power (BaseAsDouble, ExponentAsDouble) AsDouble
Returns the Base value raised to the Exponent power.
ProgressDialogHide
Hides a visible progress dialog. Does not do anything if no progress dialog is visible.
ProgressDialogShow (TextAsCharSequence)
Shows a dialog with a circular spinning bar and the specified text. Unlike Msgbox and InputList methods, the code will not block. You should call ProgressDialogHide to remove the dialog. The dialog will also be removed if the user presses on the Back key.
Shows a dialog with a circular spinning bar and the specified text. Unlike Msgbox and InputList methods, the code will not block. You should call ProgressDialogHide to remove the dialog. Cancelable - Whether the user can dismiss the dialog by pressing on the Back key.
QUOTEAsString
Quote character. The value of Chr(34).
RegexAsRegex
Regular expressions related methods.
Return
Returns from the current sub and optionally returns the given value. Syntax: Return [value]
Rnd (MinAsInt, MaxAsInt) AsInt
Returns a random integer between Min (inclusive) and Max (exclusive).
RndSeed (SeedAsLong)
Sets the random seed value. This method can be used for debugging as it allows you to get the same results each time.
Round (NumberAsDouble) AsLong
Returns the closest long number to the given number.
Rounds the given number and leaves up to the specified number of fractional digits.
Select
Compares a single value to multiple values. Example: DimvalueAsInt value = 7 Selectvalue Case1 Log("One")
Case2, 4, 6, 8 Log("Even")
Case3, 5, 7, 9 Log("Odd larger than one")
CaseElse Log("Larger than 9")
EndSelect
SenderAsObject
Returns the object that raised the event. Only valid while inside the event sub. Example: SubButton_Click DimbAsButton b = Sender b.Text = "I've been clicked" EndSub
Sin (RadiansAsDouble) AsDouble
Calculates the trigonometric sine function. Angle measured in radians.
SinD (DegreesAsDouble) AsDouble
Calculates the trigonometric sine function. Angle measured in degrees.
Sleep (MillisecondsAsInt)
Pauses the current sub execution and resumes it after the specified time.
Internal keyword used by the Smart String literal.
Sqrt (ValueAsDouble) AsDouble
Returns the positive square root.
StartActivity (ActivityAsObject)
Starts an activity or brings it to front if it already exists. The target activity will be started once the program is free to process its message queue. Activity can be a string with the target activity name or it can be the actual activity. After this call the current activity will be paused and the target activity will be resumed. This method can also be used to send Intents objects to the system. Note that you should usually not call StartActivity from a Service. Example: StartActivity (Activity2)
StartService (ServiceAsObject)
Starts the given service. The service will be first created if it was not started before. The target service will be started once the program is free to process its message queue. Note that you cannot show a Msgbox after this call and before the service starts. Service - The service module or the service name. Example: StartService(SQLService)
Schedules the given service to start at the given time. Service - The service module. Pass Me when calling from a service module that schedules itself. Time - The time to start the service. If this time has already past the service will be started now. The actual delivery time might change to reduce battery usage. Use StartServiceAtExact if the exact time is important. DuringSleep - Whether to start the service when the device is sleeping. If set to false and the device is sleeping at the specified time, the service will be started when the device wakes up. Setting DuringSleep to True can have a large impact on the battery usage. StartServiceAt can be used to schedule a repeating task. You should call it under Service_Start to schedule the next task. This call cancels previous scheduled tasks (for the same service). Example: StartServiceAt(SQLService, DateTime.Now + 30 * 1000, false) 'will start after 30 seconds.
Same as StartServiceAt for Android versions up to 4.3 (API 18). On Android 4.4+ it forces the OS to start the service at the exact time. This method will have a larger impact on the battery compared to StartServiceAt and should only be used in cases where it is important for the service to start at the exact time.
StopService (ServiceAsObject)
Stops the given service. Service_Destroy will be called. Call StartService afterwards will first create the service. Service - The service module or service name. Pass empty string to stop the current service (from the service module). Example: StopService(SQLService)
Sub
Declares a sub with the parameters and return type. Syntax: Sub name [(list of parameters)] [As return-type] Parameters include name and type. The lengths of arrays dimensions should not be included. Example: SubMySub (FirstNameAsString, LastNameAsString, AgeAsInt, OtherValues() AsDouble) AsBoolean ...
EndSub In this example OtherValues is a single dimension array. The return type declaration is different than other declarations as the array parenthesis follow the type and not the name (which does not exist in this case).
SubExists (ObjectAsObject, SubAsString) AsBoolean
Tests whether the object includes the specified method. Returns false if the object was not initialized or not an instance of a user class.
TABAsString
Tab character.
Tan (RadiansAsDouble) AsDouble
Calculates the trigonometric tangent function. Angle measured in radians.
TanD (DegreesAsDouble) AsDouble
Calculates the trigonometric tangent function. Angle measured in degrees.
Shows a quick little message that goes out automatically. Message - The text message to show. LongDuration - If true then shows the message for a long period, otherwise shows the message for a short period.
TrueAsBoolean
Try
Any exception thrown inside a try block will be caught in the catch block. Call LastException to get the caught exception. Syntax: Try ... Catch ... End Try
Type
Declares a structure. Can only be used inside sub Globals or sub Process_Globals. Syntax: Type type-name (field1, field2, ...) Fields include name and type. Example: TypeMyType (NameAsString, Items(10) AsInt)
Dima, bAsMyType a.Initialize a.Items(2) = 123
Until
Loops until the condition is true. Syntax: Do Until condition ... Loop
While
Loops while the condition is true. Syntax: Do While condition ... Loop
Holds values related to the display. You can get the values of the the current display by calling GetDeviceLayoutValues. For example: DimlvAsLayoutValues lv = GetDeviceLayoutValues Log(lv) 'will print the values to the log Activity.LoadLayout and Panel.LoadLayout return a LayoutValues object with the values of the chosen layout variant.
A status bar notification. The user can open the notifications screen and press on the notification. Pressing on the notification will start an activity as set by the notification object. Notifications are usually used by services as services are not expected to directly start activities. The notification must have an icon and its "info" must be set. Example: DimnAsNotification n.Initialize n.Icon = "icon" n.SetInfo("This is the title", "and this is the body.", Main) 'Change Main to "" if this code is in the main module. n.Notify(1)
Sets whether the notification will be canceled automatically when the user clicks on it.
Cancel (IdAsInt)
Cancels the notification with the given Id.
IconAsString [write only]
Sets the icon displayed. The icon value is the name of the image file without the extension. The name is case sensitive. The image file should be manually copied to the following folder: source folder\Objects\res\drawable. You can use "icon" to use the application icon (which is also located in this folder): n.Icon = "icon"
IMPORTANCE_DEFAULTAsInt
Default notification importance: shows everywhere, makes noise, but does not visually intrude.
IMPORTANCE_HIGHAsInt
Higher notification importance: shows everywhere, makes noise and peeks. May use full screen intents.
IMPORTANCE_LOWAsInt
Low notification importance: shows everywhere, but is not intrusive.
IMPORTANCE_MINAsInt
Minimum notification importance: only shows in the shade, below the fold. Cannot be used with foreground services.
Initialize
Initializes the notification. By default the notification plays a sound, shows a light and vibrates the phone.
Initialize2 (ImportanceLevelAsInt)
Initializes the notification and sets the notification channel importance level. Note that the importance level only affect Android 8+ devices. DimnoAsNotification no.Initialize2(no.IMPORTANCE_DEFAULT)
InsistentAsBoolean [write only]
Sets whether the sound will play repeatedly until the user opens the notifications screen.
IsInitializedAsBoolean
LightAsBoolean [write only]
Sets whether the notification will show a light. Example: n.Light = False
Notify (IdAsInt)
Displays the notification. Id - The notification id. This id can be used to later update this notification (by calling Notify again with the same Id), or to cancel the notification.
NumberAsInt
Gets or sets a number that will be displayed on the icon. This is useful to represent multiple events in a single notification.
OnGoingEventAsBoolean [write only]
Sets whether this notification is an "ongoing event". The notification will be displayed in the ongoing section and it will not be cleared.
Sets the message text and action. Title - The message title. Body - The message body. Activity - The activity to start when the user presses on the notification. Pass an empty string to start the current activity (when calling from an activity module). Example: n.SetInfo("Some title", "Some text", Main)
Similar to SetInfo. Also sets a string that can be later extracted in Activity_Resume. Title - The message title. Body - The message body. Tag - An arbitrary string that can be later extract when the user clicks on the notification. Activity - The activity to start when the user presses on the notification. Pass an empty string to start the current activity (when calling from an activity module). Example of extracting the tag: SubActivity_Resume DiminAsIntent in = Activity.GetStartingIntent Ifin.HasExtra("Notification_Tag") Then Log(in.GetExtra("Notification_Tag")) 'Will log the tag EndIf EndSub
SoundAsBoolean [write only]
Sets whether the notification will play a sound. Example: n.Sound = False
VibrateAsBoolean [write only]
Sets whether the notification will vibrate. Example: n.Vibrate = False
Each Service module includes a Service object. This object is used to bring the service in and out of the foreground state. See the Services tutorial for more information.
Always enter foreground mode when the service is started. This is useful when you want to make sure that the OS doesn't kill the process until the task completes.
AUTOMATIC_FOREGROUND_NEVERAsInt
Never enter automatic foreground mode. This means that you must handle it yourself to avoid the app from crashing.
AUTOMATIC_FOREGROUND_WHEN_NEEDEDAsInt
Automatic foreground mode will be set when needed. This will only happen on Android 8+ devices when the service is started while the app is in the background.
AutomaticForegroundModeAsInt
Sets the automatic foreground mode. It should be one of the AUTOMATIC_FOREGROUND constants. Default value is AUTOMATIC_FOREGROUND_WHEN_NEEDED. Should be set in Service_Create.
Brings the current service to the foreground state and displays the given notification. Id - The notification Id (see the notification object documentation). Notification - The notification that will be displayed.
StopAutomaticForeground
Stops the automatic foreground state. Does nothing if the service was not in that state. You can call this method at the end of the background task as an alternative to calling StopService(Me).
StopForeground (IdAsInt)
Takes the current service out of the foreground state and cancels the notification with the given Id.
Strings are immutable in Basic4android, which means that you can change the value of a string variable but you cannot change the text stored in a string object. So methods like SubString, Trim and ToLowerCase return a new string, they do not change the value of the current string. Typical usage: DimsAsString s = "some text" s = s.Replace("a", "b") You can use StringBuilder if you need a mutable string. Note that string literals are also string objects: Log(" some text ".Trim)
Lexicographically compares the two strings. Returns a value less than 0 if the current string precedes Other. Returns 0 if both strings are equal. Returns a value larger than 0 if the current string comes after Other. Note that upper case characters precede lower case characters.
Tests whether the string contains the given string parameter.
EndsWith (SuffixAsString) AsBoolean
Returns true if this string ends with the given Suffix.
EqualsIgnoreCase (otherAsString) AsBoolean
Returns true if both strings are equal ignoring their case.
GetBytes (CharsetAsString) AsByte()
Encodes the string into a new array of bytes. Example: DimData() AsByte Data = "Some string".GetBytes("UTF8")
IndexOf (SearchForAsString) AsInt
Returns the index of the first occurrence of SearchFor string in the string. Returns -1 if SearchFor was not found.
IndexOf2 (SearchForAsString, IndexAsInt) AsInt
Returns the index of the first occurrence of SearchFor string in the string. Starts searching from the given Index. Returns -1 if SearchFor was not found.
LastIndexOf (SearchForAsString) AsInt
Returns the index of the first occurrence of SearchFor string in the string. The search starts at the end of the string and advances to the beginning.
Returns a new string resulting from the replacement of all the occurrences of Target with Replacement.
StartsWith (PrefixAsString) AsBoolean
Returns true if this string starts with the given Prefix.
SubString (BeginIndexAsInt) AsString
Returns a new string which is a substring of the original string. The new string will include the character at BeginIndex and will extend to the end of the string.
Returns a new string which is a substring of the original string. The new string will include the character at BeginIndex and will extend to the character at EndIndex, not including the last character.
Example: "012345".SubString2(2, 4) 'returns "23"
ToLowerCaseAsString
Returns a new string which is the result of lower casing this string.
ToUpperCaseAsString
Returns a new string which is the result of upper casing this string.
TrimAsString
Returns a copy of the original string without any leading or trailing white spaces.
StringBuilder is a mutable string, unlike regular strings which are immutable. StringBuilder is especially useful when you need to concatenate many strings. The following code demonstrates the performance boosting of StringBuilder: DimstartAsLong start = DateTime.Now 'Regular string DimsAsString Fori = 1To5000 s = s & i Next Log(DateTime.Now - start)
'StringBuilder start = DateTime.Now DimsbAsStringBuilder sb.Initialize Fori = 1To5000 sb.Append(i)
Next Log(DateTime.Now - start) Tested on a real device, the first 'for loop' took about 20 seconds and the second took less then tenth of a second. The reason is that the code: s = s & i creates a new string each iteration (strings are immutable). The method StringBuilder.ToString converts the object to a string.
Appends the specified text at the end. Returns the same object, so you can chain methods. Example: sb.Append("First line").Append(CRLF).Append("Second line")
Initialize
Initializes the object. Example: DimsbAsStringBuilder sb.Initialize sb.Append("The value is: ").Append(SomeOtherVariable).Append(CRLF)
A Timer object generates ticks events at specified intervals. Using a timer is a good alternative to a long loop, as it allows the UI thread to handle other events and messages. Note that the timer events will not fire while the UI thread is busy running other code. The timer Enabled property is set to False by default. To make it start working you should change it to True. Timer events will not fire when the activity is paused, or if a blocking dialog (like Msgbox) is visible. Timers should be declared in Sub Process_Globals. Otherwise you may get multiple timers running when the activity is recreated. It is also important to disable the timer when the activity is pausing and then enable it when it resumes. This will save CPU and battery.
Gets or sets whether the timer is enabled (ticking).
Initialize (EventNameAsString, IntervalAsLong)
Initializes the timer with the event sub prefix and the specified interval (measured in milliseconds). IMPORTANT: this object should be declared in Sub Process_Globals. Example: Timer1.Initialize("Timer1", 1000)
Timer1.Enabled = True
SubTimer1_Tick 'Handle tick events EndSub
IntervalAsLong
Gets or sets the interval between tick events, measured in milliseconds.