Android Programming 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.

List of types:

CallItem
CallLog
Contact
Contacts
Contacts2
ContentChooser
Email
LogCat
PackageManager
Phone
PhoneAccelerometer
PhoneCalls
PhoneEvents
PhoneId
PhoneIntents
PhoneOrientation
PhoneSensors
PhoneSms
PhoneVibrate
PhoneWakeState
RingtoneManager
Sms
SmsInterceptor
SmsMessages
VoiceRecognition

CallItem

Represents a single call in the call logs. See CallLog for more information.

Events:

None

Members:


  CachedName As String

  CallType As Int

  Date As Long

  Duration As Long

  Id As Int

  Number As String

  TYPE_INCOMING As Int

  TYPE_MISSED As Int

  TYPE_OUTGOING As Int

Members description:

CachedName As String
Returns the cached name assigned to this call number at the time of call.
Returns an empty string if no name was assigned.
CallType As Int
The call type. This value matches one of the TYPE constants.
Date As Long
The call date measured as ticks.
Duration As Long
The call duration in seconds.
Id As Int
The call internal id.
Number As String
The call phone number.
TYPE_INCOMING As Int
TYPE_MISSED As Int
TYPE_OUTGOING As Int

CallLog

CallLog allows you to browse the call logs.
Retrieved calls are always ordered by descending date.
Usage example:
Dim Calls As List
Dim CallLog As CallLog
calls = CallLog.GetAll(10) 'Get the last 10 calls
For i = 0 To calls.Size - 1
  Dim c As CallItem
  c = calls.Get(i)
  Dim callType, name As String
  Select c.CallType
    Case c.TYPE_INCOMING
      callType="Incoming"
    Case c.TYPE_MISSED
      callType = "Missed"
    Case c.TYPE_OUTGOING
      callType = "Outgoing"
  End Select
  name = c.CachedName
  If name = "" Then name = "N/A"
  Log("Number=" & c.Number & ", Name=" & name _
    & ", Type=" & callType & ", Date=" & DateTime.Date(c.Date))
Next

Permissions:

android.permission.READ_CONTACTS
android.permission.READ_CALL_LOG

Events:

None

Members:


  GetAll (Limit As Int) As List

  GetById (Id As Int) As CallItem

  GetSince (Date As Long, Limit As Int) As List

Members description:

GetAll (Limit As Int) As List
Returns all calls ordered by date (descending) as a List of CallItems.
Limit - Maximum number of CallItems to return. Pass 0 to return all items.
GetById (Id As Int) As CallItem
Returns the CallItem with the specified Id.
Returns Null if no matching CallItem found.
GetSince (Date As Long, Limit As Int) As List
Returns all CallItems with a date value larger than the specified value.
Limit - Maximum number of items to return. Pass 0 to return all items.

Contact

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.

Events:

None

Members:


  DisplayName As String

  EMAIL_CUSTOM As Int

  EMAIL_HOME As Int

  EMAIL_MOBILE As Int

  EMAIL_OTHER As Int

  EMAIL_WORK As Int

  GetEmails As Map

  GetPhones As Map

  GetPhoto As BitmapWrapper

  Id As Int

  LastTimeContacted As Long

  Name As String

  Notes As String

  PHONE_CUSTOM As Int

  PHONE_FAX_HOME As Int

  PHONE_FAX_WORK As Int

  PHONE_HOME As Int

  PHONE_MOBILE As Int

  PHONE_OTHER As Int

  PHONE_PAGER As Int

  PHONE_WORK As Int

  PhoneNumber As String

  Starred As Boolean

  TimesContacted As Int

Members description:

DisplayName As String
The displayed name. Equals to the Name if the Name is not empty, otherwise equals to the contacts first email address.
EMAIL_CUSTOM As Int
EMAIL_HOME As Int
EMAIL_MOBILE As Int
EMAIL_OTHER As Int
EMAIL_WORK As Int
GetEmails As Map
Returns a Map with the contacts email addresses as keys and the email types as values.
This call executes an additional query.
GetPhones As Map
Returns a Map with all the contacts phone numbers as keys and the phone types as values.
This call executes an additional query.
GetPhoto As BitmapWrapper
Returns the contact photo or Null if there is no attached photo.
This call executes an additional query.
Id As Int
Internal Id.
LastTimeContacted As Long
Last time that this contact was contacted. Value is a ticks value.
Name As String
Contact name.
Notes As String
PHONE_CUSTOM As Int
PHONE_FAX_HOME As Int
PHONE_FAX_WORK As Int
PHONE_HOME As Int
PHONE_MOBILE As Int
PHONE_OTHER As Int
PHONE_PAGER As Int
PHONE_WORK As Int
PhoneNumber As String
Primary phone number.
Starred As Boolean
Whether this contact is a "favorite" contact.
TimesContacted As Int
Number of times that this contact was contacted.

