Press on the image to return to the main documentation page.
Phone
The Phone library changed and several methods belonging to the Phone object have moved to PhoneId and PhoneVibrate. The reason for this change is to avoid adding unnecessary permissions. The Phone library contains all kinds of features related to the Android phone. Phone object includes information about the device and also other general features. PhoneAccelerometer and PhoneOrientation objects are now replaced with PhoneSensors which support other sensors as well. PhoneEvents allows you to handle all kinds of system events. PhoneId gives access to the the specific phone values. PhoneSms supports sending Sms messages. PhoneVibrate vibrates the phone. SmsMessages together with Sms support fetching messages from the phone database. SmsInterceptor intercepts incoming Sms messages. PhoneIntents and PhoneCalls include several useful intents. Email helps with building an Intent that sends an email. PhoneWakeState allows you to force the screen and power to keep on. Contact and Contacts give access to the stored contacts. CallLog and CallItem give access to the phone calls log. ContentChooser allows the user to choose content from other applications. For example the user can choose an image from the Gallery application. VoiceRecognition converts speech to text. LogCat tracks the internal phone logs. PackageManager allows you to retrieve information about the installed applications.
Represents a single contact. The Contacts object should be used to get lists of Contact objects. EMAIL_x constants are the possible email types. PHONE_x constants are the possible phone types.
Contacts object allows you to access the device stored contacts. The following code finds all contacts named John (actually it will find all contacts which their name contains the string "john"), and print their fields to the LogCat. It will also fetch the contact photo if it exists. Example: DimContacts1AsContacts DimlistOfContactsAsList listOfContacts = Contacts1.FindByName("John", False)
Fori = 0TolistOfContacts.Size - 1 DimContactAsContact Contact = listOfContacts.Get(i)
Log(Contact) 'will print the fields to the LogCat DimphotoAsBitmap photo = Contact.GetPhoto Ifphoto <> NullThenActivity.SetBackgroundImage(photo)
DimemailsAsMap emails = Contact.GetEmails Ifemails.Size > 0ThenLog("Email addresses: " & emails)
DimphonesAsMap phones = Contact.GetPhones Ifphones.Size > 0ThenLog("Phone numbers: " & phones)
Next
Returns a List of Contact objects with all contacts matching the given email. Email - The email to search for. Exact - If True then only contacts with the exact email address (case sensitive) will return , otherwise all contacts email addresses that include the Email string will return (case insensitive).
FindByName (NameAsString, ExactAsBoolean) AsList
Returns a List of Contact objects with all contacts matching the given name. Name - The name to search for. Exact - If True then only contacts with the exact name value (case sensitive) will return , otherwise all contacts names that include the Name string will return (case insensitive).
GetAllAsList
Returns a List of Contact objects with all the contacts. This list can be very large.
GetById (IdAsInt) AsContact
Returns the Contact with the specified Id. Returns Null if no matching contact found.
Contacts2 object allows you to access the device stored contacts. This type is based on a new API supported by Android 2.0 and above. This type supersedes Contacts type. The following code finds all contacts named John (actually it will find all contacts which their name contains the string "john"), and print their fields to the LogCat. It will also fetch the contact photo if it exists. Example: DimContacts2AsContacts2 DimlistOfContactsAsList listOfContacts = Contacts2.FindByName("John", False, True, True)
Fori = 0TolistOfContacts.Size - 1 DimContactAsContact Contact = listOfContacts.Get(i)
Log(Contact) 'will print the fields to the LogCat DimphotoAsBitmap photo = Contact.GetPhoto Ifphoto <> NullThenActivity.SetBackgroundImage(photo)
DimemailsAsMap emails = Contact.GetEmails Ifemails.Size > 0ThenLog("Email addresses: " & emails)
DimphonesAsMap phones = Contact.GetPhones Ifphones.Size > 0ThenLog("Phone numbers: " & phones)
Next
Returns a List of Contact objects with all contacts matching the given email. Email - The email to search for. Exact - If True then only contacts with the exact email address (case sensitive) will return , otherwise all contacts email addresses that include the Email string will return (case insensitive).
IncludePhoneNumber - Whether to fetch the default phone number. IncludeNotes - Whether to fetch the notes field.
Returns a List of Contact objects with all contacts matching the given name. Name - The name to search for. Exact - If True then only contacts with the exact name value (case sensitive) will return , otherwise all contacts names that include the Name string will return (case insensitive).
IncludePhoneNumber - Whether to fetch the default phone number. IncludeNotes - Whether to fetch the notes field.
Returns the Contact with the specified Id. Returns Null if no matching contact found. IncludePhoneNumber - Whether to fetch the default phone number. IncludeNotes - Whether to fetch the notes field.
This method is an asynchronous version of GetContactsByQuery. Once the list is ready the Complete event will be raised. The EventName parameter sets the sub that will handle this event.
Returns a list of contacts based on the specified query and arguments. Query - The SQL query. Pass an empty string to return all contacts. Arguments - An array of strings used for parameterized queries. Pass Null if not needed. IncludePhoneNumber - Whether to fetch the phone number for each contact. IncludeNotes - Whether to fetch the notes field for each contact.
The ContentChooser object allows the user to select a specific type of content using other installed applications. For example the user can use the internal Gallery application to select an image. If the user has installed a file manager then the ContentChooser can be used to select general files. This object should usually be declared as a process global object. After initializing the object you can let the user select content by calling Show with the required MIME types. The Result event will be raised with a Success flag and with the content Dir and FileName. Note that these values may point to resources other than regular files. Still you can pass them to methods that expect Dir and FileName. Only content types that can be opened with an InputStream are supported.
Events:
Result (Success As Boolean, Dir As String, FileName As String)
Initializes the object and sets the Sub that will handle the Result event. Example: DimCCAsContentChooser CC.Initialize("CC")
IsInitializedAsBoolean
Show (MimeAsString, TitleAsString)
Sends the request to the system. If there are more than one applications that support the given Mime then a list with the applications will be displayed to the user. The Result event will be raised after the user chose an item or canceled the dialog. Mime - The content MIME type. Title - The title of the chooser dialog (when there is more than one application). Examples: CC.Show("image/*", "Choose image")
CC.Show("audio/*", "Choose audio file")
Using an Email object you can create an intent that holds a complete email message. You can then launch the email application by calling StartActivity. Note that the email will not be sent automatically. The user will need to press on the send button. Example: DimMessageAsEmail Message.To.Add("SomeEmail@example.com")
Message.Attachments.Add(File.Combine(File.DirRootExternal, "SomeFile.txt"))
StartActivity(Message.GetIntent)
LogCat allows you to read the internal phone logs. Refer to the LogCat documentation for more information about the optional arguments. The LogCatData event is raised when there is new data available. You should use BytesToString to convert the raw bytes to string. Note that the LogCatData event is raised in a different thread. This means that you can only log the messages. You can also use the Threading library to delegate the data to the main thread.
The PackageManager allows you to find information about installed applications. Applications are referenced using their package name. You can get a list of all the packages by calling GetInstalledPackages.
Returns an Intent object that can be used to start the given application. Example: DiminAsIntent DimpmAsPackageManager in = pm.GetApplicationIntent("com.google.android.youtube")
Ifin.IsInitializedThenStartActivity(in)
StartActivity(in)
GetApplicationLabel (PackageAsString) AsString
Returns the application label.
GetInstalledPackagesAsList
Returns a list of the installed packages. Example: DimpmAsPackageManager DimpackagesAsList packages = pm.GetInstalledPackages Fori = 0Topackages.Size - 1 Log(packages.Get(i))
Next
Returns a list with the installed activities that can handle the given intent. Each item in the list is the "component name" of an activity. You can use Intent.SetComponent to explicitly choose the activity. The first item is considered the best match. For example, the following code lists all the activities that can "view" a text file: DimpmAsPackageManager DimIntent1AsIntent Intent1.Initialize(Intent1.ACTION_VIEW, "file://")
Intent1.SetType("text/*")
ForEachcnAsStringInpm.QueryIntentActivities(Intent1)
Log(cn)
Next
Returns an internal drawable object. See this page for a list of available resources. Example: DimpAsPhone DimbdAsBitmapDrawable bd = p.GetResourceDrawable(17301618)
Activity.AddMenuItem2("Menu1", "Menu1", bd.Bitmap)
GetRingerModeAsInt
Returns the phone ringer mode. Value will be one of the RINGER constants.
GetSettings (SettingsAsString) AsString
Returns the value of the phone settings based on the given key. The possible keys are listed here. The keys are lower cased. Example: DimpAsPhone Log(GetSettings("android_id"))
GetSimOperatorAsString
Returns the code of the SIM provider. Returns an empty string if it is not available.
GetVolume (ChannelAsInt) AsInt
Returns the volume of the specified channel. Channel - One of the VOLUME constants.
HideKeyboard (ActivityAsActivityWrapper)
Hides the soft keyboard if it is displayed. Example: DimpAsPhone p.HideKeyboard(Activity)
IsAirplaneModeOnAsBoolean
Tests whether the phone "airplane mode" is on.
IsNetworkRoamingAsBoolean
Returns true if the device is considered roaming on the current network.
ManufacturerAsString [read only]
ModelAsString [read only]
ProductAsString [read only]
RINGER_NORMALAsInt
Normal phone ringer mode.
RINGER_SILENTAsInt
Phone ringer will be silent and it will not vibrate.
Sends an intent to all BroadcastReceivers that listen to this type of intents. Example of asking the media scanner to rescan a file: DimiAsIntent i.Initialize("android.intent.action.MEDIA_SCANNER_SCAN_FILE", _
"file://" & File.Combine(File.DirRootExternal, "pictures/1.jpg"))
DimpAsPhone p.SendBroadcastIntent(i)
SetMute (ChannelAsInt, MuteAsBoolean)
Mutes or unmutes the given channel. Channel - One of the VOLUME constants. Mute - Whether to mute or unmute the channel. Starting from Android 7+ this method will throw an exception if the user set the Do Not Disturb mode, unless your app has requested a special permission with NOTIFICATION_POLICY_ACCESS_SETTINGS.
SetRingerMode (ModeAsInt)
Sets the phone ringer mode. Mode - One of the RINGER constants. Starting from Android 7+ this method will throw an exception if the user set the Do Not Disturb mode, unless your app has requested a special permission with NOTIFICATION_POLICY_ACCESS_SETTINGS. Example: DimpAsPhone p.SetRingerMode(p.RINGER_VIBRATE)
SetScreenBrightness (ValueAsFloat)
Sets the brightness of the current activity. This method cannot be called from a service module. Value - A float between 0 to 1. Set -1 for automatic brightness. Example: SubProcess_Globals Dimphone1AsPhone EndSub
Changes the current activity orientation. This method cannot be called from a service module. Orientation - -1 for unspecified, 0 for landscape and 1 for portrait.
Sets the volume of the specified channel. Channel - One of the VOLUME constants. VolumeIndex - The volume index. GetMaxVolume can be used to find the largest possible value. ShowUI - Whether to show the volume UI windows. Starting from Android 7+ this method will throw an exception if the user set the Do Not Disturb mode, unless your app has requested a special permission with NOTIFICATION_POLICY_ACCESS_SETTINGS. Example: DimpAsPhone p.SetVolume(p.VOLUME_MUSIC, 3, True)
Runs a native shell command. Many commands are inaccessible because of OS security restrictions. Calling Shell will block the calling thread until the other process completes. Command - Command to run. Args - Additional arguments. Can be Null if not needed. StdOut - A StringBuilder that will hold the standard output value. Can be Null if not needed. StdErr - A StringBuilder that will hold the standard error value. Can be Null if not needed. Returns the process exit value. Example: DimpAsPhone DimsbAsStringBuilder sb.Initialize p.Shell("df", Null, sb, Null)
Msgbox(sb.ToString, "Free space:")
This object gives access to the internal accelerometers sensors. See the Orientation and accelerometers example. This object should be declared as a process global object.
Events:
AccelerometerChanged (X As Float, Y As Float, Z As Float)
This object creates an intent that launches the phone application. The reason that it is not part of the PhoneIntents library is that it requires an additional permission.
The Android OS sends all kinds of messages to notify applications of changes in the system. The PhoneEvents object allows you to catch such messages and handle those events in your program. Usually you will want to add this object to a Service module instead of an Activity module in order not to miss events that happen while your activity is paused. Working with this object is quite simple. You should declare this object in Sub Process_Globals and initialize it in Sub Service_Create. From now on your declared sub events will handle the events. The Intent object which was sent by the system is passed as the last parameter. The events supported are: AirplaneModeChanged - Raised when the "airplane mode" state changes. State - True when airplane mode is active. BatteryChanged - Raised when the battery status changes. Level - The current level. Scale - The maximum level. Plugged - Whether the device is plugged to an electricity source. ConnectivityChanged - There was a change in the state of the WIFI network or the MOBILE network (other network). NetworkType - WIFI or MOBILE. State - One of the following values: CONNECTING, CONNECTED, SUSPENDED, DISCONNECTING, DISCONNECTED, UNKNOWN. DeviceStorageLow - The device internal memory condition is low. DeviceStorageOk - The device internal low memory condition no longer exists. PackageAdded - An application was installed. Package - The application package name. PackageRemoved - An application was uninstalled. Package - The application package name. PhoneStateChanged - The phone state has changed. State - One of the three values: IDLE, OFFHOOK, RINGING. OFFHOOK means that there is a call or that the phone is dialing. IncomingCall - Available when the State value is RINGING. ScreenOff - The screen has turned off. ScreenOn - The screen has turned on. Shutdown - The phone is shutting down (turned off not just sleeping). SmsDelivered - An Sms message sent by your application was delivered to the recipient. PhoneNumber - The target phone number. SmsSentStatus - Raised after your application sends an Sms message. Success - Whether the message was sent successfully. ErrorMessage - One of the following values: GENERIC_FAILURE, NO_SERVICE, RADIO_OFF, NULL_PDU or OK. PhoneNumber - The target phone number. TextToSpeechFinish - The Text To Speech engine has finished processing the messages in the queue. UserPresent - The user has unlocked the keyguard screen.
Events:
AirplaneModeChanged (State As Boolean, Intent As Intent) BatteryChanged (Level As Int, Scale As Int, Plugged As Boolean, Intent As Intent) ConnectivityChanged (NetworkType As String, State As String, Intent As Intent) DeviceStorageLow (Intent As Intent) DeviceStorageOk (Intent As Intent) PackageAdded (Package As String, Intent As Intent) PackageRemoved (Package As String, Intent As Intent) PhoneStateChanged (State As String, IncomingNumber As String, Intent As Intent) ScreenOff (Intent As Intent) ScreenOn (Intent As Intent) SmsDelivered (PhoneNumber As String, Intent As Intent) SmsSentStatus (Success As Boolean, ErrorMessage As String, PhoneNumber As String, Intent As Intent) Shutdown (Intent As Intent) TextToSpeechFinish (Intent As Intent) UserPresent (Intent As Intent)
Initializes the object and starts listening for events. The PhoneStateEvent will also be handled. Example: DimPhoneIdAsPhoneId DimPEAsPhoneEvents PE.InitializeWithPhoneState("PE", PhoneId)
StopListening
Stops listening for events. You can later call Initialize to start listening for events again.
This object contains methods that create intents objects. An intent does nothing until you call StartActivity with the intent. Calling StartActivity sends the intent to the OS.
This object gives access to the internal orientation sensors. See the Orientation and accelerometers example. This object should be declared as a process global object.
Events:
OrientationChanged (Azimuth As Float, Pitch As Float, Roll As Float)
The PhoneSensors object allows you to listen for changes in one of the device sensors. See the Sensors example. Most devices do not support all sensors. The StartListening method returns False if the sensor is not supported. After initializing the object and calling StartListening, the SensorChanged event will be raised each time the sensor value changes. The value is passed as an array of Floats. Some sensors pass a single value and some pass three values.
Returns the event accuracy, between 0 (unreliable) to 3 (maximum accuracy).
Initialize (SensorTypeAsInt)
Initializes the object and sets the sensor type (one of the TYPE_ constants).
Initialize2 (SensorTypeAsInt, SensorDelayAsInt)
Initializes the object and sets the sensor type and sensor events rate. SensorType - One of the TYPE_ constants. SensorDelay - A value between 1 (fastest rate) to 3 (slowest rate). This is only a hint to the system.
MaxValueAsFloat [read only]
Returns the maximum value for this sensor. Returns -1 if this sensor is not supported.
StartListening (EventNameAsString) AsBoolean
Starts listening for sensor events. Returns True if the sensor is supported. Usually you will want to start listening in Sub Activity_Resume and stop listening in Sub Activity_Pause.
StopListening
Stops listening for events.
TimestampAsLong [read only]
Returns the event timestamp measured in nanoseconds. Note that the actual value has different meanings on different devices. Thus it should only be used to compare between sensor events.
TYPE_ACCELEROMETERAsInt
Three values - Acceleration measured in Meters / Second ^ 2 for each axis (X, Y and Z).
TYPE_GYROSCOPEAsInt
Three values - Angular velocity measured in Radians / Second around each of the three axis.
TYPE_LIGHTAsInt
Single value - Ambient light level measured in SI lux units.
TYPE_MAGNETIC_FIELDAsInt
Three values - Ambient magnetic field measured in micro-Tesla for the X, Y and Z axis.
TYPE_ORIENTATIONAsInt
Three values - Orientation measured in degrees for azimuth, pitch and roll.
TYPE_PRESSUREAsInt
Single value - Atmospheric pressure.
TYPE_PROXIMITYAsInt
Single value - Proximity measured in centimeters. Most devices will return only two possible values representing "near" and "far". "far" should match MaxRange and "near" should be a value smaller than MaxRange.
Sends an Sms message. Note that this method actually sends the message (unlike most other methods that create an intent object). You can use PhoneEvents to handle the SmsSentStatus and SmsDelivered events. This method is equivalent to calling Send2(PhoneNumber, Text, True, True).
Sends an Sms message. Note that this method actually sends the message (unlike most other methods that create an intent object). You can use PhoneEvents to handle the SmsSentStatus and SmsDelivered events. ReceiveSentNotification - If true then the SmsSentStatus event (PhoneEvents) will be raised when the message is sent. ReceiveDeliveredNotification - If true then the SmsDelivered event (PhoneEvents) will be raised when the message is delivered. Note that the two above notifications might incur an additional payment.
The PhoneWakeState object allows you to prevent the device from turning off the screen. Once you call KeepAlive the phone screen will stay on till you call ReleaseKeepAlive. It is important to eventually release it. A recommended usage is to call KeepAlive in Activity_Resume and call ReleaseKeepAlive in Activity_Pause. Note that the user can still turn off the screen by pressing on the power button. Calling PartialLock will prevent the CPU from going to sleep even if the user presses on the power button. It will not however affect the screen.
Prevents the device from going to sleep. Call ReleaseKeepAlive to release the power lock. BrightScreen - Whether to keep the screen bright or dimmed.
PartialLock
Acquires a partial lock. This will prevent the CPU from going to sleep, even if the user presses on the power button. Make sure to call ReleasePartialLock eventually to release this lock.
ReleaseKeepAlive
Releases the power lock and allows the device to go to sleep.
ReleasePartialLock
Releases a partial lock that was previously acquired by calling PartialLock.
The RingtoneManager object allows you to set or get the default ringtone. It also provides access to the default ringtone picker. The RingtoneResult event will be raised when the picker is closed with the Uri of the selected ringtone. Note that an empty string will be returned if the "Silence" option was selected. Example of playing the selected ringtone with MediaPlayer: SubProcess_Globals PrivatermAsRingtoneManager EndSub
Adds a sound file to the internal media store and return the Uri to the new entry. Dir - The file folder. Should be a folder under the storage card (public folder). FileName - The file name. Title - The entry title. IsAlarm - Whether this entry should be added to the alarms sounds list. IsNotification - Whether this entry should be added to the notifications sounds list. IsRingtone - Whether this entry should be added to the ringtones sounds list. IsMusic - Whether this entry should be added to the music list.
Returns a string that represents the virtual content folder. This can be used to play a Ringtone with MediaPlayer.
GetDefault (TypeAsInt) AsString
Returns the Uri of the default ringtone of a specific type. Returns an empty string if no default is available. Use Play to play the ringtone.
Play (UriAsString)
Plays a ringtone Uri.
SetDefault (TypeAsInt, UriAsString)
Sets the default ringtone for the given type. In order to get the Uri you should use AddToMediaStore (for new sounds) or ShowRingtonePicker (for existing sounds).
Shows the ringtone picker activity. The PickerResult will be raised after the user selects a ringtone. EventName - Sets the sub that will handle the PickerResult event. Type - Defines the type(s) of sounds that will be listed. Multiple types can be set using Bit.Or. IncludeSilence - Whether to include the Silence option in the list. ChosenRingtone - The uri of the ringtone that will be selected when the dialog opens. Pass an empty string if not needed.
The id of the person who sent the message. Will be -1 if this data is missing. You can find more information about this person by calling Contacts.GetById.
ReadAsBoolean
Whether this message has been read.
ThreadIdAsInt
Thread id.
TypeAsInt
The message type. One of the SmsMessages constant values.
Listens for incoming SMS messages. The MessageReceived event is raised when a new message arrives. Returning True from the MessageReceived event will cause the broadcasted message to be aborted. This can be used to prevent the message from reaching the standard SMS application. However in order for your application to receive the message before other applications you should use Initialize2 and set the priority value to a value larger than 0. It should be 999 according to the Android documentation.
Permissions:
android.permission.RECEIVE_SMS
Events:
MessageReceived (From As String, Body As String) As Boolean MessageSent (MessageId As Int)
Initializes the object and starts listening for new messages.
Initialize2 (EventNameAsString, PriorityAsInt)
Initializes the object and starts listening for new messages. The last parameter defines the application priority compared to other applications that listen to incoming messages. You should set it to 999 according to the official Android documentation in order to receive the message first. It is however possible that a third party application has used a higher value.
ListenToOutgoingMessages
Listens to outgoing messages. MessageSent event will be raised when a message is sent. You can call SmsMessages.GetByMessageId to retrieve the message.
StopListening
Stops listening for events. You can later call Initialize to start listening again.
Provides access to the stored SMS messages. Note that you can use PhoneSms to send SMS messages. Example of printing all messages from the last week: DimSmsMessages1AsSmsMessages DimList1AsList List1 = SmsMessages1.GetAllSince(DateTime.Add(DateTime.Now, 0, 0, -7))
Fori = 0ToList1.Size - 1 DimSmsAsSms Sms = List1.Get(i)
Log(Sms)
Next
Most Android devices support voice recognition (speech to text). Usually the service works by sending the audio stream to some external server which analyzes the stream and returns the possible results. Working with this object is quite simple. You should declare a VoiceRecognition object as a process global object and initialize it in Activity_Create when FirstTime is True. Later when you call Listen a dialog will be displayed, asking the user to speak. The Result event will be raised with a Success flag and a list with the possible results (usually one result).