Seguendo alla lettera le istruzione del tutorial impieghi tre/quattro minuti per un'app funzionante!Bella idea. E semplice da realizzare?
La pagina PHP potrebbe eseguire del codice molto simile a quello del modulo B4J, parte del tutorial. In pratica utilizzare le credenziali opportune per inviare un mesasggio su un certo topic/canale che poi sarà quello su cui sarà in ascolto l'app B4ANon è un'app che crea il file, ma una pagina php.
Yessa, ho appena sguardato (traduzione: dato uno sguardoLa pagina PHP potrebbe eseguire del codice molto simile a quello del modulo B4J, parte del tutorial. In pratica utilizzare le credenziali opportune per inviare un mesasggio su un certo topic/canale che poi sarà quello su cui sarà in ascolto l'app B4A
#Region Project Attributes
#ApplicationLabel: TurnApp
#VersionCode: 2
#VersionName: 2.0
'SupportedOrientations possible values: unspecified, landscape or portrait.
#SupportedOrientations: portrait
#CanInstallToExternalStorage: True
#LibraryVersion: 2.20
#LibraryName: OkHttpUtils2
#BridgeLogger: True
#End Region
#Region Activity Attributes
#FullScreen: False
#IncludeTitle: True
#End Region
Sub Process_Globals
'These global variables will be declared once when the application starts.
'These variables can be accessed from all modules.
Dim hc As OkHttpClient
Dim awake As PhoneWakeState
Dim timer1 As Timer
Dim timer2 As Timer
End Sub
Sub Globals
'These global variables will be redeclared each time the activity is created.
'These variables can only be accessed from this module.
Dim p As Phone
Dim pnlmessage As Panel
Dim lblmessage As Label
Dim vr As VoiceRecognition
Dim txtmessagerx As EditText
Dim mp As MediaPlayer
Dim mp2 As MediaPlayer
Dim mp3 As MediaPlayer
Dim mp4 As MediaPlayer
Dim answ As Int
Private lblmessage2 As Label
End Sub
Sub Activity_Create(FirstTime As Boolean)
'Do not forget to load the layout file created with the visual designer. For example:
If FirstTime Then
Activity.LoadLayout("TurnApp")
p.SetScreenOrientation(1)
vr.Initialize("vr")
mp.Initialize
mp2.Initialize
mp3.Initialize
mp4.Initialize
Dim job As HttpJob
job.Initialize("j", Me)
'job.Download("http://www.xxxxxx.xx/xxxxxx/xxxx/NumeroA.txt")
'job.Download("http://www.xxxxxx.xx/xxxx/xxxxxx/NumeroB.txt")
pnlmessage.Visible=True
pnlmessage.SetLayout(0%x,0%y,100%x,100%y)
lblmessage.SetLayout(1%x,2%y,98%x,48%y)
lblmessage2.SetLayout(1%x,49%y,98%x,48%y)
hc.Initialize("hc")
timer1.Initialize("timer1",4000)
timer2.Initialize("timer2",4000)
timer1.Enabled=True
timer2.Enabled=True
Else
Activity.LoadLayout("TurnApp")
p.SetScreenOrientation(1)
vr.Initialize("vr")
mp.Initialize
mp2.Initialize
mp3.Initialize
pnlmessage.Visible=True
pnlmessage.SetLayout(0%x,0%y,100%x,100%y)
lblmessage.SetLayout(1%x,2%y,98%x,48%y)
lblmessage2.SetLayout(1%x,49%y,98%x,48%y)
hc.Initialize("hc")
timer1.Initialize("timer1",4000)
timer1.Enabled=True
End If
txtmessagerx.Color=Colors.White
End Sub
Sub Activity_KeyPress (KeyCode As Int) As Boolean
Dim answ As Int
If KeyCode = KeyCodes.KEYCODE_BACK Then
answ = Msgbox2("Sei sicuro di voler uscire da Boarding Pass? Are you sure to exit Boarding Pass?","AVVISO!!","YES","","NO",Null)
If answ = DialogResponse.POSITIVE Then
mp.Stop
mp2.Stop
mp3.Stop
Return False
Else
End If
End If
Return True
End Sub
Sub dati_Click
pnlmessage.Visible=False
End Sub
Sub timer1_Tick
Dim job As HttpJob
job.Initialize("Job", Me)
job.Download("http://www.xxxxx.xx/xxxx/xxxxx/NumeroA.txt")
'job.Download("http://www.xxxxx.xxx/xxxx/xxxx/NumeroB.txt")
End Sub
Sub timer2_Tick
Log("sono sulla sub timer2")
Dim job As HttpJob
job.Initialize("Job", Me)
'job.Download("http://www.xxxx.xx/xxx/xxx/NumeroA.txt")
job.Download("http://www.xxxx.xx/xx/xxxxxxx/NumeroB.txt")
End Sub
Sub JobDone (job As HttpJob)
Log("JobName = " & job.JobName & ", Success = " & job.Success)
If job.Success = True Then
Select job.JobName
Case "Job" , "job2"
'print the result to the logs
txtmessagerx.Text=job.GetString
Log(job.GetString)
If txtmessagerx.Text.StartsWith("A") Then
lblmessage.Text=txtmessagerx.Text
else if txtmessagerx.Text.StartsWith("B") Then
lblmessage2.Text=txtmessagerx.Text
End If
Case "Job3"
'show the downloaded image
Activity.SetBackgroundImage(job.GetBitmap)
End Select
Else
Log("Error: " & job.ErrorMessage)
ToastMessageShow("Error: " & job.ErrorMessage, True)
End If
job.Release
End Sub
Sub txtmessagerx_TextChanged (Old As String, New As String)
If txtmessagerx.Text = Old Then
Else
sound
Log("vai sulla sub Creafile")
End If
End Sub
Sub sound
mp.Initialize
mp.Load(File.DirAssets,"din2.wav")
mp.Play
End Sub
Sub Activity_Resume
awake.KeepAlive(True)
End Sub
Sub Activity_Pause (UserClosed As Boolean)
awake.ReleaseKeepAlive
End Sub
#Region Module Attributes
#StartAtBoot: False
#End Region
'HttpUtils2 version 2.10 (based on OkHttp library)
'Service module
Sub Process_Globals
Private hc As OkHttpClient
Private TaskIdToJob As Map
Public TempFolder As String
Private taskCounter As Int
End Sub
Sub Service_Create
TempFolder = File.DirInternalCache
hc.Initialize("hc")
TaskIdToJob.Initialize
End Sub
Sub Service_Start (StartingIntent As Intent)
End Sub
Sub Service_Destroy
End Sub
Public Sub SubmitJob(job As HttpJob) As Int
taskCounter = taskCounter + 1
TaskIdToJob.Put(taskCounter, job)
If job.Username <> "" And job.Password <> "" Then
hc.ExecuteCredentials(job.GetRequest, taskCounter, job.Username, job.Password)
Else
hc.Execute(job.GetRequest, taskCounter)
End If
Return taskCounter
End Sub
Sub hc_ResponseSuccess (Response As OkHttpResponse, TaskId As Int)
Response.GetAsynchronously("response", File.OpenOutput(TempFolder, TaskId, False), _
True, TaskId)
End Sub
Sub Response_StreamFinish (Success As Boolean, TaskId As Int)
If Success Then
CompleteJob(TaskId, Success, "")
Else
CompleteJob(TaskId, Success, LastException.Message)
End If
End Sub
Sub hc_ResponseError (Response As OkHttpResponse, Reason As String, StatusCode As Int, TaskId As Int)
If Response <> Null Then
Log(Response.ErrorResponse)
Response.Release
End If
CompleteJob(TaskId, False, Reason)
End Sub
Sub CompleteJob(TaskId As Int, success As Boolean, errorMessage As String)
Dim job As HttpJob = TaskIdToJob.Get(TaskId)
TaskIdToJob.Remove(TaskId)
job.success = success
job.errorMessage = errorMessage
job.Complete(TaskId)
End Sub
'HttpUtils2 version 2.01
'Class module
Sub Class_Globals
Public JobName As String
Public Success As Boolean
Public Username, Password As String
Public ErrorMessage As String
Private target As Object
Private taskId As String
Private req As OkHttpRequest
Public Tag As Object
Type MultipartFileData (Dir As String, FileName As String, KeyName As String, ContentType As String)
End Sub
'Initializes the Job.
'Name - The job's name. Note that the name doesn't need to be unique.
'TargetModule - The activity or service that will handle the JobDone event.
Public Sub Initialize (Name As String, TargetModule As Object)
JobName = Name
target = TargetModule
End Sub
'Sends a POST request with the given data as the post data.
Public Sub PostString(Link As String, Text As String)
PostBytes(Link, Text.GetBytes("UTF8"))
End Sub
'Sends a POST request with the given string as the post data
Public Sub PostBytes(Link As String, Data() As Byte)
req.InitializePost2(Link, Data)
CallSubDelayed2(HttpUtils2Service, "SubmitJob", Me)
End Sub
'Sends a PUT request with the given data as the post data.
Public Sub PutString(Link As String, Text As String)
PutBytes(Link, Text.GetBytes("UTF8"))
End Sub
'Sends a POST request with the given string as the post data
Public Sub PutBytes(Link As String, Data() As Byte)
req.InitializePut2(Link, Data)
CallSubDelayed2(HttpUtils2Service, "SubmitJob", Me)
End Sub
'Sends a multipart POST request.
'NameValues - A map with the keys and values. Pass Null if not needed.
'Files - List of MultipartFileData items. Pass Null if not needed.
public Sub PostMultipart(Link As String, NameValues As Map, Files As List)
Dim boundary As String = "---------------------------1461124740692"
Dim stream As OutputStream
stream.InitializeToBytesArray(0)
Dim b() As Byte
Dim eol As String = Chr(13) & Chr(10)
If NameValues <> Null And NameValues.IsInitialized Then
For Each key As String In NameValues.Keys
Dim value As String = NameValues.Get(key)
Dim s As String = _
$"--${boundary}
Content-Disposition: form-data; name="${key}"
${value}
"$
b = s.Replace(CRLF, eol).GetBytes("UTF8")
stream.WriteBytes(b, 0, b.Length)
Next
End If
If Files <> Null And Files.IsInitialized Then
For Each fd As MultipartFileData In Files
Dim s As String = _
$"--${boundary}
Content-Disposition: form-data; name="${fd.KeyName}"; filename="${fd.FileName}"
Content-Type: ${fd.ContentType}
"$
b = s.Replace(CRLF, eol).GetBytes("UTF8")
stream.WriteBytes(b, 0, b.Length)
Dim in As InputStream = File.OpenInput(fd.Dir, fd.FileName)
File.Copy2(in, stream)
stream.WriteBytes(eol.GetBytes("utf8"), 0, 2)
Next
End If
s = _
$"
--${boundary}--
"$
b = s.Replace(CRLF, eol).GetBytes("UTF8")
stream.WriteBytes(b, 0, b.Length)
PostBytes(Link, stream.ToBytesArray)
req.SetContentType("multipart/form-data; boundary=" & boundary)
req.SetContentEncoding("UTF8")
End Sub
'Sends a POST request with the given file as the post data.
'This method doesn't work with assets files.
Public Sub PostFile(Link As String, Dir As String, FileName As String)
Dim length As Int
If Dir = File.DirAssets Then
Log("Cannot send files from the assets folder.")
Return
End If
length = File.Size(Dir, FileName)
Dim In As InputStream
In = File.OpenInput(Dir, FileName)
If length < 1000000 Then '1mb
'There are advantages for sending the file as bytes array. It allows the Http library to resend the data
'if it failed in the first time.
Dim out As OutputStream
out.InitializeToBytesArray(length)
File.Copy2(In, out)
PostBytes(Link, out.ToBytesArray)
Else
req.InitializePost(Link, In, length)
CallSubDelayed2(HttpUtils2Service, "SubmitJob", Me)
End If
End Sub
'Submits a HTTP GET request.
'Consider using Download2 if the parameters should be escaped.
Public Sub Download(Link As String)
req.InitializeGet(Link)
CallSubDelayed2(HttpUtils2Service, "SubmitJob", Me)
End Sub
'Submits a HTTP GET request.
'Encodes illegal parameter characters.
'<code>Example:
'job.Download2("http://www.example.com", _
' Array As String("key1", "value1", "key2", "value2"))</code>
Public Sub Download2(Link As String, Parameters() As String)
Dim sb As StringBuilder
sb.Initialize
sb.Append(Link)
If Parameters.Length > 0 Then sb.Append("?")
Dim su As StringUtils
For i = 0 To Parameters.Length - 1 Step 2
If i > 0 Then sb.Append("&")
sb.Append(su.EncodeUrl(Parameters(i), "UTF8")).Append("=")
sb.Append(su.EncodeUrl(Parameters(i + 1), "UTF8"))
Next
req.InitializeGet(sb.ToString)
CallSubDelayed2(HttpUtils2Service, "SubmitJob", Me)
End Sub
'Called by the service to get the request
Public Sub GetRequest As OkHttpRequest
Return req
End Sub
'Called by the service when job completes
Public Sub Complete (id As Int)
taskId = id
CallSubDelayed2(target, "JobDone", Me)
End Sub
'Should be called to free resources held by this job.
Public Sub Release
File.Delete(HttpUtils2Service.TempFolder, taskId)
End Sub
'Returns the response as a string encoded with UTF8.
Public Sub GetString As String
Return GetString2("UTF8")
End Sub
'Returns the response as a string.
Public Sub GetString2(Encoding As String) As String
Dim tr As TextReader
tr.Initialize2(File.OpenInput(HttpUtils2Service.TempFolder, taskId), Encoding)
Dim res As String
res = tr.ReadAll
tr.Close
Return res
End Sub
'Returns the response as a bitmap
Public Sub GetBitmap As Bitmap
Dim b As Bitmap
b = LoadBitmap(HttpUtils2Service.TempFolder, taskId)
Return b
End Sub
'Returns the response as a bitmap loaded with LoadBitmapSample.
Public Sub GetBitmapSample(Width As Int, Height As Int) As Bitmap
Return LoadBitmapSample(HttpUtils2Service.TempFolder, taskId, Width, Height)
End Sub
Public Sub GetInputStream As InputStream
Dim In As InputStream
In = File.OpenInput(HttpUtils2Service.TempFolder, taskId)
Return In
End Sub
Region Service Attributes
#StartAtBoot: False
#End Region
Sub Process_Globals
'These global variables will be declared once when the application starts.
'These variables can be accessed from all modules.
Dim N As Notification
Dim hc As OkHttpClient
Dim testo As String
Dim timer1 As Timer
Dim timer2 As Timer
End Sub
Sub Service_Create
n.Initialize
n.Icon = "icon"
n.Sound = False
n.Vibrate = False
n.Light = False
n.OnGoingEvent=True
' n.SetInfo("NUMERO", "txtmessagerx.text",Main)
'Change Main (above) to "" if this code is in the main module.
n.Notify(1)
hc.Initialize("hc")
timer1.Initialize("timer1",4000)
timer2.Initialize("timer2",4000)
timer1.Enabled=True
timer2.Enabled=True
End Sub
Sub Service_Start (StartingIntent As Intent)
n.Notify(1)
Service.StopAutomaticForeground 'Call this when the background task completes (if there is one)
End Sub
Sub timer1_Tick
Log("sono sulla sub timer1 di Starter")
Dim job As HttpJob
job.Initialize("Job", Me)
job.Download("http://www.xxxxx.xxx/xxxxx/xxxx/NumeroA.txt")
'job.Download("http://www.xxx.xxx/xxx/xxx/NumeroB.txt")
End Sub
Sub timer2_Tick
Log("sono sulla sub timer2 di Starter")
Dim job As HttpJob
job.Initialize("Job", Me)
'job.Download("http://www.xxx.xx/xxxx/xxxx/NumeroA.txt")
job.Download("http://www.xxx.xx/xxx/xxxxx/NumeroB.txt")
End Sub
Sub JobDone (job As HttpJob)
Log("JobName = " & job.JobName & ", Success = " & job.Success)
If job.Success = True Then
Select job.JobName
Case "Job" , "job2"
'print the result to the logs
testo =job.GetString
Log(job.GetString)
If testo.StartsWith("A") Then
' qui secondo me dovrebbe fare il confronto per la lettera A
else if testo.StartsWith("B") Then
' qui secondo me dovrebbe fare il confronto per la lettera B
End If
Case "Job3"
'show the downloaded image
'Activity.SetBackgroundImage(job.GetBitmap)
End Select
Else
Log("Error: " & job.ErrorMessage)
ToastMessageShow("Error: " & job.ErrorMessage, True)
End If
job.Release
End Sub
Sub testo_TextChanged (Old As String, New As String)
If testo = Old Then
Else
ToastMessageShow(testo,True)
Log("vai sulla sub Creafile")
End If
End Sub
Sub Service_Destroy
End Sub
A parte che non credo (spero di no) che sia il cliente a dover inserire il numero e quindi si dovrebbe usare una Label, se è una EditText nell'evento TextChanged metti:pensavo di fare una variabile testo come stringa ma come faccio a fare il confronto con una edittext nella main che ha il numero inserito dal cliente?
Ormai sei troppo vecchio e lento, @udgCome ti dicevo, se in Sub Process_Globals metti una variabile stringa (es. mionumero) e nel Main assegni a questa il valore della edittext, hai risolto.
mionumero = edInputNumero.Text
Chi? Io? Deppiù, me sa(se fa' pe dì visto che sei giurassico quanto me)
Dato che la domanda è rivolta ad una specifica persona... non si rispondeudg se creo una variabile stringa nel modulo di servizio e sulla sub process global, questa nella main non viene vista, quindi come mai ? non potreste farmi un esempio o magari illustrarmi perchè mi dice che la variabile non risulta assegnata ? insomma chi spacchiu a fari?
Non essere cattivo..Dato che la domanda è rivolta ad una specifica persona... non si risponde
Ciao, mi riferivo a Luca/Mario. Il "cattivone" era lui. Ma è tutto uno scherzo tra amici. A noi piace scherzare e prenderci simpaticamente in giro.udg scusami non voglio essere cattivo
We use cookies and similar technologies for the following purposes:
Do you accept cookies and these technologies?
We use cookies and similar technologies for the following purposes:
Do you accept cookies and these technologies?