Contacts

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:
Dim Contacts1 As Contacts
Dim listOfContacts As List
listOfContacts = Contacts1.FindByName("John", False)
For i = 0 To listOfContacts.Size - 1
  Dim Contact As Contact
  Contact = listOfContacts.Get(i)
  Log(Contact) 'will print the fields to the LogCat
  Dim photo As Bitmap
  photo = Contact.GetPhoto
  If photo <> Null Then Activity.SetBackgroundImage(photo)
  Dim emails As Map
  emails = Contact.GetEmails
  If emails.Size > 0 Then Log("Email addresses: " & emails)
  Dim phones As Map
  phones = Contact.GetPhones
  If phones.Size > 0 Then Log("Phone numbers: " & phones)
Next

Permissions:

android.permission.READ_CONTACTS

Events:

None

Members:


  FindByMail (Email As String, Exact As Boolean) As List

  FindByName (Name As String, Exact As Boolean) As List

  GetAll As List

  GetById (Id As Int) As Contact

Members description:

FindByMail (Email As String, Exact As Boolean) As List
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 (Name As String, Exact As Boolean) As List
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).
GetAll As List
Returns a List of Contact objects with all the contacts. This list can be very large.
GetById (Id As Int) As Contact
Returns the Contact with the specified Id.
Returns Null if no matching contact found.

Contacts2

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:
Dim Contacts2 As Contacts2
Dim listOfContacts As List
listOfContacts = Contacts2.FindByName("John", False, True, True)
For i = 0 To listOfContacts.Size - 1
Dim Contact As Contact
Contact = listOfContacts.Get(i)
Log(Contact) 'will print the fields to the LogCat
Dim photo As Bitmap
photo = Contact.GetPhoto
If photo <> Null Then Activity.SetBackgroundImage(photo)
Dim emails As Map
emails = Contact.GetEmails
If emails.Size > 0 Then Log("Email addresses: " & emails)
Dim phones As Map
phones = Contact.GetPhones
If phones.Size > 0 Then Log("Phone numbers: " & phones)
Next

Permissions:

android.permission.READ_CONTACTS

Events:

Complete (ListOfContacts As List)

Members:


  FindByMail (Email As String, Exact As Boolean, IncludePhoneNumber As Boolean, IncludeNotes As Boolean) As List

  FindByName (Name As String, Exact As Boolean, IncludePhoneNumber As Boolean, IncludeNotes As Boolean) As List

  GetAll (IncludePhoneNumber As Boolean, IncludeNotes As Boolean) As List

  GetById (Id As Int, IncludePhoneNumber As Boolean, IncludeNotes As Boolean) As Contact

  GetContactsAsync (EventName As String, Query As String, Arguments() As String, IncludePhoneNumber As Boolean, IncludeNotes As Boolean)

  GetContactsByQuery (Query As String, Arguments() As String, IncludePhoneNumber As Boolean, IncludeNotes As Boolean) As List

Members description:

FindByMail (Email As String, Exact As Boolean, IncludePhoneNumber As Boolean, IncludeNotes As Boolean) As List
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.
FindByName (Name As String, Exact As Boolean, IncludePhoneNumber As Boolean, IncludeNotes As Boolean) As List
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.
GetAll (IncludePhoneNumber As Boolean, IncludeNotes As Boolean) As List
Returns a List of Contact objects with all the contacts. This list can be very large.
GetById (Id As Int, IncludePhoneNumber As Boolean, IncludeNotes As Boolean) As Contact
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.
GetContactsAsync (EventName As String, Query As String, Arguments() As String, IncludePhoneNumber As Boolean, IncludeNotes As Boolean)
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.
GetContactsByQuery (Query As String, Arguments() As String, IncludePhoneNumber As Boolean, IncludeNotes As Boolean) As List
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.

ContentChooser

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)

Members:


  Initialize (EventName As String)

  IsInitialized As Boolean

  Show (Mime As String, Title As String)

