I wanna do an app that check when a jack headbutton is pushed and send a sms with a GPS point.
I used ERELs GPS demo and NJdude Broadcaster Example, but when i enable GPS cant intercept the pushed button,
did know someone how can i set the prioritys? or how can i handle both services?
The button alone works, the gps alone works
Mi code is this
And on Starter
And in mod_var code
On receiver activity
MANIFEST
Thank you in advance and Thanks BGSoft too
Osvaldo
I used ERELs GPS demo and NJdude Broadcaster Example, but when i enable GPS cant intercept the pushed button,
did know someone how can i set the prioritys? or how can i handle both services?
The button alone works, the gps alone works
Mi code is this
B4X:
Region Module Attributes
#FullScreen: False
#IncludeTitle: True
#ApplicationLabel: Test GPS
#VersionCode: 1
#VersionName:
#SupportedOrientations: unspecified
#End Region
Sub Process_Globals
Dim pressTime As Long
Dim cadena As String
Public rp As RuntimePermissions
End Sub
Sub Globals
Dim lblLon As Label
Dim lblLat As Label
Dim lblSpeed As Label
Dim lblSatellites As Label
Private ListView1 As ListView
End Sub
Sub Activity_Create(FirstTime As Boolean)
Activity.LoadLayout("1")
Log(mod_vars.SpeakerPhoneState)
rp.CheckAndRequest(rp.PERMISSION_SEND_SMS)
Wait For Activity_PermissionResult (Permission As String, Result As Boolean)
End Sub
Sub Activity_Resume
If Starter.GPS1.GPSEnabled = False Then
ToastMessageShow("Please enable the GPS device.", True)
StartActivity(Starter.GPS1.LocationSettingsIntent) 'Will open the relevant settings screen.
Else
Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_ACCESS_FINE_LOCATION)
Wait For Activity_PermissionResult (Permission As String, Result As Boolean)
If Result Then CallSubDelayed(Starter, "StartGPS")
End If
End Sub
Sub Activity_Pause (UserClosed As Boolean)
' Dim Sms1 As PhoneSms
' Log("cadena en sms enviando sms ")
' Log(cadena)
'
CallSubDelayed(Starter, "StopGPS")
End Sub
Public Sub GpsStatus (Satellites As List)
Dim sb As StringBuilder
sb.Initialize
sb.Append("Satellites:").Append(CRLF)
For i = 0 To Satellites.Size - 1
Dim Satellite As GPSSatellite = Satellites.Get(i)
sb.Append(CRLF).Append(Satellite.Prn).Append($" $1.2{Satellite.Snr}"$).Append(" ").Append(Satellite.UsedInFix)
sb.Append(" ").Append($" $1.2{Satellite.Azimuth}"$).Append($" $1.2{Satellite.Elevation}"$)
Next
lblSatellites.Text = sb.ToString
End Sub
Public Sub LocationChanged(Location1 As Location)
lblLat.Text = "Lat = " & Location1.ConvertToMinutes(Location1.Latitude)
lblLon.Text = "Lon = " & Location1.ConvertToMinutes(Location1.Longitude)
lblSpeed.Text = $"Speed = $1.2{Location1.Speed} m/s "$
cadena=Location1.Latitude&","&Location1.Longitude
End Sub
Sub add_intent(i As Intent )
ListView1.AddSingleLine(i.Action)
ListView1.AddSingleLine(i.ExtrasToString)
End Sub
Sub Activity_PermissionResult (Permission As String, Result As Boolean)
If Permission = rp.PERMISSION_ACCESS_FINE_LOCATION Then
Log("Permisos concedidos!!!")
End If
StartService("Receiver")
Log("arranco el service")
End Sub
And on Starter
B4X:
Region Service Attributes
#StartAtBoot: False
#ExcludeFromLibrary: True
#End Region
Sub Process_Globals
Public rp As RuntimePermissions
Public GPS1 As GPS
Private gpsStarted As Boolean
' del broadcaster receiver
Private gpsStarted As Boolean
Public rp As RuntimePermissions
Public GPS1 As GPS
End Sub
Sub Service_Create
GPS1.Initialize("GPS")
End Sub
Public Sub StartGps
If gpsStarted = False Then
GPS1.Start(0, 0)
gpsStarted = True
End If
End Sub
Public Sub StopGps
If gpsStarted Then
GPS1.Stop
gpsStarted = False
End If
End Sub
Sub GPS_LocationChanged (Location1 As Location)
CallSub2(Main, "LocationChanged", Location1)
End Sub
Sub GPS_GpsStatus (Satellites As List)
CallSub2(Main, "GpsStatus", Satellites)
End Sub
Sub Application_Error (Error As Exception, StackTrace As String) As Boolean
Return True
End Sub
Sub Service_Destroy
StopGps
End Sub
And in mod_var code
B4X:
'Code module
'Subs in this code module will be accessible from all modules.
Sub Process_Globals
'These global variables will be declared once when the application starts.
'These variables can be accessed from all modules.
Dim LastStarterMessage As String
Dim HeadSetState As Int = -1
Dim SpeakerPhoneState As Boolean = False
Dim SpeakerPhoneRouted As Boolean = False
End Sub
B4X:
#Region Activity Attributes
#FullScreen: False
#IncludeTitle: True
#End Region
#Region Module Attributes
'´' #StartAtBoot: False
#End Region
'Service module
Sub globals
Private v As PhoneVibrate
End Sub
Sub Process_Globals
'These global variables will be declared once when the application starts.
'These variables can be accessed from all modules.
Dim Broadcast As BroadCastReceiver
End Sub
Sub Service_Create
Broadcast.Initialize("BroadcastReceiver")
Log(Broadcast.isOrderedBroadcast)
End Sub
Sub Service_Start(StartingIntent As Intent)
Broadcast.SetPriority(2147483647)
Broadcast.registerReceiver("android.intent.action.MEDIA_BUTTON")
StartingIntent.PutExtra("state", 1)
Log("broad:"&Broadcast.isRegistered)
Broadcast.registerReceiver("")
End Sub
Sub Service_Destroy
End Sub
Sub process_intent(i As Intent )
Dim sf As StringFunctions
sf.Initialize
If sf.InString(i.ExtrasToString,"action=ACTION_DOWN") >= 0 Then
v.Vibrate(100)
' // start press count
Log("Boton Presionado...........................")
If Main.pressTime = 0 Then
Main.pressTime = DateTime.Now
' Dim in As Intent
' in.Initialize(in.ACTION_CALL, "tel:+5492994195223")
' StartActivity(in)
'' ENVIAR UN SMS DE AVISO
Dim Sms1 As PhoneSms
Log("cadena en sms enviando sms ")
Log(Main.cadena)
Sms1.Send("+5xxx9419xx","Oscar este es un sms enviado por el equipo , Y yo me encuentro aqui: http://maps.google.com/?q="&Main.cadena&"zoom=8")
'Dim p As PhoneCalls
'StartActivity(p.Call("+5492994195223"))
Log(DateTime.Time(DateTime.Now) & " Inicio de presionar botón")
End If
'CallSub(Main,"clear_list")
Log(DateTime.Time(DateTime.Now) & " Inicio de presionar botón")
End If
'CallSub(Main,"clear_list")
If sf.InString(i.ExtrasToString,"action=ACTION_UP") >= 0 Then
Log(DateTime.Time(DateTime.Now) & Round2((DateTime.Now - Main.pressTime) / DateTime.TicksPerSecond,2))
Main.pressTime = 0
Log(DateTime.Time(DateTime.Now) & " Finde presionar boton")
End If
CallSub2(Main,"add_intent",i)
If sf.InString(i.ExtrasToString,"action=ACTION_UP") >= 0 Then
Log(DateTime.Time(DateTime.Now) & Round2((DateTime.Now - Main.pressTime) / DateTime.TicksPerSecond,2))
Main.pressTime = 0
Log(DateTime.Time(DateTime.Now) & " Finde presionar boton")
End If
CallSub2(Main,"add_intent",i)
End Sub
Sub BroadcastReceiver_OnReceive(Action As String, Extras As Object)
Dim i As Intent = Extras
Dim HeadsetState() As String
HeadsetState = Array As String("Unplugged", "Plugged")
Log(i.ExtrasToString)
Log(HeadsetState)
ToastMessageShow("State: " & HeadsetState(i.GetExtra("state")), False)
Log(Action)
setSpeakerPhone(mod_vars.HeadSetState)
Log(mod_vars.HeadSetState)
End Sub
Sub Media_OnCommand(Command As String)
Log(Command)
End Sub
Sub Media_OnButton(Intent As Intent) As Boolean
Log(Intent.ExtrasToString)
process_intent(Intent)
Return False
End Sub
#if java
import android.support.v4.media.session.MediaSessionCompat.*;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import anywheresoftware.b4a.BA;
import anywheresoftware.b4a.objects.IntentWrapper;
import android.os.Bundle;
import android.os.ResultReceiver;
import android.content.IntentFilter;
public static class MyReceiver extends BroadcastReceiver {
public MyReceiver() {
super();
}
@Override
public void onReceive(Context context, Intent intent) {
IntentWrapper baIntent = new IntentWrapper();
baIntent.setObject(intent);
processBA.raiseEventFromUI(null, "media_onbutton", baIntent);
abortBroadcast();
}
}
public static class MyCallback extends Callback {
public MyCallback() {
}
public void onCommand(String command, Bundle args, ResultReceiver cb) {
processBA.raiseEventFromUI(null, "media_oncommand", command);
}
public boolean onMediaButtonEvent(Intent mediaButtonIntent) {
IntentWrapper baIntent = new IntentWrapper();
baIntent.setObject(mediaButtonIntent);
Boolean b = (Boolean) processBA.raiseEvent(null, "media_onbutton", baIntent);
return b == null ? false : b;
}
}
#end if
Sub setSpeakerPhone(state As Int)
Dim s As Boolean = False
If state = 1 Then
s = True
End If
mod_vars.SpeakerPhoneState = s
If s Then
If Not(mod_vars.SpeakerPhoneRouted) Then
If s Then
' // dsiable headset microphone
reroute_speakerphone(0)
mod_vars.SpeakerPhoneRouted = True
v.Vibrate(100)
End If
End If
Else
If mod_vars.SpeakerPhoneRouted Then
mod_vars.SpeakerPhoneRouted = False
v.Vibrate(100)
End If
End If
End Sub
Sub reroute_speakerphone(state As Int)
Dim jo As JavaObject
jo.InitializeContext
Dim r As Reflector
Try
r.Target = jo.RunMethod("getSystemService", Array("audio"))
r.RunMethod4("setWiredDeviceConnectionState", Array (4, state, "device"), _
Array As String("java.lang.int", "java.lang.int", "java.lang.String"))
Catch
mod_vars.LastStarterMessage = LastException.Message
End Try
Log(mod_vars.LastStarterMessage)
End Sub
#End Region
MANIFEST
B4X:
'This code will be applied to the manifest file during compilation.
'You do not need to modify it in most cases.
'See this link for for more information: https://www.b4x.com/forum/showthread.php?p=78136
AddManifestText(
<uses-sdk android:minSdkVersion="4" android:targetSdkVersion="26"/>
<supports-screens android:largeScreens="true"
android:normalScreens="true"
android:smallScreens="true"
android:anyDensity="true"/>)
SetApplicationAttribute(android:icon, "@drawable/icon")
SetApplicationAttribute(android:label, "$LABEL$")
'End of default text.
AddManifestText(<uses-feature android:name="android.hardware.location.gps"/>)
'AddReceiverText(svc_power, <intent-filter>
' <action
' android:priority="2147483647"
' android:enabled="true"
' android:name="android.intent.action.HEADSET_PLUG"
' />
'' </intent-filter>)
AddApplicationText(
<receiver android:name="starter$MyReceiver">
<intent-filter android:priority="2147483647" >
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</receiver>)
' // permissions
AddPermission(android.permission.CALL_PHONE)
AddPermission(android.permission.SEND_SMS)
AddPermission(android.permission.MODIFY_AUDIO_SETTINGS)
AddPermission(android.permission.CONNECTIVITY_INTERNAL)
AddPermission(android.permission.BROADCAST_STICKY)
AddPermission(android.permission.MEDIA_CONTENT_CONTROL)
AddPermission(android.permission.MODIFY_PHONE_STATE)
AddPermission(android.permission.WAKE_LOCK)
AddPermission(android.permission.ACCESS_FINE_LOCATION)
AddPermission(android.permission.ACCESS_HEADSET_PLUG)
AddManifestText(<uses-feature android:name="android.hardware.location.gps"/>)
' // End of default text.
Thank you in advance and Thanks BGSoft too
Osvaldo