### StartApp - Hello World Example (Python) Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/app/StartApp.htm Launches the 'Hello World' application using its file path. This example demonstrates the Python syntax for starting an app and is only functional in an APK environment. ```python from native import app def OnStart(): app.StartApp( "/sdcard/DroidScript/Hello World/Hello World.js" ) ``` -------------------------------- ### Create and Start Audio Recorder (Python) Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/app/CreateAudioRecorder.htm Creates an AudioRecorder, sets the output file, and starts recording. Ensure the file path is valid and accessible. This example records for 5 seconds. ```python from native import app file = "/sdcard/demofile.wav" def OnStart(): global rec rec = app.CreateAudioRecorder() rec.SetFile( file ) rec.Start() app.ShowPopup( "Please speak" ) setTimeout( StopRecording, 5000 ) def StopRecording(): rec.Stop() app.ShowPopup( "Finished recording. Now playing" ) ply = app.CreateMediaPlayer() ply.SetFile( file ) ply.SetOnReady( ply.Play ) ``` -------------------------------- ### Show Camera Preview Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/app/CreateCameraView.htm Example demonstrating how to create a CameraView, set an OnReady callback, add it to a layout, and start the camera preview. ```javascript function OnStart() { lay = app.CreateLayout( "Linear", "VCenter,FillXY" ); cam = app.CreateCameraView( 0.8, 0.4 ); cam.SetOnReady( cam_OnReady ); lay.AddChild( cam ); app.AddLayout( lay ); } function cam_OnReady() { cam.StartPreview(); } ``` ```python from native import app def OnStart(): global cam lay = app.CreateLayout( "Linear", "VCenter,FillXY" ) cam = app.CreateCameraView( 0.8, 0.4 ) cam.SetOnReady( cam_OnReady ) lay.AddChild( cam ) app.AddLayout( lay ) def cam_OnReady(): cam.StartPreview() ``` -------------------------------- ### Get Media File Example Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/app/GetMediaFile.htm This example demonstrates how to use app.GetMediaFile to get a file path for a new PNG image in the 'Hello World' folder and then displays the path using an alert. The folder will be created if it doesn't exist. ```javascript function OnStart() { var path = app.GetMediaFile("Hello World", ".png"); app.Alert( path ); } ``` ```python from native import app def OnStart(): path = app.GetMediaFile("Hello World", ".png") app.Alert(path) ``` -------------------------------- ### StartApp - Hello World Example (JavaScript) Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/app/StartApp.htm Starts the 'Hello World' app located at the specified path. This function is only effective when run from an APK. ```javascript function OnStart() { app.StartApp( "/sdcard/DroidScript/Hello World/Hello World.js" ); } ``` -------------------------------- ### OnStart Event Example Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/intro/AppEvents.htm Demonstrates the OnStart event, which is called when DroidScript initializes. It shows how to check if the app has started. ```javascript setTimeout(OnLoad); function OnStart() { alert("called OnStart\nApp Started: " + app.IsStarted()); } function OnLoad() { alert("called OnLoad\nApp Started: " + app.IsStarted()); } ``` -------------------------------- ### Create and Start Audio Recorder (JavaScript) Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/app/CreateAudioRecorder.htm Creates an AudioRecorder, sets the output file, and starts recording. Ensure the file path is valid and accessible. This example records for 5 seconds. ```javascript var file = "/sdcard/demofile.wav"; function OnStart() { rec = app.CreateAudioRecorder(); rec.SetFile( file ); rec.Start(); app.ShowPopup( "Please speak" ); setTimeout( StopRecording, 5000 ); } function StopRecording() { rec.Stop(); app.ShowPopup( "Finished recording. Now playing" ); ply = app.CreateMediaPlayer(); ply.SetFile( file ); ply.SetOnReady( ply.Play ); } ``` -------------------------------- ### LoadPlugin Example (JavaScript) Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/app/LoadPlugin.htm Import an installed plugin into your app using its URL path. Ensure the plugin is installed and accessible via the provided URL. ```javascript app.LoadPlugin( "YourPluginUrl" ) ``` -------------------------------- ### OnStart Event Example (Python) Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/intro/AppEvents.htm Demonstrates the OnStart event in Python, which is called when DroidScript initializes. It shows how to check if the app has started. ```python setTimeout(OnLoad) def OnStart(): alert("called OnStart\nApp Started: " + app.IsStarted()) def OnLoad(): alert("called OnLoad\nApp Started: " + app.IsStarted()) ``` -------------------------------- ### Show Camera Preview Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/app/CreateCameraView.htm Initializes a CameraView and sets up a callback for when the camera is ready to start the preview. This is a fundamental setup for using the camera. ```javascript function OnStart() { lay = app.CreateLayout( "Linear", "VCenter,FillXY" ); cam = app.CreateCameraView( 0.8, 0.4 ); cam.SetOnReady( cam_OnReady ); lay.AddChild( cam ); app.AddLayout( lay ); } function cam_OnReady() { cam.StartPreview(); } ``` ```python from native import app def OnStart(): global cam lay = app.CreateLayout( "Linear", "VCenter,FillXY" ) cam = app.CreateCameraView( 0.8, 0.4 ) cam.SetOnReady( cam_OnReady ) lay.AddChild( cam ) app.AddLayout( lay ) def cam_OnReady(): cam.StartPreview() ``` -------------------------------- ### Main App Python Example Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/app/SendMessage.htm This Python code sets up the main application UI, including text display and buttons to interact with the service. It creates the service file, starts the service, and defines callbacks for service readiness and incoming messages. ```python def OnStart():     global txt     #Create the Service.js file     #(In regular usage create the file yourself)     app.WriteFile("Service.js", servicejs )     #Create a layout.     lay = app.CreateLayout( "linear", "VCenter,FillXY" )     #Create text control to display data from the service.     txt = app.CreateText( "", 0.4 )     txt.SetTextSize( 22 )     lay.AddChild( txt )     #Create an 'Send Message' button.     btn = app.CreateButton( "Send Message to Service", 0.6, 0.1 )     lay.AddChild( btn )     btn.SetOnTouch( lambda: svc.SendMessage("change") )     #Create a 'Stop Service' button.     btn = app.CreateButton( "Stop Service", 0.6, 0.1 )     lay.AddChild( btn )     btn.SetOnTouch( lambda: svc.Stop() )     #Add layout to app.     app.AddLayout( lay )     #Start/connect to our service.     svc = app.CreateService( "this", "this", OnServiceReady )     svc.SetOnMessage( OnServiceMessage )     #This will cause your service to start at boot.     #(Set it to "none" if you need to stop it starting)     #app.SetAutoBoot( "Service" ) #Called after our service has started. def OnServiceReady():     app.Debug( "Service Ready" ) #Called when messages comes from our service. def OnServiceMessage( msg ):     txt.SetText( "Count: " + msg ) ``` -------------------------------- ### Start Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/app/CreateWebServer.htm Starts the WebServer. ```APIDOC ## Start ### Description Start the server. ### Method Call ``` -------------------------------- ### Example UI Theme and Component Setup Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/UIDocs.htm Demonstrates how to set up a full-screen layout, add an app bar with icons, text controls, buttons for theme toggling and color changes, and a floating action button. This snippet is useful for initializing a DroidScript application's UI. ```javascript class Main extends App { onStart() { // Create a full screen layout. this.main = ui.addLayout( "main", "Linear", "VCenter,FillXY" ) this.main.setChildMargins(0, "20px", 0, "20px") // add an appbar this.apb = ui.addAppBar( this.main, "My App", "menu" ) // some appbar icons this.search = ui.addButton(this.apb.layout, "search", "icon") this.more = ui.addButton(this.apb.layout, "more_vert", "icon") // some text control ui.addText(this.main, "This is a text control.") // toggle dark and light theme this.btn = ui.addButton(this.main, "Toggle Theme", "", 0.7) this.btn.setOnTouch( this.changeTheme ) // change primary color this.btn = ui.addButton(this.main, "Set Primary", "Primary", 0.7) this.btn.setOnTouch( this.changePrimary ) // change secondary color this.btn = ui.addButton(this.main, "Set Secondary", "Secondary", 0.7) this.btn.setOnTouch( this.changeSecondary ) // some floating action button this.fab = ui.addFAB(this.main, "add", "secondary") } changeTheme() { ui.setTheme( ui.theme.dark ? "light" : "dark") } changePrimary() { ui.showColorPicker(null, null, function(value) { ui.setThemeColor(value) }) } changeSecondary() { ui.showColorPicker(null, null, function(value) { ui.setThemeColor(null, value) }) } } ``` -------------------------------- ### Basic Example Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/app/CreateToggle.htm A simple example demonstrating how to create a toggle button, set an OnTouch listener, and add it to the layout. ```APIDOC ## Example - Basic ### JavaScript ```javascript function OnStart() { lay = app.CreateLayout("Linear", "VCenter,FillXY"); tgl = app.CreateToggle("Toggle Me"); tgl.SetOnTouch(ShowState); lay.AddChild(tgl); app.AddLayout(lay); } function ShowState(isChecked) { app.ShowPopup("Checked = " + isChecked, "Short"); } ``` ### Python ```python def OnStart(): lay = app.CreateLayout("Linear", "VCenter,FillXY") tgl = app.CreateToggle("Toggle Me") tgl.SetOnTouch(ShowState) lay.AddChild(tgl) app.AddLayout(lay) def ShowState(isChecked): app.ShowPopup("Checked = " + isChecked, "Short") ``` ``` -------------------------------- ### Main App JavaScript Example Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/app/SendMessage.htm This JavaScript code sets up the main application UI, including text display and buttons to interact with the service. It creates the service file, starts the service, and defines callbacks for service readiness and incoming messages. ```javascript function OnStart() {     //Create the Service.js file     //(In regular usage create the file yourself)     app.WriteFile("Service.js", servicejs );     //Create a layout.     lay = app.CreateLayout( "linear", "VCenter,FillXY" );     //Create text control to display data from the service.     txt = app.CreateText( "", 0.4 );     txt.SetTextSize( 22 );     lay.AddChild( txt );     //Create an 'Send Message' button.     btn = app.CreateButton( "Send Message to Service", 0.6, 0.1 );     lay.AddChild( btn );     btn.SetOnTouch( function(){ svc.SendMessage("change"); } );     //Create a 'Stop Service' button.     btn = app.CreateButton( "Stop Service", 0.6, 0.1 );     lay.AddChild( btn );     btn.SetOnTouch( function(){ svc.Stop(); } );     //Add layout to app.     app.AddLayout( lay );     //Start/connect to our service.     svc = app.CreateService( "this", "this", OnServiceReady );     svc.SetOnMessage( OnServiceMessage );     //This will cause your service to start at boot.     //(Set it to "none" if you need to stop it starting)     //app.SetAutoBoot( "Service" ); } //Called after our service has started. function OnServiceReady() {     app.Debug( "Service Ready" ); } //Called when messages comes from our service. function OnServiceMessage( msg ) {     txt.SetText( "Count: " + msg ); } ``` -------------------------------- ### Hello World Example Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/global/I.htm A basic 'Hello World' example. This snippet demonstrates the fundamental output mechanism. ```JavaScript function OnStart() { app.Alert( "Hello World" ); } ``` -------------------------------- ### Create Overlay and Memory Monitor Example Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/app/CreateOverlay.htm This JavaScript snippet demonstrates how to create an overlay and use it to display a real-time memory monitor. It requires the app object and includes functions for starting the overlay and updating its display. ```javascript cfg.Portrait; function OnStart() { app.ToBack(); lay = app.CreateLayout( "Linear" ); img = app.CreateImage( null, .3, .1 ); img.SetBackColor("#66333333"); img.SetAutoUpdate( false ); lay.AddChild( img ); ovl = app.CreateOverlay(); ovl.AddLayout( lay, 0.8, app.GetTop() ); app.Animate( Update, 1 ); } var lst = new Array(100).fill(1e5); function Update( time ) { var mem = app.GetMemoryInfo(); lst.push( Math.round( 100 * mem.avail / mem.total ) - 50 ); lst = lst.slice( -100 ); img.Clear(); img.SetPaintColor( "red" ); img.DrawLine( 0, mem.threshold / mem.total, 1, mem.threshold / mem.total ); img.SetPaintColor( "white" ); img.DrawSamples( lst, 50 ); img.Update(); } ``` -------------------------------- ### Example - Basic Usage Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/ui/addDialog.htm This example demonstrates how to create and show a basic dialog with 'Disagree' and 'Agree' actions. ```APIDOC ## Example - Basic Usage ### JavaScript ```javascript class Main extends App { onStart() { // Create a fullscreen layout this.main = ui.addLayout("main", "Linear", "VCenter,FillXY"); // Add a button to trigger the dialog this.btn = ui.addButton(this.main, "Show Dialog", "Contained,Primary"); this.btn.setOnTouch(this.showDialog); // Dialog content var bodyText = "Let Google help apps determine location. This means sending anonymous location data to Google, even when no apps are running."; // Initialize the Dialog this.dlg = ui.addDialog("Use Google's location service?", bodyText, "Disagree,Agree"); } showDialog() { this.dlg.show(); } } ``` ### Python ```python from hybrid import ui def OnStart(): global dlg # Create a fullscreen layout main = ui.addLayout("main", "Linear", "VCenter,FillXY") # Add a button to trigger the dialog btn = ui.addButton(main, "Show Dialog", "Contained,Primary") btn.setOnTouch(showDialog) # Dialog content bodyText = "Let Google help apps determine location. This means sending anonymous location data to Google, even when no apps are running." # Initialize the Dialog dlg = ui.addDialog("Use Google's location service?", bodyText, "Disagree,Agree") def showDialog(event): # event is not used in this example but is required by the callback signature dlg.show() ``` ``` -------------------------------- ### Hello World TextToSpeech Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/app/TextToSpeech.htm Plays the text 'DroidScript is awesome!' using the default TextToSpeech engine settings. This is a basic example to get started. ```javascript function OnStart() { app.TextToSpeech( "DroidScript is awesome!", 1.0, 1.0 ); } ``` -------------------------------- ### Hello World TextToSpeech Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/app/TextToSpeech.htm Plays the text 'DroidScript is awesome!' using the default TextToSpeech engine settings in Python. This is a basic example to get started. ```python from native import app def OnStart(): app.TextToSpeech("DroidScript is awesome!", 1.0, 1.0) ``` -------------------------------- ### Get Sensor Names Example Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/app/CreateSensor.htm This example demonstrates how to get a list of available sensor names on the device. ```APIDOC ## Get Sensor Names ### Description Retrieves a comma-separated string of all available sensor names on the device. ### Method sns.GetNames() ### Returns - **string:** A comma-separated list of sensor names. ``` -------------------------------- ### Orientation Sensor Example Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/app/CreateSensor.htm This example demonstrates how to use the Orientation sensor to get the device's azimuth, pitch, and roll. ```APIDOC ## Orientation Sensor ### Description Creates an Orientation sensor to monitor the device's rotation. ### Method sns = app.CreateSensor( "Orientation" ) sns.SetOnChange( sns_OnChange ) sns.Start() ### Parameters - **sns_OnChange( azimuth, pitch, roll, time )** - Callback function that is called when the sensor detects a change. - **azimuth** (number) - The device's rotation around the Z-axis. - **pitch** (number) - The device's rotation around the X-axis. - **roll** (number) - The device's rotation around the Y-axis. - **time** (number) - The timestamp of the event. ``` -------------------------------- ### Get Router Address Example (JavaScript) Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/app/GetRouterAddress.htm Demonstrates how to get the router's IP address and display it using an alert box. ```javascript function OnStart() { var ip = app.GetRouterAddress(); app.Alert(ip); } ``` -------------------------------- ### Get Application Path Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/app_ApplicationInformation.htm Retrieves the installation path of the application. ```APIDOC ## GetAppPath ### Description Retrieves the installation path of the application. ### Method GET ### Endpoint /app/GetAppPath ### Parameters None ### Response #### Success Response (200) - **appPath** (string) - The file system path where the application is installed. ``` -------------------------------- ### txp.GetLineStart Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/MUI/CreateTextParagraph.htm Gets the starting position of a line in the text control. ```APIDOC ## txp.GetLineStart ### Description Get line start. ### Method Not specified (assumed to be a method call on a text object) ### Parameters - **line** (integer) - Required - The line number. ### Returns - **startPosition** (integer) - The starting position of the line. ``` -------------------------------- ### Create and Start Web Server Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/app/CreateWebServer.htm Initializes a web server on a specified port, sets the root folder for serving files, and starts the server. It also defines a callback for handling incoming messages. ```javascript serv = app.CreateWebServer( 8080 ); serv.SetFolder( app.GetAppPath() ); serv.SetOnReceive( serv_OnReceive ); serv.Start(); ``` -------------------------------- ### app.InstallApp Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/app/InstallApp.htm Starts the installation process of an apk file from your local drive. ```APIDOC ## app.InstallApp ### Description Starts the installation process of an apk file from your local drive. ### Method Signature `app.InstallApp( apkFile: String, callback?: Function, options?: String ) → Boolean` ### Parameters #### apkFile - **Type**: String - **Description**: Path to the APK file (e.g., "/absolute/..." or "relative/..."). #### callback (Optional) - **Type**: Function - **Signature**: `callback( packageName: String, status: String )` - **Description**: A function to be called after the installation process. #### options (Optional) - **Type**: String - **Description**: Additional options for the installation process. ``` -------------------------------- ### Example - Sleep and Wake (Python) Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/app/WakeUp.htm Demonstrates how to put the device to sleep and then wake it up after a delay using SetTimeout. Ensure the app has necessary permissions for sleep/wake functionality. ```python from native import app def OnStart(): app.GoToSleep() app.SetTimeout("app.WakeUp()", 5000) ``` -------------------------------- ### Show Installed Apps (JavaScript) Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/app/GetInstalledApps.htm Displays a list of installed application package names in a UI list. This example demonstrates basic usage of GetInstalledApps and CreateList. ```javascript function OnStart() { app.ShowProgress(); var lay = app.CreateLayout( "linear" ); var list = app.GetInstalledApps(); lst = app.CreateList( "", 1, 1 ); lay.AddChild( lst ); for(var i in list) { var a = list[i]; lst.AddItem(a.packageName); } app.AddLayout(lay); app.HideProgress(); } ``` -------------------------------- ### Web Server Python Setup Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/app/CreateWebServer.htm Sets up the web server in Python, writes the HTML file, displays the server address, and creates the UI elements for interaction. It also configures the web server to serve files from the app's path and handle incoming messages. ```python from native import app indexhtml = """ WebSockets Demo count = 0; function Connect() { // Open web socket to phone. ws = new WebSocket( "ws://" + window.location.host ); ws.onopen = ws_onopen; ws.onmessage = ws_onmessage; ws.onclose = ws_onclose; ws.onerror = ws_onerror; } function Send() { ws.send( "Hello " + count++ ); } function ws_onopen() { id_info.innerHTML = "Socket Open"; } function ws_onmessage( msg ) { id_info.innerHTML = msg.data; } function ws_onclose() { id_info.innerHTML = "Socket Closed"; } function ws_onerror(e) { id_info.innerHTML = "Socket Error: " + e.data; }