Members description:

Initialize (EventName As String)
Initializes the object and sets the Sub that will handle the Result event.
Example:
Dim CC As ContentChooser
CC.Initialize("CC")
IsInitialized As Boolean
Show (Mime As String, Title As String)
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")

Email

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:
Dim Message As Email
Message.To.Add("SomeEmail@example.com")
Message.Attachments.Add(File.Combine(File.DirRootExternal, "SomeFile.txt"))
StartActivity(Message.GetIntent)

Events:

None

Members:


  Attachments As List

  BCC As List

  Body As String

  CC As List

  GetHtmlIntent As android.content.Intent

  GetIntent As android.content.Intent

  Subject As String

  To As List

Members description:

Attachments As List
BCC As List
Body As String
CC As List
GetHtmlIntent As android.content.Intent
Returns the Intent that should be sent with StartActivity.
The email message will be a Html message.
GetIntent As android.content.Intent
Returns the Intent that should be sent with StartActivity.
Subject As String
To As List

LogCat

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.

Events:

LogCatData (Buffer() As Byte, Length As Int)

Members:


  LogCatStart (Args() As String, EventName As String)

  LogCatStop

Members description:

LogCatStart (Args() As String, EventName As String)
Starts tracking the logs.
Args - Optional arguments passed to the internal LogCat command.
EventName - The Sub that will handle the LogCatData event.
LogCatStop
Stops tracking the logs.

PackageManager

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.

Events:

None

Members:


  GetApplicationIcon (Package As String) As android.graphics.drawable.Drawable

  GetApplicationIntent (Package As String) As IntentWrapper

  GetApplicationLabel (Package As String) As String

  GetInstalledPackages As List

  GetVersionCode (Package As String) As Int

  GetVersionName (Package As String) As String

  QueryIntentActivities (Intent As android.content.Intent) As List

Members description:

GetApplicationIcon (Package As String) As android.graphics.drawable.Drawable
Returns the application icon.
Example:
Dim pm As PackageManager
Activity.Background = pm.GetApplicationIcon("com.google.android.youtube")
GetApplicationIntent (Package As String) As IntentWrapper
Returns an Intent object that can be used to start the given application.
Example:
Dim in As Intent
Dim pm As PackageManager
in = pm.GetApplicationIntent("com.google.android.youtube")
If in.IsInitialized Then StartActivity(in)
StartActivity(in)
GetApplicationLabel (Package As String) As String
Returns the application label.
GetInstalledPackages As List
Returns a list of the installed packages.
Example:
Dim pm As PackageManager
Dim packages As List
packages = pm.GetInstalledPackages
For i = 0 To packages.Size - 1
  Log(packages.Get(i))
Next
GetVersionCode (Package As String) As Int
Returns the application version code.
GetVersionName (Package As String) As String
Returns the application version name.
QueryIntentActivities (Intent As android.content.Intent) As List
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:
Dim pm As PackageManager
Dim Intent1 As Intent
Intent1.Initialize(Intent1.ACTION_VIEW, "file://")
Intent1.SetType("text/*")
For Each cn As String In pm.QueryIntentActivities(Intent1)
  Log(cn)
Next

Phone


Events:

None

Members:


  GetDataState As String

  GetMaxVolume (Channel As Int) As Int

  GetNetworkOperatorName As String

  GetNetworkType As String

  GetPhoneType As String

  GetResourceDrawable (ResourceId As Int) As android.graphics.drawable.Drawable

  GetRingerMode As Int

  GetSettings (Settings As String) As String

  GetSimOperator As String

  GetVolume (Channel As Int) As Int

  HideKeyboard (Activity As ActivityWrapper)

  IsAirplaneModeOn As Boolean

  IsNetworkRoaming As Boolean

  Manufacturer As String [read only]

  Model As String [read only]

  Product As String [read only]

  RINGER_NORMAL As Int

  RINGER_SILENT As Int

  RINGER_VIBRATE As Int

  SdkVersion As Int [read only]

  SendBroadcastIntent (Intent As android.content.Intent)

  SetMute (Channel As Int, Mute As Boolean)

  SetRingerMode (Mode As Int)

  SetScreenBrightness (Value As Float)

  SetScreenOrientation (Orientation As Int)

  SetVolume (Channel As Int, VolumeIndex As Int, ShowUI As Boolean)

  Shell (Command As String, Args() As String, StdOut As StringBuilder, StdErr As StringBuilder) As Int

  ShellAsync (Command As String, Args() As String) As Object

  VOLUME_ALARM As Int

  VOLUME_MUSIC As Int

  VOLUME_NOTIFICATION As Int

  VOLUME_RING As Int

  VOLUME_SYSTEM As Int

  VOLUME_VOICE_CALL As Int

