|     Inicio    |   |         |  |   FOROS      |  |      |      
   Elastix - VoIP B4A (Basic4Android) App inventor 2 PHP - MySQL
  Estación meteorológica   ADB Shell - Android Arduino
   AutoIt (Programación) Visual Basic Script (VBS) FireBase (BD autoactualizable) NodeMCU como Arduino
  Teleco - Emisora de A.M. Visual Basic Cosas de Windows Webs interesantes
Translate:
Búsqueda en este sitio:


Nuevo concurso para España, Argentina, Brasil, Chile, Colombia, Ecuador, México, Perú y Portugal.

B4A en español - Juan Antonio Villalpando
(BASIC4Android)

-- Tutorial de B4A --

Volver al índice del tutorial                    Return to index tutorial

____________________________

Basic4Android.

45.- Estudio de la biblioteca Phone

Tutoriales. Estudio de la biblioteca Phone.
(Ver también la librería PhoneStateListener)

Presentación

- En un tutorial anterior vimos las posibilidades de la Biblioteca OSLibrary, ahora vamos a ver algunas de las posibilidades de otra Biblioteca importante Phone.

- Library viene a significar Biblioteca, aunque algunos lo traducen en el argot informático como Librería.

- Mediante la Biblioteca Phone podemos:

- Ver listado de los usuarios que tenemos en el móvil.
- Ver listado de llamadas recibidas.
- Consultar email, llamadas y sms recibidos.
- Obtener información sobre los paquetes de programas que tenemos.
- Obtener información sobre las características de nuestro móvil y de nuestro operador.
- Configurar el acelerómetro, consultar la orientación geográfica.
- Enviar email y sms.
- Realizar llamadas.
- Actuar con los sensores de temperatura, acelerómetro, giroscopio, luz, campo magnético, proximidad, presión...
- Sonido, reconocimiento de voz.
- etc.

Podemos obtener información de la Biblioteca Phone en los foros de B4A: Biblioteca Phone.

Para utilizar una Biblioteca primero debemos tener en la carpeta:

C:\Program Files (x86)\Anywhere Software\Basic4android\Libraries

dos archivos de la forma:

Phone.jar
Phone.xml

Luego cuando creemos un programa debemos activar esa Biblioteca:


Después, para utilizarla debemos declarar algunos de los Tipos que la componen:

Fíjate en la ayuda la List of types que componen esta Biblioteca:

- Consulta en qué parte de esa lista está la acción que quieres hacer, y declara una variable con ese tipo, en este ejemplo he puesto la letra p

Dim p As Phone

- Ahora para consultar un valor del tipo Phone lo hacemos así:

Label1.Text = "Fabricante = " & p.Manufacturer

es decir la variable p. y luego el miembro que queremos consultar.

Si lo que queremos es establacer un valor lo haríamos así:

p.SetRingerMode(p.RINGER_VIBRATE)
p.SetScreenBrightness(0.33)
p.SetVolume(p.VOLUME_MUSIC, 3, True)

 

Si quisieramos utilizar otro de esos tipos lo tendríamos que declarar también, en este caso he elegido pi

Dim pi As PhoneID

Ahora para consultar uno de los valores de ese tipo lo hacemos así:

Label1.Text = "Número SIM de serie = " & pi.GetSimSerialNumber

Es decir, primero declaramos una variable para el Type que vamos a utilizar y luego escribimos la variable, un punto y el miembro de ese tipo.


variable_de_tipo_declarado.miembro

 

- Podemos crear usuarios en el emulador mediante el icono de Contactos que se encuentra en la pantalla de Aplicaciones.

- Crearemos una nueva aplicación.

No hace falta Designer ni Layout ya que los controles (View) se crean en el código.

Consultando el código, sus comentarios y el tutorial oficial de la Biblioteca Phone, se puede tener una buena idea de lo que hace esta Biblioteca.

Copiamos y pegamos este código...

Estudio de la biblioteca Phone
Sub Process_Globals
' Juan Antonio Villalpando
' juana1991@yahoo.com
    