DroidScript WebSockets Demo

Ready
""" count = 0 def OnStart(): global txt, serv, ip, txtMsg # Create the Index.html file # note: in regular use move the html to a separate file app.WriteFile( "Index.html", indexhtml ) ip = app.GetIPAddress() app.Alert( ip +":8080", "Type the following address into your browser" ) app.PreventWifiSleep() lay = app.CreateLayout( "linear", "VCenter,FillXY" ) txt = app.CreateText( "No connected clients.", 0.8, 0.3, "AutoScale,MultiLine" ) txt.SetTextSize( 22 ) lay.AddChild( txt ) txtMsg = app.CreateText( "", 0.8, 0.3, "AutoScale,MultiLine" ) txtMsg.SetTextSize( 22 ) lay.AddChild( txtMsg ) btn = app.CreateButton( "Send Message", 0.4, 0.1) btn.SetMargins( 0, 0.05, 0, 0 ) btn.SetOnTouch( SendMessage ) lay.AddChild( btn ) app.AddLayout( lay ) serv = app.CreateWebServer( 8080 ) serv.SetFolder( app.GetAppPath() ) serv.SetOnReceive( serv_OnReceive ) serv.Start() ``` -------------------------------- ### Example - Get Funfact (JavaScript) Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/app/HttpRequest.htm Demonstrates how to make a GET request to fetch data from a URL and process the response. Requires a callback function to handle the reply. ```javascript var address = "http://www.randomfunfacts.com"; app.HttpRequest( "GET", address, null, null, handleReply ); function handleReply( error, reply ) { if( error ) alert( reply ); else { var funfact = reply.slice( reply.indexOf("") + 3, reply.indexOf("") ); alert( funfact ); } } ``` -------------------------------- ### GetLineStart Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/app/CreateTextEdit.htm Gets the starting character position of a specific line in the TextEdit object. ```APIDOC ## GetLineStart ### Description Gets the starting character position of a specific line in the TextEdit object. ### Method GetLineStart ### Parameters - **line** (Number) - Required - The line number. ### Returns - **Number:** The starting character position of the line. ``` -------------------------------- ### Copy Folder Example (Python) Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/app/CopyFolder.htm This Python example shows how to create a folder and copy its contents to the /sdcard directory, followed by a verification step. ```python from native import app def OnStart(): app.MakeFolder("myFolder") app.CopyFolder("myFolder", "/sdcard/myFolder") if app.FolderExists("/sdcard/myFolder"): app.ShowPopup("myFolder exists in /sdcard/!") else: app.ShowPopup("myFolder does not exist in /sdcard/!") ``` -------------------------------- ### Show Installed Apps (Python) Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/app/GetInstalledApps.htm Displays a list of installed application package names in a UI list. This example demonstrates basic usage of GetInstalledApps and CreateList in Python. ```python from native import app def OnStart(): app.ShowProgress() lay = app.CreateLayout("linear") list = app.GetInstalledApps() lst = app.CreateList("", 1, 1) lay.AddChild(lst) for i in range(len(list)): a = list[i] lst.AddItem(a.packageName) app.AddLayout(lay) app.HideProgress() ``` -------------------------------- ### Get Notification ID - JavaScript Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/app/GetNotifyId.htm Use this function to get the ID of the notification that started your app. If an ID is returned, it can be displayed; otherwise, a new notification is created and shown. ```javascript function OnStart() { var id = app.GetNotifyId(); if( id ) app.Alert( id, "Notification ID" ); else { not = app.CreateNotification(); not.SetMessage( "You have an urgent notification", "Press me!", "Do as the title says." ); not.Notify( 1234 ); setTimeout( app.Exit, 2000 ); } } ``` -------------------------------- ### Copy Folder Example Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/app/CopyFolder.htm Demonstrates how to create a folder and then copy its contents to the /sdcard directory. It also includes a check to verify if the folder was successfully copied. ```javascript function OnStart() { app.MakeFolder("myFolder"); app.CopyFolder("myFolder", "/sdcard/myFolder"); if(app.FolderExists("/sdcard/myFolder")) app.ShowPopup("myFolder exists in /sdcard/!"); else app.ShowPopup("myFolder does not exist in /sdcard/!"); } ``` -------------------------------- ### Example - Get Funfact (Python) Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/app/HttpRequest.htm Demonstrates how to make a GET request to fetch data from a URL and process the response using Python syntax. Requires a callback function to handle the reply. ```python from native import app address = "http://www.randomfunfacts.com" app.HttpRequest("GET", address, None, None, handleReply) def handleReply(error, reply): if error: app.Alert(reply) else: funfact = reply[reply.index("") + 3: reply.index("")] app.Alert(funfact) ``` -------------------------------- ### Basic ShowKeyboard Example Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/app/ShowKeyboard.htm Demonstrates how to show the keyboard for a TextEdit control. Ensure the TextEdit control has focus before calling ShowKeyboard. ```javascript function OnStart() { lay = app.CreateLayout( "linear", "VCenter,FillXY" ); edt = app.CreateTextEdit( "Hell World" ); edt.Focus(); lay.AddChild( edt ); app.AddLayout( lay ); app.ShowKeyboard(edt ); } ``` -------------------------------- ### Get Apk Builder Version or DroidScript Version Source: https://github.com/droidscript/docs/blob/master/files/markup/en/intro/08 Best Practices.md Determines and returns the version of the Apk Builder plugin if installed, or the DroidScript version if the app is built as an APK. Displays a message if the plugin is not installed. ```Python def getBuilderVersion(): msg = "Apk Builder plugin not installed" path = app.GetPrivateFolder("Plugins") + "/apkbuilder/Version.txt" if app.FileExists(path): msg = "Apk Builder version " + app.ReadFile(path) elif app.IsAPK(): msg = "APK built with " + str(round(app.GetDSVersion(), 2)) #round and convert to string. return msg ``` -------------------------------- ### Example - Get Saved Data Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/app/GetData.htm Demonstrates how to save data using app.SetData and then retrieve it using app.GetData. ```javascript function OnStart() { app.SetData( "myvar", "Hello World!" ); var data = app.GetData("myvar"); app.Alert( data, "Saved Data:" ); } ``` ```python from native import app def OnStart(): app.SetData("myvar", "Hello World!") data = app.GetData("myvar") app.Alert(data, "Saved Data:") ``` -------------------------------- ### Initialize and Configure Drawer Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/ui/addDrawer.htm This example shows how to initialize a drawer with content and dynamically change its anchor position and width based on user selection. It includes setting up lists for navigation within the drawer. ```javascript class Main extends App { onStart() { // Creates a fullscreen layout with objects vertically centered. this.main = ui.addLayout( "main", "Linear", "VCenter,FillXY") // Adds a select control to the main layout. this.sel = ui.addSelect(this.main, ["Left", "Top", "Right", "Bottom"], "Radio,Outlined", 0.7) this.sel.label = "Select anchor position" // Add a callback handler for `onChange` event of the select control. this.sel.setOnChange(this.onSelect) // Creates a linear layout for the drawer. this.drawerLay = ui.addLayout( null, "Linear" ) // Initialize the drawer by passing the drawer layout. this.drawer = ui.addDrawer( this.drawerLay, "left" ) var lst1 = [ [ "music_note", "Audios" ], [ "movie", "Videos" ], [ "insert_drive_file", "Documents" ] ] // Adds a list to the drawer layout. this.lstMenu1 = ui.addList( this.drawerLay, lst1, "Icon", 1 ) this.lstMenu1.setOnTouch( this.closeDrawer ) this.lstMenu1.label = "Main navigation" // Adds a divider into the drawer layout. ui.addDivider( this.drawerLay, 1 ) var lst2 = [ [ "mail", "All Mail" ], [ "inbox", "Inbox" ], [ "drafts", "Outbox" ], [ "send", "Sent" ] ] // Adds another list to the drawer layout. this.lstMenu2 = ui.addList( this.drawerLay, lst2, "Icon", 1 ) this.lstMenu2.label = "Secondary navigation" this.lstMenu2.setOnTouch( this.closeDrawer ) } openDrawer() { this.drawer.show() } closeDrawer( title ) { ui.showPopup( title ) this.drawer.hide() } onSelect( value ) { // Set the drawer anchor first this.drawer.anchor = value // Set the drawer width depending on anchor position if(value == "Top" || value == "Bottom") { this.drawer.width = 0.5 } else { this.drawer.width = 0.7 } // Open the drawer this.drawer.show() } } ``` -------------------------------- ### Basic Switch Settings Example Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/MUI/CreateSwitchSettings.htm Demonstrates the basic usage of MUI.CreateSwitchSettings to create a single toggleable setting. It shows how to initialize the UI, create the switch, and handle touch events. ```JavaScript function OnStart() { color = MUI.colors.teal app.InitializeUIKit(color.teal) lay = MUI.CreateLayout("Linear", "FillXY,VCenter") skb = MUI.CreateSwitchSettings("Enable Sound", 1) skb.SetOnTouch(OnTouch) lay.AddChild(skb) app.AddLayout(lay) } function OnTouch(text, value) { app.ShowPopup(text+" : "+value) } ``` ```Python def OnStart(): color = MUI.colors.teal app.InitializeUIKit(color.teal) lay = MUI.CreateLayout("Linear", "FillXY,VCenter") skb = MUI.CreateSwitchSettings("Enable Sound", 1) skb.SetOnTouch(OnTouch) lay.AddChild(skb) app.AddLayout(lay) def OnTouch(text, value): app.ShowPopup(text+" : "+value) ``` -------------------------------- ### Basic ShowKeyboard Example (Python) Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/app/ShowKeyboard.htm Demonstrates how to show the keyboard for a TextEdit control in Python. Ensure the TextEdit control has focus before calling ShowKeyboard. ```python from native import app def OnStart(): lay = app.CreateLayout("linear", "VCenter,FillXY") edt = app.CreateTextEdit("Hello World") edt.Focus() lay.AddChild(edt) app.AddLayout(lay) app.ShowKeyboard(edt) ``` -------------------------------- ### Get GFX Version Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/gfx/version.htm Retrieves the current version number of the GFX library. The versioning starts from 1.1 in DS182b2. ```APIDOC ## Get GFX Version ### Description Retrieves the current version number of the GFX library. The versioning starts from 1.1 in DS182b2. ### Method N/A (Direct property access or function call) ### Endpoint N/A ### Parameters N/A ### Request Example ```js var version = gfx.version; ``` ```python version = gfx.version ``` ### Response #### Success Response - **version** (String) - The GFX version number, e.g., "1.1" ``` -------------------------------- ### GetTop Example (Python) Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/app/GetTop.htm Demonstrates how to get the top border distance in Python. The value is returned as a fraction by default. ```python from native import app def OnStart(): top = app.GetTop() app.Alert(top, "Top") ``` -------------------------------- ### Choose WiFi Network Example (Python) Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/app/ChooseWifi.htm Demonstrates how to use the app.ChooseWifi function in Python to prompt the user to select a WiFi network. The callback function receives the selected SSID. ```python from native import app def OnStart(): lay = app.CreateLayout( "linear", "VCenter,FillXY" ) btnChoose = app.CreateButton( "Choose WiFi", 0.5, 0.1 ) btnChoose.SetOnTouch( btnChoose_OnTouch ) lay.AddChild( btnChoose ) app.AddLayout( lay ) def btnChoose_OnTouch(): app.ChooseWifi( "", "", OnWifiChoose ) def OnWifiChoose( ssid ): app.ShowPopup( "User selected " + ssid ) ``` -------------------------------- ### GetTop Example (JavaScript) Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/app/GetTop.htm Demonstrates how to get the top border distance in JavaScript. The value is returned as a fraction by default. ```javascript function OnStart() { var top = app.GetTop(); app.Alert(top, "Top"); } ``` -------------------------------- ### Example - Direct HTML Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/app/CreateWebView.htm Illustrates creating a WebView and loading HTML content directly as a string. ```javascript function OnStart() { lay = app.CreateLayout( "linear", "VCenter,FillXY" ); web = app.CreateWebView( 0.8, 0.8 ); web.SetBackColor( "#00000000" ); lay.AddChild( web ); app.AddLayout( lay ); html = "
" + " " + "
" + " Hello World!

" + "
"; web.LoadHtml( html, "file:///Sys/" ); } ``` ```python from native import app def OnStart(): lay = app.CreateLayout( "linear", "VCenter,FillXY" ) web = app.CreateWebView( 0.8, 0.8 ) web.SetBackColor( "#00000000" ) lay.AddChild( web ) app.AddLayout( lay ) html = "
" + " " + "
" + " Hello World!

" + "
" web.LoadHtml( html, "file:///Sys/" ) ``` -------------------------------- ### Take Pictures Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/app/CreateCameraView.htm Example showing how to create a CameraView, set it up, and take a picture, saving it to a specified file path. ```javascript function OnStart() { lay = app.CreateLayout( "Linear", "VCenter,FillXY" ); cam = app.CreateCameraView( 0.8, 0.4 ); cam.SetOnReady( cam_OnReady ); lay.AddChild( cam ); btn = app.CreateButton( "Snap", 0.3, -1 ); btn.SetOnTouch( Snap ); lay.AddChild( btn ); app.AddLayout( lay ); } function cam_OnReady() { cam.SetPictureSize( 1024, 768 ); cam.StartPreview(); } function Snap() { cam.TakePicture( "/sdcard/MyPic.jpg" ); app.ShowPopup("Picture saved"); } ``` ```python from native import app def OnStart(): global cam lay = app.CreateLayout( "Linear", "VCenter,FillXY" ) cam = app.CreateCameraView( 0.8, 0.4 ) cam.SetOnReady( cam_OnReady ) lay.AddChild( cam ) btn = app.CreateButton( "Snap", 0.3, -1 ) btn.SetOnTouch( Snap ) lay.AddChild( btn ) app.AddLayout( lay ) def cam_OnReady(): cam.SetPictureSize( 1024, 768 ) cam.StartPreview() def Snap(): cam.TakePicture( "/sdcard/MyPic.jpg" ) app.ShowPopup("Picture saved") ``` -------------------------------- ### Show Default Orientation (Python) Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/app/GetDefaultOrientation.htm Get the default orientation and display it in an alert box. This function is called when the application starts. ```python def OnStart(): orient = app.GetDefaultOrientation() app.Alert( orient ) ``` -------------------------------- ### Python Example - Choose Image Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/app/ChooseImage.htm Demonstrates how to use app.ChooseImage in Python to open the photo gallery and handle the selected image path. ```python from native import app def OnStart(): lay = app.CreateLayout( "linear", "VCenter,FillXY" ) btnChoose = app.CreateButton("Choose Image", 0.5, 0.1) btnChoose.SetOnTouch(btnChoose_OnTouch) lay.AddChild(btnChoose) app.AddLayout(lay) def btnChoose_OnTouch(): app.ChooseImage("internal", OnChoose) def OnChoose(path): app.Alert("image path: " + path) ``` -------------------------------- ### Show Default Orientation (JavaScript) Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/app/GetDefaultOrientation.htm Get the default orientation and display it in an alert box. This function is called when the application starts. ```javascript function OnStart() { var orient = app.GetDefaultOrientation(); app.Alert( orient ); } ``` -------------------------------- ### Basic WebSocket Example Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/app/CreateWebSocket.htm Demonstrates how to create a WebSocket client, set up event handlers for connection opening and closing, and integrate with a WebServer. This is useful for real-time communication between clients and a server. ```JavaScript function OnStart() { ip = app.GetIPAddress(); lay = app.CreateLayout( "linear", "VCenter,FillXY" ); txt = app.CreateText( "No connected clients.", 0.8, 0.3, "AutoScale,log" ); txt.SetTextSize( 22 ); lay.AddChild( txt ); app.AddLayout( lay ); serv = app.CreateWebServer( 8080 ); serv.SetFolder( app.GetAppPath() ); serv.SetOnReceive( serv_OnReceive ); serv.Start(); var sock = app.CreateWebSocket( "sock1", ip, 8080 ); sock.SetOnOpen( OnSockOpen ); sock.SetOnClose( OnSockClose ); } function OnSockOpen() { app.ShowPopup( "Connected" ); var clients = serv.GetWebSockClients(); for(var i in clients) txt.Log( clients[i].id + ": " + clients[i].remoteAddress ); } function OnSockClose() { app.ShowPopup( "Disconnected" ); } ``` ```Python from native import app def OnStart(): global txt, serv ip = app.GetIPAddress() lay = app.CreateLayout("linear", "VCenter,FillXY") txt = app.CreateText("No connected clients.", 0.8, 0.3, "AutoScale,log") txt.SetTextSize(22) lay.AddChild(txt) app.AddLayout(lay) serv = app.CreateWebServer(8080) serv.SetFolder(app.GetAppPath()) serv.SetOnReceive(serv_OnReceive) serv.Start() sock = app.CreateWebSocket("sock1", ip, 8080) sock.SetOnOpen(OnSockOpen) sock.SetOnClose(OnSockClose) def OnSockOpen(): app.ShowPopup("Connected") clients = serv.GetWebSockClients() for i in clients: txt.Log(clients[i].id + ": " + clients[i].remoteAddress) def OnSockClose(): app.ShowPopup("Disconnected") ``` -------------------------------- ### Choose WiFi Network Example (JavaScript) Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/app/ChooseWifi.htm Demonstrates how to use the app.ChooseWifi function to prompt the user to select a WiFi network. The callback function receives the selected SSID. ```javascript function OnStart() { lay = app.CreateLayout( "linear", "VCenter,FillXY" ); btnChoose = app.CreateButton( "Choose WiFi", 0.5, 0.1 ); btnChoose.SetOnTouch( btnChoose_OnTouch ); lay.AddChild( btnChoose ); app.AddLayout( lay ); } function btnChoose_OnTouch() { app.ChooseWifi( "", "", OnWifiChoose ); } function OnWifiChoose( ssid ) { app.ShowPopup( "User selected " + ssid ); } ``` -------------------------------- ### Get Router Address Example (Python) Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/app/GetRouterAddress.htm Shows how to retrieve the router's IP address and present it to the user via an alert. ```python from native import app def OnStart(): ip = app.GetRouterAddress() app.Alert(ip) ``` -------------------------------- ### Get App Name Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/app/GetName.htm Returns the name of the APK application. For example, if your app runs in DroidScript, the name will be "DroidScript". ```APIDOC ## app.GetName() ### Description Returns the name of the APK application. ### Method app.GetName() ### Returns - **String**: The name of the application. ### Example - Get app Name (JavaScript) ```javascript function OnStart() { name = app.GetName(); app.Alert( name ); } ``` ### Example - Get app Name (Python) ```python from native import app def OnStart(): name = app.GetName() app.Alert(name) ``` ``` -------------------------------- ### Example - Sleep and Wake Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/app/GoToSleep.htm Demonstrates putting the device to sleep and then waking it up after a delay. Ensure the WakeUp method is available and correctly implemented. ```javascript function OnStart() { app.GoToSleep(); setTimeout("app.WakeUp()", 5000) } ``` ```python def OnStart(): app.GoToSleep() setTimeout("app.WakeUp()", 5000) ``` -------------------------------- ### Get Keyboard Height Example Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/app/GetKeyboardHeight.htm Use this snippet to display the keyboard height when the keyboard is shown. It requires setting an on-show-keyboard callback. ```javascript function OnStart() { lay = app.CreateLayout( "linear" ); txt = app.CreateText( "Keyboard Height: ", .8, -1, "left" ); lay.AddChild( txt ); edt = app.CreateTextEdit( "Hello World", .8, .4 ); lay.AddChild( edt ); app.SetOnShowKeyboard( OnKeyboardShow ); app.AddLayout( lay ); } function OnKeyboardShow() { var height = app.GetKeyboardHeight(); txt.SetText( "Keyboard Height: " + height + "px" ); } ``` ```python from native import app def OnStart(): global txt lay = app.CreateLayout("linear") txt = app.CreateText("Keyboard Height: ", .8, -1, "left") lay.AddChild(txt) edt = app.CreateTextEdit("Hello World", .8, .4) lay.AddChild(edt) app.SetOnShowKeyboard(OnKeyboardShow) app.AddLayout(lay) def OnKeyboardShow(shown): height = app.GetKeyboardHeight() txt.SetText("Keyboard Height: " + str(height) + "px") ``` -------------------------------- ### Main Application Layout Example Source: https://github.com/droidscript/docs/blob/master/docs/docs/latest/ui/addLayout.htm Demonstrates creating a fullscreen linear layout, adding a button, and handling touch events for both the layout and the button. This is useful for setting up the primary interface of an application. ```javascript class Main extends App { onStart() { // Create a fullscreen linear layout with objects vertically centered. this.main = ui.addLayout("main", "Linear", "VCenter", 1, 1) // Add a callback hanlder when the layout is touched this.main.setOnTouch( this.onTouch ) // Add a button control to the main layout this.btn = ui.addButton(this.main, "Button", "primary") // Add a callback handler when the button is touched this.btn.setOnTouch( this.btnTouch ) } onTouch() { ui.showPopup( "You click the layout!" ) } btnTouch() { if(this.main.backColor == "yellow") { this.main.backColor = "white" } else { this.main.backColor = "yellow" } } } ```