Members description:

GetDataState As String
Returns the current cellular data connection state.
Possible values: DISCONNECTED, CONNECTING, CONNECTED, SUSPENDED.
GetMaxVolume (Channel As Int) As Int
Gets the maximum volume index (value) for the given channel.
Channel - One of the VOLUME constants.
GetNetworkOperatorName As String
Returns the name of current registered operator.
Returns an empty string if it is not available.
GetNetworkType As String
Returns the currently used cellular network type.
Possible values: 1xRTT, CDMA, EDGE, EHRPD, EVDO_0, EVDO_A, EVDO_B, GPRS, HSDPA,
HSPA, HSPAP, HSUPA, IDEN, LTE, UMTS, UNKNOWN.
GetPhoneType As String
Returns the phone radio type. Possible values: CDMA, GSM, NONE.
GetResourceDrawable (ResourceId As Int) As android.graphics.drawable.Drawable
Returns an internal drawable object.
See this
page for a list of available resources.
Example:
Dim p As Phone
Dim bd As BitmapDrawable
bd = p.GetResourceDrawable(17301618)
Activity.AddMenuItem2("Menu1", "Menu1", bd.Bitmap)
GetRingerMode As Int
Returns the phone ringer mode.
Value will be one of the RINGER constants.
GetSettings (Settings As String) As String
Returns the value of the phone settings based on the given key.
The possible keys are listed
here.
The keys are lower cased.
Example:
Dim p As Phone
Log(GetSettings("android_id"))
GetSimOperator As String
Returns the code of the SIM provider.
Returns an empty string if it is not available.
GetVolume (Channel As Int) As Int
Returns the volume of the specified channel.
Channel - One of the VOLUME constants.
HideKeyboard (Activity As ActivityWrapper)
Hides the soft keyboard if it is displayed.
Example:
Dim p As Phone
p.HideKeyboard(Activity)
IsAirplaneModeOn As Boolean
Tests whether the phone "airplane mode" is on.
IsNetworkRoaming As Boolean
Returns true if the device is considered roaming on the current network.
Manufacturer As String [read only]
Model As String [read only]
Product As String [read only]
RINGER_NORMAL As Int
Normal phone ringer mode.
RINGER_SILENT As Int
Phone ringer will be silent and it will not vibrate.
RINGER_VIBRATE As Int
Phone ringer will vibrate and silent.
SdkVersion As Int [read only]
Returns an integer describing the SDK version.
SendBroadcastIntent (Intent As android.content.Intent)
Sends an intent to all BroadcastReceivers that listen to this type of intents.
Example of asking the media scanner to rescan a file:
Dim i As Intent
i.Initialize("android.intent.action.MEDIA_SCANNER_SCAN_FILE", _
  "file://" & File.Combine(File.DirRootExternal, "pictures/1.jpg"))
Dim p As Phone
p.SendBroadcastIntent(i)
SetMute (Channel As Int, Mute As Boolean)
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 (Mode As Int)
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:
Dim p As Phone
p.SetRingerMode(p.RINGER_VIBRATE)
SetScreenBrightness (Value As Float)
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:
Sub Process_Globals
  Dim phone1 As Phone
End Sub

Sub Globals
  Dim sb As SeekBar
End Sub

Sub Activity_Create(FirstTime As Boolean)
  sb.Initialize("sb")
  sb.Max = 100
  sb.Value = 50
  Activity.AddView(sb, 10dip, 10dip, 90%x, 30dip)
End Sub
Sub sb_ValueChanged (Value As Int, UserChanged As Boolean)
  phone1.SetScreenBrightness(Max(Value, 5) / 100)
End Sub
SetScreenOrientation (Orientation As Int)
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.
SetVolume (Channel As Int, VolumeIndex As Int, ShowUI As Boolean)
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:
Dim p As Phone
p.SetVolume(p.VOLUME_MUSIC, 3, True)
Shell (Command As String, Args() As String, StdOut As StringBuilder, StdErr As StringBuilder) As Int
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:
Dim p As Phone
Dim sb As StringBuilder
sb.Initialize
p.Shell("df", Null, sb, Null)
Msgbox(sb.ToString, "Free space:")
ShellAsync (Command As String, Args() As String) As Object
Asynchronous version of Shell. Should be used with Wait For:

Dim p As Phone
Wait For (p.ShellAsync("ping", Array As String("-c", "1", "b4x.com"))) Complete (Success As Boolean, ExitValue As Int, StdOut As String, StdErr As String)
If Success Then
  Log(ExitValue)
  Log("Out: " & StdOut)
  Log("Err: "& StdErr)
Else
  Log("Error: " & LastException)
End If
VOLUME_ALARM As Int
Alarms channel.
VOLUME_MUSIC As Int
Music channel.
VOLUME_NOTIFICATION As Int
Notifications channel.
VOLUME_RING As Int
Phone ring channel.
VOLUME_SYSTEM As Int
System sounds channel.
VOLUME_VOICE_CALL As Int
Voice calls channel.

PhoneAccelerometer

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)

Members:


  StartListening (EventName As String)

  StopListening

Members description:

StartListening (EventName As String)
Starts listening for AccelerometerChanged events.
StopListening
Stops listening for events.

PhoneCalls

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.

Permissions:

android.permission.CALL_PHONE

Events:

None

Members:


  Call (PhoneNumber As String) As android.content.Intent

Members description:

Call (PhoneNumber As String) As android.content.Intent
Creates an intent that will call a phone number.
Example:
Dim p As PhoneCalls
StartActivity(p.Call("1234567890"))

PhoneEvents

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)

Members:


  Initialize (EventName As String)

  InitializeWithPhoneState (EventName As String, PhoneId As PhoneId)

  StopListening

Members description:

Initialize (EventName As String)
Initializes the object and starts listening for events.
The PhoneStateEvent will not be raised. Use InitializeWithPhoneState instead if it is needed.
InitializeWithPhoneState (EventName As String, PhoneId As PhoneId)
Initializes the object and starts listening for events.
The PhoneStateEvent will also be handled.
Example:
Dim PhoneId As PhoneId
Dim PE As PhoneEvents
PE.InitializeWithPhoneState("PE", PhoneId)
StopListening
Stops listening for events. You can later call Initialize to start listening for events again.

PhoneId


Permissions:

android.permission.READ_PHONE_STATE

Events:

None

Members:


  GetDeviceId As String

  GetLine1Number As String

  GetSimSerialNumber As String

  GetSubscriberId As String

Members description:

GetDeviceId As String
Returns a unique device Id. Returns an empty string if the device Id is not available (usually on wifi only devices).
GetLine1Number As String
Returns the phone number string for line 1 as configured in the SIM card.
Returns an empty string if it is not available.
GetSimSerialNumber As String
Returns the serial number of the SIM card.
Returns an empty string if it is not available.
GetSubscriberId As String
Returns the unique subscriber id.
Returns an empty string if it is not available.

PhoneIntents

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.

Events:

None

Members:


  OpenBrowser (Uri As String) As android.content.Intent

  PlayAudio (Dir As String, File As String) As android.content.Intent

  PlayVideo (Dir As String, File As String) As android.content.Intent

Members description:

OpenBrowser (Uri As String) As android.content.Intent
Creates an intent that will open the specified URI.
Example:
StartActivity (PhoneIntents.OpenBrowser("http://www.google.com"))
PlayAudio (Dir As String, File As String) As android.content.Intent
Creates an intent that will start playing the given audio file with the default player.
This method cannot work with internal files.
PlayVideo (Dir As String, File As String) As android.content.Intent
Creates an intent that will start playing the given video file with the default player.
This method cannot work with internal files.

PhoneOrientation

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)

Members:


  StartListening (EventName As String)

  StopListening

Members description:

StartListening (EventName As String)
Starts listening for OrientationChanged events.
StopListening
Stops listening for events.

PhoneSensors

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.

Events:

SensorChanged (Values() As Float)

Members:


  Accuracy As Int [read only]

  Initialize (SensorType As Int)

  Initialize2 (SensorType As Int, SensorDelay As Int)

  MaxValue As Float [read only]

  StartListening (EventName As String) As Boolean

  StopListening

  Timestamp As Long [read only]

  TYPE_ACCELEROMETER As Int

  TYPE_GYROSCOPE As Int

  TYPE_LIGHT As Int

  TYPE_MAGNETIC_FIELD As Int

  TYPE_ORIENTATION As Int

  TYPE_PRESSURE As Int

  TYPE_PROXIMITY As Int

  TYPE_TEMPERATURE As Int