End Sub

Sub Globals
    ' Crearemos 9 botones.
    Dim Buttons(5,4) As Button
    
    ' Crearemos 1 etiqueta (Label)
    Dim etiqueta As Label
Dim informacion As String Dim numero_boton As Int End Sub Sub Activity_Create(FirstTime As Boolean) Dim ancho, alto, offsetY As Int ancho = 60dip alto = 30dip For y =1 To 2 For x = 1 To 4 numero_boton = numero_boton + 1 Dim b As Button b.Initialize("Button") b.TextSize = 8 b.Text = numero_boton b.Tag = numero_boton Activity.AddView(b, -80 + x * (ancho + 10dip), -40 + y * (alto + 10dip), ancho, alto) Buttons(x,y) = b Next Next ' Los View cuando se crean en el código hay que ' Iniciarlos y luego Añadirlos al Activiy etiqueta.Initialize("etiqueta") etiqueta.TextSize = 12 etiqueta.TextColor = Colors.White etiqueta.Color = Colors.Black Activity.AddView(Etiqueta, 20dip, 80dip, 300dip, 800dip) End Sub Sub Activity_Resume ' CallSubDelayed(Me, "HideKeyboard") End Sub
Sub Activity_Pause (UserClosed As Boolean) End Sub Sub Button_Click Dim b As Button b = Sender Select b.Tag Case 1 ' Type Phone Dim p As Phone informacion = "Estado de la conexión = " & p.GetDataState & CRLF & _ "Volumen máximo = " & p.GetMaxVolume(1) & CRLF & _ "Nombre del operador de red = " & p.GetNetworkOperatorName & CRLF & _ "Tipo de red = " & p.GetNetworkType & CRLF & _ "Tipo de teléfono = " & p.GetPhoneType & CRLF & _ "Tipo de tono de llamada = " & p.GetRingerMode & CRLF & _ "Configuración (ver en tutorial listado de claves) = " & p.GetSettings("android_id") & CRLF & _ "SIM del Operador = " & p.GetSimOperator & CRLF & _ "Volumen actual = " & p.GetVolume(1) & CRLF & _ "Modo avión = " & p.IsAirplaneModeOn & CRLF & _ "Roaming = " & p.IsNetworkRoaming & CRLF & _ "Fabricante = " & p.Manufacturer & CRLF & _ "Modelo = " & p.Model & CRLF & _ "Producto = " & p.Product & CRLF & _ "Para Vibrar = p.SetRingerMode(p.RINGER_VIBRATE)" & CRLF & _ "Versión SDK = " & p.SdkVersion & CRLF & _ "Para poner Mute = p.SetMute(1)" & CRLF & _ "Para poner Brillo de pantalla = p.SetScreenBrightness(0.33)" & CRLF & _ "Para poner volumen = p.SetVolume(p.VOLUME_MUSIC, 3, True)" ' Forma de establecer las variables p.SetRingerMode(p.RINGER_VIBRATE) p.SetScreenBrightness(0.33) p.SetVolume(p.VOLUME_MUSIC, 3, True) etiqueta.Text = informacion Msgbox("Pulsa para continuar","Pulsa") ' Ejecutar comando del shell directamente desde código Dim sb As StringBuilder sb.Initialize p.Shell("ls -l", Null, sb, Null) Msgbox(sb.ToString, "Listado:") Case 2 ' Type PhoneID Dim pi As PhoneId informacion = "Número identificador = " & pi.GetDeviceId & CRLF & _ "Número de Línea 1 = " & pi.GetLine1Number & CRLF & _ "Número SIM de serie = " & pi.GetSimSerialNumber & CRLF & _ "Identificación del subscriptor = " & pi.GetSubscriberId etiqueta.Text = informacion Case 3 ' Envío de un email ' SOLO FUNCIONA EN EL MOVIL REAL, NO EN EL EMULADOR!!!!!. Dim m As Email Dim p As Phone m.To.Add("super_cani@hotmail.com") m.Body = "Hola, cómo estás." m.Subject = "OLA KE ASE" ' m.Attachments.Add(File.Combine(File.DirRootExternal, "1.jpg")) ' El este caso el contenido es el de un archivo ' m.Body = File.ReadString(File.DirRootExternal, "sdcard-disk0/data/transfer/mybody.txt") StartActivity(m.GetIntent) p.HideKeyboard(Activity) Case 4 etiqueta.Visible = False ' Type PackageManager Dim pm As PackageManager ' Obtiene el icono del Navegador y lo pone de fondo de Pantalla (Background) Activity.Background = pm.GetApplicationIcon("com.android.browser") Msgbox("Pulsa para continuar","Pulsa") ' Nombre de la aplicación etiqueta.Visible = True etiqueta.Text = pm.GetApplicationLabel("com.android.browser") Msgbox("Pulsa para continuar","Pulsa") ' Programas instalados. ' El listado de programas instalados se presenta en la ventana Logs ' a esta ventana se llega pulsando la pestaña Logs, abajo - izquierda ' al lado de la pestaña Libs. (También pulsamos el botón Connect) Dim packages As List packages = pm.GetInstalledPackages For i = 0 To packages.Size - 1 Log(packages.Get(i)) Next Msgbox("Pulsa para continuar","Pulsa") ' Lanza un programa Dim in As Intent in = pm.GetApplicationIntent("com.android.browser") If in.IsInitialized Then StartActivity(in) StartActivity(in) Case 5 ' Type PhoneCalls ' Llamar a un teléfono. Dim pc As PhoneCalls StartActivity(pc.Call("759555555")) Case 6 etiqueta.Text = "6" Case 7 etiqueta.Text = "7" Case 8 ' Listado de contactos etiqueta.Text = "" Dim Contacts1 As Contacts Dim listOfContacts As List listOfContacts = Contacts1.GetAll For i = 0 To listOfContacts.Size - 1 Dim Contact As Contact Contact = listOfContacts.Get(i) ' Log(Contact) 'will print the fields to the LogCat etiqueta.Text= etiqueta.Text & Contact & CRLF 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 etiqueta.Text = etiqueta.Text & "Dirección de correo: " & emails & CRLF Dim phones As Map phones = Contact.GetPhones If phones.Size > 0 Then etiqueta.Text = etiqueta.Text & "Número de telefóno: " & phones & CRLF Next Case Else etiqueta.Text = "Nada" End Select End Sub Sub HideKeyboard Dim p As Phone p.HideKeyboard(Activity) End Sub