Members description:

Accuracy As Int [read only]
Returns the event accuracy, between 0 (unreliable) to 3 (maximum accuracy).
Initialize (SensorType As Int)
Initializes the object and sets the sensor type (one of the TYPE_ constants).
Initialize2 (SensorType As Int, SensorDelay As Int)
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.
MaxValue As Float [read only]
Returns the maximum value for this sensor.
Returns -1 if this sensor is not supported.
StartListening (EventName As String) As Boolean
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.
Timestamp As Long [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_ACCELEROMETER As Int
Three values - Acceleration measured in Meters / Second ^ 2 for each axis (X, Y and Z).
TYPE_GYROSCOPE As Int
Three values - Angular velocity measured in Radians / Second around each of the three axis.
TYPE_LIGHT As Int
Single value - Ambient light level measured in SI lux units.
TYPE_MAGNETIC_FIELD As Int
Three values - Ambient magnetic field measured in micro-Tesla for the X, Y and Z axis.
TYPE_ORIENTATION As Int
Three values - Orientation measured in degrees for azimuth, pitch and roll.
TYPE_PRESSURE As Int
Single value - Atmospheric pressure.
TYPE_PROXIMITY As Int
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.
TYPE_TEMPERATURE As Int
Single value - Ambient temperature.

PhoneSms


Permissions:

android.permission.SEND_SMS

Events:

None

Members:


  Send (PhoneNumber As String, Text As String)

  Send2 (PhoneNumber As String, Text As String, ReceiveSentNotification As Boolean, ReceiveDeliveredNotification As Boolean)

Members description:

Send (PhoneNumber As String, Text As String)
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).
Send2 (PhoneNumber As String, Text As String, ReceiveSentNotification As Boolean, ReceiveDeliveredNotification As Boolean)
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.

PhoneVibrate


Permissions:

android.permission.VIBRATE

Events:

None

Members:


  Vibrate (TimeMs As Long)

Members description:

Vibrate (TimeMs As Long)
Vibrates the phone for the specified duration.

PhoneWakeState

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.

Permissions:

android.permission.WAKE_LOCK

Events:

None

Members:


  KeepAlive (BrightScreen As Boolean)

  PartialLock

  ReleaseKeepAlive

  ReleasePartialLock

Members description:

KeepAlive (BrightScreen As Boolean)
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.

RingtoneManager

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:

Sub Process_Globals
  Private rm As RingtoneManager
End Sub

Sub Globals

End Sub

Sub Activity_Create(FirstTime As Boolean)
  rm.ShowRingtonePicker("rm", rm.TYPE_RINGTONE, True, "")
End Sub

Sub rm_PickerResult (Success As Boolean, Uri As String)
  If Success Then
    If Uri = "" Then
      ToastMessageShow("Silent was chosen", True)
    Else
      rm.Play(Uri)
    End If
  Else
    ToastMessageShow("Error loading ringtone.", True)
  End If  
End Sub

Permissions:

android.permission.WRITE_SETTINGS

Events:

PickerResult (Success As Boolean, Uri As String)

Members:


  AddToMediaStore (Dir As String, FileName As String, Title As String, IsAlarm As Boolean, IsNotification As Boolean, IsRingtone As Boolean, IsMusic As Boolean) As String

  DeleteRingtone (Uri As String)

  GetContentDir As String

  GetDefault (Type As Int) As String

  Play (Uri As String)

  SetDefault (Type As Int, Uri As String)

  ShowRingtonePicker (EventName As String, Type As Int, IncludeSilence As Boolean, ChosenRingtone As String)

  TYPE_ALARM As Int

  TYPE_NOTIFICATION As Int

  TYPE_RINGTONE As Int

Members description:

AddToMediaStore (Dir As String, FileName As String, Title As String, IsAlarm As Boolean, IsNotification As Boolean, IsRingtone As Boolean, IsMusic As Boolean) As String
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.