Comentarios al código.

- La Biblioteca tiene más posibilidades de las que he tratado con este código, es conviente echarle un vistazo debido a su importancia.

- Si quieres tener más información sobre los Contactos que tienes configurados, puedes utilizar esta otra biblioteca: fgContacts

Ejecutar un comando desde el código de B4A

Dim StdOut, StdErr As StringBuilder
StdOut.Initialize
StdErr.Initialize
Dim Ph As Phone

Ph.Shell("date", Null, StdOut, Null)

' Ph.Shell("pm", Array As String ( "list", "packages" ), sb, Null)
Msgbox(StdOut.ToString,"Fecha")

Hay una librería llamada suCommand con la que también podemos ejecutar algunos comandos

http://www.basic4ppc.com/forum/basic4android-updates-questions/14648-shell-root-2.html

Veamos un ejemplo de ejecutar comandos desde código, en este caso vamos a realizar un PING.

Para que funcione este código, antes debemos modificar el archivo AndroidManifest.xml que está en la carpeta Objects de nuestro proyecto y escribir añadir la linea marcada. Con esta línea estamos añadiendo permiso de salida a Internet de la aplicación.

<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<uses-permission android:name="android.permission.INTERNET"/>
</intent-filter>

Código en Basic4android
Sub Process_Globals
    Dim ph As Phone
    Dim sb As StringBuilder
    Dim dirIP As String
End Sub

Sub Globals
    Dim boton As Button
End Sub