Example:
Dim r As RingtoneManager
Dim u As String
u = r.AddToMediaStore(File.DirRootExternal, "bounce.mp3", "Bounce!", True, True, True, True)
r.SetDefault(r.TYPE_RINGTONE, u)
DeleteRingtone (Uri As String)
Deletes the given entry.
GetContentDir As String
Returns a string that represents the virtual content folder. This can be used to play a Ringtone with MediaPlayer.
GetDefault (Type As Int) As String
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 (Uri As String)
Plays a ringtone Uri.
SetDefault (Type As Int, Uri As String)
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).
ShowRingtonePicker (EventName As String, Type As Int, IncludeSilence As Boolean, ChosenRingtone As String)
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.
TYPE_ALARM As Int
TYPE_NOTIFICATION As Int
TYPE_RINGTONE As Int

Sms

Represents an SMS message.
SMS messages are retrieved using SmsMessages object.

Events:

None

Members:


  Address As String

  Body As String

  Date As Long

  Id As Int

  PersonId As Int

  Read As Boolean

  ThreadId As Int

  Type As Int

Members description:

Address As String
The message address.
Body As String
Message body.
Date As Long
The date of this message.
Id As Int
Message internal id.
PersonId As Int
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.
Read As Boolean
Whether this message has been read.
ThreadId As Int
Thread id.
Type As Int
The message type. One of the SmsMessages constant values.

SmsInterceptor

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)

Members:


  Initialize (EventName As String)

  Initialize2 (EventName As String, Priority As Int)

  ListenToOutgoingMessages

  StopListening

Members description:

Initialize (EventName As String)
Initializes the object and starts listening for new messages.
Initialize2 (EventName As String, Priority As Int)
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.

SmsMessages

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:
Dim SmsMessages1 As SmsMessages
Dim List1 As List
List1 = SmsMessages1.GetAllSince(DateTime.Add(DateTime.Now, 0, 0, -7))
For i = 0 To List1.Size - 1
  Dim Sms As Sms
  Sms = List1.Get(i)
  Log(Sms)
Next

Permissions:

android.permission.READ_SMS

Events:

None

Members:


  GetAll As List

  GetAllSince (Date As Long) As List

  GetBetweenDates (StartDate As Long, EndDate As Long) As List

  GetByMessageId (Id As Int) As List

  GetByPersonId (PersonId As Int) As List

  GetByThreadId (ThreadId As Int) As List

  GetByType (Type As Int) As List

  GetUnreadMessages As List

  TYPE_DRAFT As Int

  TYPE_FAILED As Int

  TYPE_INBOX As Int

  TYPE_OUTBOX As Int

  TYPE_QUEUED As Int

  TYPE_SENT As Int

  TYPE_UNKNOWN As Int

Members description:

GetAll As List
Returns all stored messages.
GetAllSince (Date As Long) As List
Returns all messages since the given date.
GetBetweenDates (StartDate As Long, EndDate As Long) As List
Returns all messages between the given dates. Start value is inclusive and end value is exclusive.
GetByMessageId (Id As Int) As List
GetByPersonId (PersonId As Int) As List
Returns a list with all messages received from the person with the given id.
GetByThreadId (ThreadId As Int) As List
Returns a list with all messages with the given ThreadId.
GetByType (Type As Int) As List
Returns a list with all messages of the given type. The type should be one of the type constants.
GetUnreadMessages As List
Returns all unread messages.
TYPE_DRAFT As Int
TYPE_FAILED As Int
TYPE_INBOX As Int
TYPE_OUTBOX As Int
TYPE_QUEUED As Int
TYPE_SENT As Int
TYPE_UNKNOWN As Int

VoiceRecognition

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).

Events:

Result (Success As Boolean, Texts As List)

Members:


  Initialize (EventName As String)

  IsSupported As Boolean

  Language As String [write only]

  Listen

  Listen2 (RecognizeIntent As android.content.Intent)

  Prompt As String [write only]

Members description:

Initialize (EventName As String)
Initializes the object and sets the Sub that will catch the Result event.
Example:
Dim VR As VoiceRecognition
VR.Initialize("VR")
IsSupported As Boolean
Tests whether voice recognition is supported on this device.
Language As String [write only]
Sets the language used. By default the device default language is used.
Example:
VR.Language = "en"
Listen
Starts listening. The Result event will be raised when the result arrives.
Listen2 (RecognizeIntent As android.content.Intent)
Similar to Listen. Allows you to build the intent yourself.
Prompt As String [write only]
Sets the prompt that is displayed in the "Speak now" dialog in addition to the "Speak now" message.
Top