Sub Activity_Create(FirstTime As Boolean)
    ' Crea Botón (Button)
    boton.Initialize("boton")
    boton.TextColor = Colors.Red
    boton.Text = "Pulsa"
    Activity.AddView(boton, 0dip, 10dip, 100%x, 10%y)
    sb.Initialize 
End Sub

Sub Activity_Resume

End Sub

Sub Activity_Pause(UserClosed As Boolean)

End Sub

Sub boton_Click
    dirIP = "www.google.com"
    ph.Shell("ping -c1 " & dirIP, Null, sb, Null)
    Log(sb)
End Sub

Pulsamos sobre Log (abajo derecha) y obtenemos esta respuesta:

En mi caso ha enviado un paquete a Google, pero se ha perdido.
ping -c1, significa que envía un paquete, si quisieramos enviar 4 escribiríamos ping -c4

___________________________________________
Consultar también PhoneEvents

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)

___________________________________________
Orientación del teléfono.

Mediante la librería Phone podemos cambiar la orientación de la pantalla, aunque debemos tener en cuenta la situación de los Views.
No funciona en el emulador. Código de DKCERT.

Código en Basic4android
Sub Process_Globals

End Sub

Sub Globals
    Dim Orient As ListView
    Dim phn As Phone
End Sub

Sub Activity_Create(FirstTime As Boolean)
    Orient.Initialize("Orient")
    Orient.AddSingleLine2("-1 = Auto (Sensor)", -1)
    Orient.AddSingleLine2(" 0 = Landscape - Set", 0)
    Orient.AddSingleLine2(" 1 = Portrait - Set", 1)
    Orient.AddSingleLine2(" 6 = Lanscape Sensor", 6)
    Orient.AddSingleLine2(" 7 = Portrait Sensor", 7)
    Orient.AddSingleLine2(" 8 = Reversed Lanscape - Set", 8)
    Orient.AddSingleLine2(" 9 = Reversed Portrait - Set", 9)
    Activity.AddView(Orient,20,20,Activity.width -40, Activity.Height-40)
End Sub

Sub Activity_Resume

End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub

Sub Orient_ItemClick (Position As Int, Value As Object)
    phn.SetScreenOrientation(Value)
End Sub
      

___________________________________________
Ver permisos de las aplicaciones actuales del teléfono.

Pulsar directametente en la pantalla.

Código en Basic4android
Sub Activity_click
   Dim pm As PackageManager
   Dim r, pi As Reflector
   r.Target = pm
   r.Target = r.GetField("pm") 'pm is the name of the native PackageManager
   For Each package In pm.GetInstalledPackages
     Log("****** " & package & " ********")
     pi.Target = r.RunMethod3("getPackageInfo", package, "java.lang.String", _
       0x00001000, "java.lang.int")
     Dim permissions() As String = pi.GetField("requestedPermissions")
     If permissions <> Null Then
       For Each per In permissions
         Log(per)
       Next
     End If
   Next
   
   End Sub

___________________________________________
Pantalla del teléfono con más o menos brillo.

Código en Basic4android
'Using Phone library
Dim pw As PhoneWakeState
 
pw.KeepAlive(False) 'Display on, dimmed
'or
pw.KeepAlive(True) 'Display on, bright

'To release
pw.ReleaseKeepAlive

___________________________________________
Ver qué versión tengo del Android

En Create haces un Log(GetOSversion)

Código en Basic4android
Sub GetOSversion As String
    ' http://developer.android.com/guide/topics/manifest/uses-sdk-element.html#ApiLevels
    ' http://en.wikipedia.org/wiki/Android_version_history
    Dim p As Phone
    Select p.SdkVersion
        Case 19 : Return "Android 4.4, KitKat (API level 19)"
        Case 18 : Return "Android 4.3, Jelly Bean MR2 (API level 18)"
        Case 17 : Return "Android 4.2/4.2.2, Jelly Bean MR1 (API level 17)"
        Case 16 : Return "Android 4.1/4.1.1, Jelly Bean (API level 16)"
        Case 15 : Return "Android 4.0.3/4.0.4, Ice Cream Sandwich MR1 (API level 15)"
        Case 14 : Return "Android 4.0/4.0.2, Ice Cream Sandwich (API level 14)"
        Case 13 : Return "Android 3.2, Honeycomb MR2 (API level 13)"
        Case 12 : Return "Android 3.1.x, Honeycomb MR1 (API level 12)"
        Case 11 : Return "Android 3.0.x, Honeycomb (API level 11)"
        Case 10 : Return "Android 2.3.3/2.3.4, Gingerbread MR1 (API level 10)"
        Case  9 : Return "Android 2.3/2.3.1/2.3.2, Gingerbread (API level 9)"
        Case  8 : Return "Android 2.2.x, Froyo (API level 8)"
        Case  7 : Return "Android 2.1.x, Eclair MR1 (API level 7)"
        Case  6 : Return "Android 2.0.1, Eclair_0_1 (API level 6)"
        Case  5 : Return "Android 2.0, Eclair (API level 5)"
        Case  4 : Return "Android 1.6, Donut (API level 4)"
        Case  3 : Return "Android 1.5, Cupcake (API level 3)"
        Case  2 : Return "Android 1.1, Base_1_1 (API level 2)"
        Case  1 : Return "Android 1.0, Base (API level 1)"
    End Select
End SubeKeepAlive

___________________________________________
IP, DNS, máscara y Puerta de enlace.

Mediante la librería Phone podemos ver los números de la conexión wifi.

Código en Basic4android
Sub Process_Globals

End Sub

Sub Globals

End Sub

Sub Activity_Create(FirstTime As Boolean)
Msgbox(GetPropInfo,"DHCP Info")
End Sub

Sub GetPropInfo As String
    Dim i As Int
    Dim P As Phone
    Dim sb As StringBuilder
    Dim PropData() As String
    Dim sWifi, sModel, sSdk, sVersion, sIP, sMask, sGate, sD1, sD2 As String
 
    sb.Initialize
    P.Shell("getprop", Null, sb, Null)
    PropData = Regex.Split(CRLF,sb.ToString)
 
    For i = 0 To PropData.Length - 1
 
        ' What is the Wifi Interface called?
        If PropData(i).Contains("[wifi.interface]") Then
            sWifi = PropData(i)
            sWifi = sWifi.Replace("[","")
            sWifi = sWifi.Replace("]","")
            sWifi = sWifi.SubString(sWifi.IndexOf(" ")).Trim
            Exit
        End If
 
    Next
 
    If sWifi.Length > 0 Then
 
        ' Get the model, android version, <sdk version, ip, subnet mask, gateway, dns1 and dns2
        For i = 0 To PropData.Length - 1
 
            If PropData(i).Contains("[ro.product.model]") Then
                sModel = PropData(i)
                sModel = sModel.Replace("[","")
                sModel = sModel.Replace("]","")
                sModel = sModel.SubString(sModel.IndexOf(" ")).Trim
            End If
 
            If PropData(i).Contains("[ro.build.version.sdk]") Then
                sSdk = PropData(i)
                sSdk = sSdk.Replace("[","")
                sSdk = sSdk.Replace("]","")
                sSdk = sSdk.SubString(sSdk.IndexOf(" ")).Trim
            End If
 
            If PropData(i).Contains("[ro.build.version.release]") Then
                sVersion = PropData(i)
                sVersion = sVersion.Replace("[","")
                sVersion = sVersion.Replace("]","")
                sVersion = sVersion.SubString(sVersion.IndexOf(" ")).Trim
            End If
 
            ' *******************************************************************
            
            If PropData(i).Contains("[dhcp." & sWifi & ".ipaddress]") Then 
                sIP = PropData(i)
                sIP = sIP.Replace("[","")
                sIP = sIP.Replace("]","")
                sIP = sIP.SubString(sIP.IndexOf(" ")).Trim
            End If
 
            If PropData(i).Contains("[dhcp." & sWifi & ".mask]") Then 
                sMask = PropData(i)
                sMask = sMask.Replace("[","")
                sMask = sMask.Replace("]","")
                sMask = sMask.SubString(sMask.IndexOf(" ")).Trim
            End If
 
            If PropData(i).Contains("[dhcp." & sWifi & ".gateway]") Then 
                sGate = PropData(i)
                sGate = sGate.Replace("[","")
                sGate = sGate.Replace("]","")
                sGate = sGate.SubString(sGate.IndexOf(" ")).Trim
            End If
 
            If PropData(i).Contains("[dhcp." & sWifi & ".dns1]") Then 
                sD1 = PropData(i)
                sD1 = sD1.Replace("[","")
                sD1 = sD1.Replace("]","")
                sD1 = sD1.SubString(sD1.IndexOf(" ")).Trim
            End If
 
            If PropData(i).Contains("[dhcp." & sWifi & ".dns2]") Then 
                sD2 = PropData(i)
                sD2 = sD2.Replace("[","")
                sD2 = sD2.Replace("]","")
                sD2 = sD2.SubString(sD2.IndexOf(" ")).Trim
            End If
 
        Next
 
        Return     "Model: " & sModel & CRLF & _
                "Android v/ " & sVersion & CRLF & _
                "SDK v/ " & sSdk & CRLF & CRLF & _
                sWifi & CRLF & _
                "IP Address: " & sIP & CRLF & _
                "Subnet Mask: " & sMask & CRLF & _
                "Default Gateway: " & sGate & CRLF & _
                "DNS #1: " & sD1 & CRLF & _
                "DNS #2: " & sD2 & CRLF
    Else
        Return "Wifi Interface not found."
    End If
 
End Sub
 
      

___________________________________________
Hacer un Ping

Código en Basic4android
Sub Process_Globals


End Sub

Sub Globals
Dim ph As Phone
Dim Label1 As Label
End Sub

Sub Activity_Create(FirstTime As Boolean)
    Activity.LoadLayout("Layout")
    
    Dim dirIP As String
    Dim SB As StringBuilder
    SB.Initialize
    
    dirIP = "www.google.com"
    ph.Shell("ping -c1 " & dirIP, Null, SB, Null)
    
    Label1.text = SB
  '   Log(SB.ToString)

End Sub

Sub Activity_Resume

End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub

Activamos las librerías Phone y StringBuilder.
Creamos un Layout con un Label1.

Añadimos al AndroidManifest:

AddPermission(android.permission.INTERNET)

 

___________________________________________

¿Se pueden crear Bibliotecas?

En las nuevas versiones de B4A, hay una opción para crearlas con gran facilidad, consulta este envío en los foros.

______________________

Puede encontrar más información sobre bibliotecas en...

Libraries

______________________

Otros permisos del archivo AndroidManifest.xml

<uses-permission android:name= " android.permission.INTERNET " />
<uses-permission android:name= " android.permission.READ_PHONE_STATE " />
<uses-permission android:name= " android.permission.ACCESS_NETWORK_STATE " />
<uses-permission android:name= " android.permission.WRITE_EXTERNAL_STORAGE "  />

__________________________________
PhoneStateListener

PhoneStateListener es otra librería con la que podrás obtener más información del móvil.

Con esta librería podrás obtener el nivel de la señal, quién está llamando, cambio de nivel de señal, cambio de geolocalización, etc

http://www.basic4ppc.com/android/forum/threads/phonestatelistener.12377/

PhoneEvents

 

 

________________________________

Si quieres que este tutorial se mantenga y lo actualice con más programas, escríbeme un correo a Juan Antonio: juana1991@yahoo.com

- Mi correo:
juana1991@yahoo.com
- KIO4.COM - Política de cookies. Textos e imágenes propiedad del autor:
© Juan A. Villalpando
No se permite la copia de información ni imágenes.
Usamos cookies propias y de terceros que entre otras cosas recogen datos sobre sus hábitos de navegación y realizan análisis de uso de nuestro sitio.
Si continúa navegando consideramos que acepta su uso. Acepto    Más información