Filter
-
Content Type
-
Category
Mobile/Wearable
Visual Display
Digital Appliance
Platform
Recommendations
Filter
Learn Code Lab
codelabdesign a watch face with customizable edge complication slots and digital clock objective learn how to add customizable edge complication slots and a digital clock on your watch face using watch face studio overview watch face studio is a graphical authoring tool designed to help users create watch faces for the wear os smartwatch ecosystem, including the galaxy watch4 and its newer versions it offers intuitive and user-friendly features for designing visually appealing and customizable watch faces without requiring coding skills with watch face studio, users can incorporate various components into their watch faces, such as digital clocks these clocks can be designed with different variations and further customized through the galaxy watch interface in addition to digital clocks and other watch face components, users can integrate complications into their designs complications display information from data sources, such as battery indicators or step counts, directly on the watch face you can display additional information on the watch face by adding a complication slot a complication slot consists of complication components and a slot bound the components implement the layout, while the slot bound acts as a cutout through which the complication component appears there are five types of complication slots circle, line, small box, large box, and edge this code lab focuses on adding edge complication slots to your watch face starting from watch face studio 1 8 7 beta , users can define all supported font styles for digital clocks that can be customized on the physical watch the studio also added a feature allowing users to design watch faces with edge complication slots set up your environment you will need the following watch face studio latest version galaxy watch4 or newer smartwatch running on wear os api 34 or higher sample project here is a sample project for you to start coding in this code lab download it and start your learning experience! customizable edge complication and digital clock sample project 363 7 kb start your project to load the sample project in watch face studio click open project locate the downloaded file and click open the sample project includes a background image that you can customize by adjusting the hue, saturation, lightness, or opacity to suit your preference add edge complications to the watch face there are two types of edge complication slots that you can add to the watch face duo and quadrant both appear along the edge of the watch face duo edge complication slot - composed of right and left edge complications quadrant edge complication slot - composed of right top, right bottom, left bottom, and left top edge complications you can only select one type per project to fit the design of the sample project, add a quadrant edge complication slot click add component then, in the complication slot section, select edge > quadrant noteyou cannot change the placement, dimension, or rotation angle of an edge complication slot however, you can delete or hide unused complications from the layer list, expand the quadrant edge complication layer select the right top edge complication and the left bottom edge complication right-click and choose delete notealthough you have already deleted a complication slot, it can still be restored to do this, right-click on the quadrant edge complication layer in the layer list and select the option to add the previously deleted complication back configure complications after adding the edge complication slots, you can configure its settings from the layer list, click the right bottom edge complication to edit its properties in the properties pane, go to complication settings and choose the following type fixed default provider watch battery complication type range value range value complication layout progress bar + icon + text notesetting the complication as fixed limits the data and provider to the values you defined customization of this complication on the physical watch or wearable app is not possible to test the complication, go to the run pane and adjust the watch battery slider the bar indicator updates based on the value of the watch battery next, go to the properties of the left top edge complication and choose the following for complication settings type editable supported types short text default provider step count short text complication layout icon + text + title to test the complication, go to the run pane and adjust the step count slider the complication text changes as you change the value of the slider you can also adjust the properties of each complication component for example, when you open the properties of title, you can change its text color add a variable digital clock there are two ways to display a digital clock on watch faces using a variable digital clock and a non-variable digital clock to understand the concept of these two types, start by adding a variable digital clock component to display hours and a colon go to add component > digital clock > variable select colon and h h for the hour adjust the placement and rotation angle of both components to complement the design with a variable digital clock, you can customize each subcomponent creatively for example, you can make the font of the first digit of the hour h10 bigger than the second digit h or place them in different positions adjust the properties of the first and second digits of the hour to have the same font size but with slightly different color tints h10 color #f5f680ff font size 70 h color #fde997ff font size 70 on the other hand, a non-variable digital clock is less flexible but acts as a single component, making it ideal for simpler watch faces to add a non-variable digital clock to display minutes go to add component > digital clock > mm adjust its placement, rotation angle, and text color to complement the design use bitmap font for minutes watch face studio supports the use of truetype and bitmap fonts by default, all text-based components, such as digital clocks, use truetype fonts truetype is the most common font format, utilizing vector-based outlines to define characters bitmap fonts, on the other hand, consist of fixed-size, pixel-based representations of characters, which have smaller file sizes and render directly as pixels, offering faster performance on low-power devices in watch face studio, bitmap fonts are used to replace predefined dynamic content, such as dates, time, and weather, in text and digital clock components this allows you to incorporate custom visual elements that align with your creative vision while maintaining functionality to use bitmap font on your watch face, follow these steps select mm from the layer list go to properties > font setting and select bitmap font click the gear icon to open the bitmap font setting for bitmap font 1 set the default font size to 50 click the + icon to add and assign bitmap images for each digit locate your bitmap images, select the image for the corresponding digit, and click open once you're done adding and assigning bitmap images for each digit, click ok to display the bitmap font as minutes noteyou can also add more bitmap fonts by opening the dropdown menu and selecting add bitmap font make the font style of the digital clock customizable to make the digital clock more customizable, you can apply styles use the style tab to define font styles for a digital clock layer this provides users with more customization options for their watch face noteyou can apply styles to digital clock fonts and image-based layers for detailed information, refer to the style tab documentation from the layer list, choose variable_hh > h10 and go to the style tab click the + button in truetype font to add font styles add fonts with bold font weights such as montserrat-bold, oswald-bold, and roboto-bold then, click the customization editor button in the style set pane, click the text id button beside id_system_style_set click the add new button to add a new text id then, input the following id id_h10_font default value 1st digit hour font then, select the newly added text id this helps users identify which components they are changing when customizing the style on a physical watch repeat the same process for h, and this time, add fonts with a medium font weight for the text id, input the following id id_h_font default value 2nd digit hour font next, add styles to a layer that uses a bitmap font select mm from the layer list and go to the style tab click the + button in bitmap font, then select add bitmap font to add and assign bitmap images for each digit set default font size to 50 click ok and input the name of your bitmap font then, click the customization editor button and modify the text id of the newly added style set using the following values id id_mm_font default value minute font to test the font styles you set, go to the run pane and choose font styles from the dropdown menu this allows you to preview how the selected styles will appear on the watch face tipyou can merge the styles by navigating to the customization editor select the style sets you want to merge, right-click, and then choose merge set test the watch face in the run pane click the preview watch face icon move the step count and watch battery sliders to see data changes in the edge complications as previously mentioned, to observe changes in the digital clock, adjust the time slider and select the font styles from the dropdown menu in the style section to test your watch face on a smartwatch, you need to connect your watch to the same network as your computer in watch face studio, select run on device select the connected watch you want to test with if your watch is not detected automatically, click scan devices to detect your device or enter its ip address manually by clicking the + button when the watch face is launched, touch and hold the watch screen to access the edit mode tap customize to choose font styles and complications notethe always-on display is already set in the project to run the watch face successfully, you may need to configure its always-on display to avoid any error when you click run on device you're done! congratulations! you have successfully achieved the goal of this code lab now, you can design a watch face with customizable edge complication slots and digital clock using watch face studio! if you’re having trouble, you may download this file customizable edge complication and digital clock complete project 420 8 kb to learn more about watch face studio, visit developer samsung com/watch-face-studio
Learn Code Lab
codelabcontrol a smart bulb objective control a smart light bulb and change its color using bixby home studio overview bixby home studio bhs provides a simple and optimized way for accessing and controlling devices connected to your smartthings account you can quickly create complex diagrams and condition-based flows with bhs's user-friendly graphical user interface gui any device compatible with smartthings can be adjusted, controlled, and updated through bixby home studio for more information, visit getting started with bixby home studio set up your environment you will need the following samsung and smartthings account same email address smart rgb light bulb added to smartthings account virtual switch from smartthings labs if a smart rgb light bulb is not available a go to smartthings app b in the menu, select labs c choose virtual switch and click + to add a virtual switch d enter the name of virtual switch, location, and room notewhen you use a virtual switch, you can only create metadata and test the turning on and off functionality however, a physical smart rgb light bulb is necessary for testing other functions of this code lab activity, such as changing the light bulb color to red smartthings labs feature is available only on android app in us, canada, uk, india, and south korea start your project go to bhs bixbydevelopers com and sign in using your samsung account create a new project select your smartthings location and smart rgb light bulb or virtual switch for the device click create metadata from scratch then, click next choose powerswitch under bixby voice category select the powerswitch-turnoff and powerswitch-turnon voice intents click next input a project name and click done use a sample graph to switch on the bulb sample graphs are various example action flows that you can explore to learn more about the different voice intents, nodes, and smartthings capabilities you can use these sample graphs as starter points for your own devices each sample graph generically handles specific capabilities covered under various user utterances through the different voice intents for example, the turn on device sample graph works for any device it covers a variety of user utterances such as "turn on air conditioner ", "turn on fan ", "turn on speaker ”, and so on follow the steps below to use the turn on device sample graph to switch on the device go to voice intents > powerswitch-turnon > graph click the sample graphs icon on the left sidebar menu to show all the available sample graphs scroll down to see the turn on device sample graph or find it using the search bar drag and drop the sample graph into your powerswitch-turnon graph editor click try it to turn on your light bulb noteif you're using a virtual switch, it will turn on, but you won't be able to see the switch itself however, you can see the state of the virtual switch change from off to on in the smartthings app turn off the light bulb and add an alternative response the turn on device sample graph functions to switch on the device when the start node triggers the command node this graph can be modified to reverse its function, to do that copy the nodes from the powerswitch-turnon graph to the powerswitch-turnoff graph editor click the command node to open the node configuration pane and change the command from on to off right-click on the command node and change its comment to turn off device click try it to turn off the device after the command is performed, the response is either success or execution failed to make the light bulb more responsive, design the graph to provide different responses depending on whether the light bulb is already off or currently on a click the raw button and delete the existing code in the raw graph b copy and paste the following json into it and click add [{"nodeid" "5b648da1-a2c3-4912-baff-a559b968070e","nodever" "1 0","nodetype" "capabilityattribute","isstateful" true,"group" null,"inputports" {"device" {"nodes" [],"portinfo" null}},"triggerports" {"success" {"nodes" ["ccf1cbb8-c99b-439f-8246-bc9e7b7abfbf"],"portinfo" null},"failure" {"nodes" [],"portinfo" null}},"valueports" {},"triggerinports" {},"configurations" {"attribute" {"datatype" "datatype schema afcapabilityattribute","datavalue" {"component" "main","capability" "switch","attribute" "switch","property" {"name" "value","datatype" "datatype primitive afstring"}}},"required" {"datatype" "datatype primitive afboolean","datavalue" true}},"styles" {"x" 415,"y" 360}},{"nodeid" "ccf1cbb8-c99b-439f-8246-bc9e7b7abfbf","nodever" "1 0","nodetype" "equalcomparison","isstateful" true,"group" null,"inputports" {"leftvalue" {"nodes" ["5b648da1-a2c3-4912-baff-a559b968070e"],"portinfo" null},"rightvalue" {"nodes" ["8d9bf8ec-7cb1-4ffe-b4c0-b0424d394027"],"portinfo" null}},"triggerports" {"true" {"nodes" ["593250c4-9c19-4155-8f90-1318f9484aab"],"portinfo" null},"false" {"nodes" ["a9c4d152-eb0d-45d2-a2bd-20217de6fee6"],"portinfo" null}},"valueports" {},"triggerinports" {},"configurations" {"operator" {"datatype" "datatype operator equalcomparisonoperator","datavalue" "equalto"}},"styles" {"x" 585,"y" 332}},{"nodeid" "8d9bf8ec-7cb1-4ffe-b4c0-b0424d394027","nodever" "1 0","nodetype" "constant","isstateful" true,"group" null,"inputports" {},"triggerports" {},"valueports" {},"triggerinports" {},"configurations" {"value" {"datatype" "datatype primitive afstring","datavalue" "on"}},"styles" {"x" 415,"y" 500}},{"nodeid" "a9c4d152-eb0d-45d2-a2bd-20217de6fee6","nodever" "1 0","nodetype" "responsefeaturealreadyset","isstateful" true,"group" null,"inputports" {},"triggerports" {},"valueports" {},"triggerinports" {},"configurations" {},"styles" {"x" 635,"y" 480}}] c four nodes were added to the graph an attribute node that receives and passes an on or off value; a constant node with on as its value; an equal comparison node that compares if the attribute value is equal to the constant value; and a response already set node d rewire the graph to make it work properly by clicking the line coming from the start node and pressing the delete key e create a new line from the start node and connect it to the attribute node's trigger port f connect the equal comparison node's true port to the command node's trigger port g click the align button a couple of times to automatically organize the graph h then, click try it while the device is already off or already on, to observe the different responses change the light bulb's color based on time the command node has two capabilities that can adjust the color of light bulb, such as colorcontrol and colortemperature in this step, use these command node capabilities together with the get current datetime node and get datetime attributes node to set the light bulb's color to red or warm, if the current date time is 8 00 pm or later otherwise, the light bulb's color remains blue add the following json into the powerswitch-turnon graph [{"nodeid" "a31659e2-68fc-42b6-8076-01c2cb9fec23","nodever" "1 0","nodetype" "getcurrentdatetime","isstateful" true,"group" null,"inputports" {"__zoneid" {"nodes" [],"portinfo" null}},"triggerports" {"main" {"nodes" ["ea58c225-7d40-45b9-85d6-d8d941de9b2e"],"portinfo" null}},"valueports" {},"triggerinports" {},"configurations" {},"styles" {"x" 715,"y" 280}},{"nodeid" "ea58c225-7d40-45b9-85d6-d8d941de9b2e","nodever" "1 0","nodetype" "getdatetimeattributes","isstateful" true,"group" null,"inputports" {"input" {"nodes" ["a31659e2-68fc-42b6-8076-01c2cb9fec23"],"portinfo" null}},"triggerports" {"main" {"nodes" ["880416f6-d288-4b97-b763-2abd46bf2737"],"portinfo" null}},"valueports" {"seconds" {"name" "seconds"},"month" {"name" "month"},"hour" {"name" "hour"},"year" {"name" "year"},"minutes" {"name" "minutes"},"timestampinseconds" {"name" "timestampinseconds"},"day" {"name" "day"}},"triggerinports" {},"configurations" {},"styles" {"x" 815,"y" 280}},{"nodeid" "880416f6-d288-4b97-b763-2abd46bf2737","nodever" "1 0","nodetype" "comparablecomparison","isstateful" true,"group" null,"inputports" {"leftvalue" {"nodes" ["gr //node/ea58c225-7d40-45b9-85d6-d8d941de9b2e/value/hour"],"portinfo" null},"rightvalue" {"nodes" ["606796bc-d8ea-4421-942d-91544271615d"],"portinfo" null}},"triggerports" {"true" {"nodes" ["b2ba65ab-5e3e-4615-8d3a-79015a03d7bc"],"portinfo" null},"false" {"nodes" [],"portinfo" null}},"valueports" {},"triggerinports" {},"configurations" {"operator" {"datatype" "datatype operator comparablecomparisonoperator","datavalue" "greaterthanorequalto"}},"styles" {"x" 975,"y" 320}},{"nodeid" "606796bc-d8ea-4421-942d-91544271615d","nodever" "1 0","nodetype" "constant","isstateful" true,"group" null,"inputports" {},"triggerports" {},"valueports" {},"triggerinports" {},"configurations" {"value" {"datatype" "datatype primitive afinteger","datavalue" 20}},"styles" {"x" 815,"y" 420}},{"nodeid" "2b22b1a1-b9cb-4881-a861-3bf74ccd7847","nodever" "1 0","nodetype" "capabilitycommand","isstateful" true,"group" null,"inputports" {"device" {"nodes" [],"portinfo" null},"1 color" {"nodes" ["2389baa9-db45-4eb3-a40c-1166bf1e620f"],"portinfo" {"datatypes" ["undefined"],"minitems" 1,"maxitems" 1,"iscustomport" true}}},"triggerports" {"success" {"nodes" ["a31659e2-68fc-42b6-8076-01c2cb9fec23"],"portinfo" null},"failure" {"nodes" [],"portinfo" null}},"valueports" {},"triggerinports" {},"configurations" {"commands" {"datatype" "datatype util aflist","datavalue" [{"datatype" "datatype schema afcapabilitycommand","datavalue" {"component" "main","capability" "colorcontrol","command" "setcolor","arguments" [{"datatype" "datatype schema afcommandargument","datavalue" {"name" "color","optional" false,"datatype" "datatype primitive afjsonobject"}}]}}]}},"styles" {"x" 590,"y" 274}},{"nodeid" "2389baa9-db45-4eb3-a40c-1166bf1e620f","nodever" "1 0","nodetype" "constant","isstateful" true,"group" null,"inputports" {},"triggerports" {},"valueports" {},"triggerinports" {},"configurations" {"value" {"datatype" "datatype primitive afjsonobject","datavalue" {"hue" 55,"saturation" 55}}},"styles" {"x" 675,"y" 440}},{"nodeid" "b2ba65ab-5e3e-4615-8d3a-79015a03d7bc","nodever" "1 0","nodetype" "capabilitycommand","isstateful" true,"group" null,"inputports" {"device" {"nodes" [],"portinfo" null},"1 temperature" {"nodes" ["4d02fcda-df99-4c75-8b0a-73bb67933acd"],"portinfo" {"datatypes" ["undefined"],"minitems" 1,"maxitems" 1,"iscustomport" true}}},"triggerports" {"success" {"nodes" [],"portinfo" null},"failure" {"nodes" [],"portinfo" null}},"valueports" {},"triggerinports" {},"configurations" {"commands" {"datatype" "datatype util aflist","datavalue" [{"datatype" "datatype schema afcapabilitycommand","datavalue" {"component" "main","capability" "colortemperature","command" "setcolortemperature","arguments" [{"datatype" "datatype schema afcommandargument","datavalue" {"name" "temperature","optional" false,"datatype" "datatype primitive afinteger"}}]}}]}},"styles" {"x" 1115,"y" 380}},{"nodeid" "4d02fcda-df99-4c75-8b0a-73bb67933acd","nodever" "1 0","nodetype" "constant","isstateful" true,"group" null,"inputports" {},"triggerports" {},"valueports" {},"triggerinports" {},"configurations" {"value" {"datatype" "datatype primitive afinteger","datavalue" 500}},"styles" {"x" 975,"y" 478}}] rewire the graph as follows a delete the wire that connects command switch node's success port and response success node's trigger port b connect the command switch node's success port to the command colorcontrol node's trigger port c connect the command colortemperature node's success port to the response success node's trigger port d connect the numerical comparison node's false port to the response success node's trigger port noteadd a constant node with time zone, for example america/new_york, as string value if you want to test this section based on your local time click align then, click try it to see how the light bulb color change based on time you're done! congratulations! you have successfully achieved the goal of this code lab now, you can control a smart light bulb using bixby home studio if you face any trouble, you may download this file control bulb complete code 25 72 kb notewatch this short clip to quickly know how to navigate your way in this code lab and to see how easy it is to use bixby home studio to learn more about bixby, visit developer samsung com/bixby
Learn Code Lab
codelabmeasure blood oxygen level on galaxy watch objective create a health app for galaxy watch, operating on wear os powered by samsung, utilizing samsung health sensor sdk to trigger and obtain blood oxygen level spo2 measurement results overview samsung health sensor sdk provides means of accessing and tracking health information contained in the health data storage its tracking service gives raw and processed sensor data such as accelerometer and body composition data sent by the samsung bioactive sensor the latest bioactive sensor of galaxy watch runs powerful health sensors such as photoplethysmogram ppg , electrocardiogram ecg , bioelectrical impedance analysis bia , sweat loss, and spo2 see samsung health sensor sdk descriptions for detailed information set up your environment you will need the following galaxy watch4 or newer android studio latest version recommended java se development kit jdk 11 or later sample code here is a sample code for you to start coding in this code lab download it and start your learning experience! measuring blood oxygen level sample code 146 3 kb connect your galaxy watch to wi-fi go to settings > connection > wi-fi and make sure that wi-fi is enabled from the list of available wi-fi networks, choose and connect to the same one as your pc turn on developer mode and adjust its settings on your watch, go to settings > about watch > software and tap on software version 5 times upon successful activation of developer mode, a toast message will display as on the image below afterwards, developer options will be visible under settings tap developer options and enable the following options adb debugging in developer options find wireless debugging turn on wireless debugging check always allow on this network and tap allow go back to developer options and click turn off automatic wi-fi notethere may be differences in settings depending on your one ui version connect your galaxy watch to android studio go to settings > developer options > wireless debugging and choose pair new device take note of the wi-fi pairing code, ip address & port in android studio, go to terminal and type adb pair <ip address> <port> <wi-fi pairing code> when prompted, tap always allow from this computer to allow debugging after successfully pairing, type adb connect <ip address of your watch> <port> upon successful connection, you will see the following message in android studio’s terminal connected to <ip address of your watch> now, you can run the app directly on your watch turn on developer mode for health platform on your watch go to settings > apps > health platform quickly tap health platform title for 10 times this enables developer mode and displays [dev mode] below the title to stop using developer mode, quickly tap health platform title for 10 times to disable it start your project in android studio, click open to open existing project locate the downloaded android project from the directory and click ok check capabilities for the device to track data with the samsung health sensor sdk, it must support a given tracker type – blood oxygen level to check this, get the list of available tracker types and verify that the tracker is on the list in the connectionmanager java file, navigate to the isspo2available function, use a provided healthtrackingservice object to create a healthtrackercapability instance, send it to the checkavailabletrackers function, and assign its result to the availabletrackers list gettrackingcapability returns a healthtrackercapability instance in the healthtrackingservice object healthtrackingservicehealthtrackingservice initiates a connection to samsung's health tracking service and provides a healthtracker instance to track a healthtrackertype public healthtrackercapability gettrackingcapability provide a healthtrackercapability instance to get a supporting health tracker type list /****************************************************************************************** * [practice 1] check capabilities to confirm spo2 availability * * ---------------------------------------------------------------------------------------- * * hint replace todo 1 with java code * get healthtrackercapability object from healthtrackingservice * send the object to checkavailabletrackers ******************************************************************************************/ public boolean isspo2available healthtrackingservice healthtrackingservice { if healthtrackingservice == null return false; list<healthtrackertype> availabletrackers = null; //"todo 1" if availabletrackers == null return false; else return availabletrackers contains healthtrackertype spo2_on_demand ; } check connection error resolution using samsung health sensor sdk api, resolve any error when connecting to health tracking service in the connectionmanager java file, navigate to the processtrackerexception function, and check if the provided healthtrackerexception object has a resolution assign the result to hasresolution variable hasresolution function in the healthtrackerexception object checks if the api can fix the error healthtrackerexceptionhealthtrackerexception contains error codes and checks the error's resolution if there is a resolution, solving the error is available by calling resolve activity boolean hasresolution checks whether the given error has a resolution /******************************************************************************************* * [practice 2] resolve healthtrackerexception error * * ----------------------------------------------------------------------------------------- * * hint replace todo 2 with java code * call hasresolution on healthtrackerexception object ******************************************************************************************/ public void processtrackerexception healthtrackerexception e { boolean hasresolution = false; //"todo 2" if hasresolution e resolve callingactivity ; if e geterrorcode == healthtrackerexception old_platform_version || e geterrorcode == healthtrackerexception package_not_installed observerupdater getobserverupdater notifyconnectionobservers r string novalidhealthplatform ; else observerupdater getobserverupdater notifyconnectionobservers r string connectionerror ; log e tag, "could not connect to health tracking service " + e getmessage ; } initialize spo2 tracker before the measurement starts, initialize the spo2 tracker by obtaining the proper health tracker object in the spo2listener java file, navigate to the init function using the provided healthtrackingservice object, create an instance of the spo2 tracker and assign it to the spo2tracker object gethealthtracker with healthtrackertype spo2_on_demand as an argument will create a healthtracker instance healthtrackingservicehealthtrackingservice initiates a connection to samsung's health tracking service and provides a healthtracker instance to track a healthtrackertype healthtracker gethealthtracker healthtrackertype healthtrackertype provides a healthtracker instance for the given healthtrackertype /******************************************************************************************* * [practice 3] initialize spo2 tracker * * ---------------------------------------------------------------------------------------- * * hint replace todo 3 with java code * initialize spo2tracker with proper samsung health sensor sdk functionality * call gethealthtracker on healthtrackingservice object * use healthtrackertype spo2_on_demand as an argument ******************************************************************************************/ void init healthtrackingservice healthtrackingservice { //"todo 3" } perform measurement for the client app to start obtaining the data through the sdk, it has to set a listener method on the healthtracker the application setups the listener when the user taps on the measure button each time there is new data, the listener callback receives it after the measurement is completed, the listener has to be disconnected due to battery drain, on-demand measurement should not last more than 30 seconds the measurement is cancelled if the final value is not delivered in time note that the sensor needs a few seconds to warm up and provide correct values, which adds to the overall measurement time the blood oxygen level values come in the ondatareceived callback of trackereventlistener in spo2listener java file, you can see the code for reading the value private final healthtracker trackereventlistener spo2listener = new healthtracker trackereventlistener { @override public void ondatareceived @nonnull list<datapoint> list { for datapoint data list { updatespo2 data ; } } }; private void updatespo2 datapoint data { int status = data getvalue valuekey spo2set status ; int spo2value = 0; if status == measurement_completed spo2value = data getvalue valuekey spo2set spo2 ; observerupdater getobserverupdater notifytrackerobservers status, spo2value ; } run unit tests for your convenience, you can find an additional unit tests package this lets you verify your code changes even without using a physical watch see instructions below on how to run unit tests right click on com samsung health spo2tracking test and execute run 'tests in 'com samsung health spo2tracking'' command if you completed all the tasks correctly, you can see that all the unit tests passed successfully run the app after building the apk, you can run the application on a connected device to measure blood oxygen level right after the app is started, it requests for user permission allow the app to receive data from the body sensors afterwards, it shows the application's main screen to get the blood oxygen level, tap on the measure button to stop the measurement, tap on the stop button you're done! congratulations! you have successfully achieved the goal of this code lab now, you can create a health app that measures blood oxygen level by yourself! if you're having trouble, you may download this file measuring blood oxygen level complete code 146 2 kb to learn more about samsung health, visit developer samsung com/health
Learn Code Lab
codelabcreate a smartthings edge driver for an iot bulb objective learn how to create and customize an edge driver for an iot bulb to seamlessly interoperate on the smartthings platform overview smartthings is a platform for iot devices to communicate within its ecosystem, enabling smarter living solutions that simplify everybody else's way of life there are multiple methods to connect an iot device to the smartthings platform, one of which is through a smartthings hub hub connected devices connect to a smartthings-compatible hub using matter, zigbee, z-wave, or lan protocols the smartthings-compatible hub allows devices that utilize these protocols to integrate within the smartthings platform, permitting users to view and control devices from the smartthings app to automate actions and more the connection from a smartthings device to a smartthings hub is made possible with edge drivers smartthings edge drivers serve as translators between the protocols used by the device and the smartthings platform these drivers enable the devices to run locally on the hub, offering many benefits including speed, reliability, and enhanced functionality learn more about edge drivers in the smartthings edge architecture section set up your environment you will need the following host pc running on windows 10 or higher or ubuntu 20 04 x64 visual studio code latest version recommended devices connected on the same network android mobile device with smartthings app installed with android 10 or higher smartthings station or smartthings hub onboarded with samsung account philips hue bulb smartthings connected device sample code here is a sample code for this code lab download it and start your learning experience! edge driver sample code 6 1 kb install smartthings cli you need to install smartthings cli as this is the main tool for developing apps and drivers for smartthings edge drivers to install smartthings cli, open a web browser and download the smartthings msi installer from the latest release open the smartthings cli setup in the downloaded file, then click next accept the license agreement terms, then click next select the destination path for installation and click next to begin the installation process, click install notethe windows installer may display a warning titled windows protected your pc to continue the installation, click more info > run anyway complete the setup by clicking finish to verify if smartthings cli is installed correctly, open the command prompt and run this command smartthings --version view and run available commands for smartthings cli with this command smartthings --help for a full list of commands, visit the smartthings cli commands notethe smartthings cli supports an automatic login flow that launches a browser window, prompting the user to log in with a samsung account and grant the cli permissions to access the user's account start your project after downloading and extracting the sample code containing the project files, click file > open folder in visual studio code to open it locate the sample code directory and click select folder once finished, the project files are seen on the explorer menu set the bulb's color configuration in init lua, under the device_init function, write the code below to set the bulb's colors and its transition time local colorcontrol = clusters colorcontrol local philips_hue_colors = { {0xed, 0xc4}, -- red {0xae, 0xe3}, -- blue {0x2c, 0xc3}, -- yellow {0x53, 0xd3}, -- green {0xca, 0x08}, -- white } local index = 1 local transition_time = 0 --1/10ths of a second -- when sent with a command, these options mask and override bitmaps cause the command -- to take effect when the switch/light is off local options_mask = 0x01 local options_override = 0x01 device send colorcontrol server commands movetohueandsaturation device, philips_hue_colors[5][1], philips_hue_colors[5][2], transition_time, options_mask, options_override local timer = device thread call_on_schedule 1, function local hue = philips_hue_colors[index][1] local sat = philips_hue_colors[index][2] device send colorcontrol server commands movetohueandsaturation device, hue, sat, transition_time, options_mask, options_override index = index + 1 % 6 if index == 0 then index = 1 end end, "color_schedule_timer" save the file and open either the command prompt or terminal notemake sure that the path directory in your cli contains the project file build and upload your edge driver in the terminal, type the following command to build and upload your edge driver package to the smartthings cloud smartthings edge drivers package create a private channel create a new channel for your edge driver and enter the following channel details smartthings edge channels create channel name smartthings edge driver channel channel description channel for sdc2024 channel terms of service url www smartthings com enroll the smartthings hub in your channel enroll your hub in your newly created channel and select the corresponding channel and hub smartthings edge channels enroll assign the edge driver to your channel assign your driver to the created channel smartthings edge channels assign install the edge driver to your hub install the created edge driver from your channel to your own hub smartthings edge drivers install control the bulb via smartthings app on your mobile phone, launch the smartthings app and tap the + icon once you're on the add device page, tap scan nearby make sure that the philips light bulb is turned on wait for the light bulb to be visible once visible, tap done now, observe the blinking and changing colors of your bulb you're done! congratulations! you have successfully achieved the goal of this code lab now, you can create an edge driver for smartthings devices that can be integrated into the smartthings ecosystem! if you're having trouble, you may download this file edge driver complete code 8 6 kb to learn more about smartthings hub connected devices and edge drivers, visit smartthings hub connected devices smartthings edge driver documentation
Learn Code Lab
codelabcreate a daily step counter on galaxy watch objective create a native app for galaxy watch, operating on wear os powered by samsung, using health platform to read your daily steps overview health platform provides a unified and straightforward way for accessing a wide range of health and wellness related data with health platform api, you may easily read and write data stored in health platform on android and wear os powered by samsung applications can have access to these secured data only with explicit user consent additionally, users may disable access to the data at any point in time see health platform descriptions for detailed information set up your environment you will need the following galaxy watch4 or newer android studio latest version recommended java se development kit jdk 11 or later sample code here is a sample code for you to start coding in this code lab download it and start your learning experience! health step count sample code 119 87 kb turn on developer mode and adjust its settings on your watch, go to settings > about watch > software and tap on software version 5 times upon successful activation of developer mode, a toast message will display as on the image below afterwards, developer options will be visible under settings tap developer options and enable the following options adb debugging debug over wi-fi turn off automatic wi-fi connect your galaxy watch to wi-fi go to settings > connection > wi-fi and make sure that wi-fi is enabled from the list of available wi-fi networks, choose and connect to the same one as your pc when successfully connected, tap a wi-fi network name, swipe down, and note the ip address you will need this to connect your watch over adb from your pc connect your galaxy watch to android studio in android studio, go to terminal and type adb connect <ip address as mentioned in previous step> when prompted, tap always allow from this computer to allow debugging upon successful connection, you will see the following message in android studio’s terminal connected to <ip address of your watch> now, you can run the app directly on your watch start your project after downloading the sample code containing the project files, in android studio click open to open existing project locate the downloaded android project stepcount from the directory and click ok check dependency and app manifest in the dependencies section of stepcount/app/build gradle file, see the appropriate dependency for health platform dependencies { implementation com google android libraries healthdata health-data-api 1 0 0-alpha01' // } notelibrary might update from time to time if necessary, choose the version suggested by android studio request for data permissions before accessing any data through health platform, the client app must obtain necessary permissions from the user in permissions java, create a permission instance to trigger relevant permission screen and obtain required consent from end user data type name intervaldatatypes steps read access accesstype read /******************************************************************************************* * [practice 1] build permission object grand permissions for read today's steps * - set interval data type of steps * - set read access type ------------------------------------------------------------------------------------------- * - hint uncomment lines below and fill todos with * 1 for interval data type intervaldatatypes steps * 2 for read access accesstype read ******************************************************************************************/ permission stepsreadpermission = permission builder // setdatatype "todo 1 1 " // setaccesstype "todo 1 2 " build ; make a query to aggregate today’s steps create read request with all necessary information to read data through health platform api the answer from the platform will be asynchronous with the result from which you can get all the data you are interested in follow the steps below to get today's steps count in stepsreader java, create a readaggregateddatarequest with cumulativeaggregationspec instance data type name intervaldatatypes steps /******************************************************************************************* * [practice 2] build read aggregated data request object for read today's steps * - set interval data type of steps ------------------------------------------------------------------------------------------- * - hint uncomment line below and fill todo 2 with * 1 for interval data type intervaldatatypes steps ******************************************************************************************/ readaggregateddatarequest readaggregateddatarequest = readaggregateddatarequest builder settimespec timespec builder setstartlocaldatetime localdatetime now with localtime midnight build // addcumulativeaggregationspec cumulativeaggregationspec builder "todo 2 1 " build build ; read cumulative steps count from cumulativedata set variable steps value to 0l it is the count of daily steps get aggregatedvalue object using cumulativedata api cumulativedataaggregateddata representing total of intervaldata over a period of time e g total steps in a day public aggregatedvalue gettotal check the result if it is not null, get aggregated value using aggregatedvalue api aggregatedvaluevalue fields aggregated over a period of time only numeric fields longfield, doublefield can be included in aggregation public long getlongvalue returns all longfields and their values that are already set add value to the daily steps result counter /******************************************************************************************* * [practice 3] read aggregated value from cumulative data and add them to the result * - get aggregatedvalue from cumulativedata object * - get steps count from aggregatedvalue object ------------------------------------------------------------------------------------------- * - hint uncomment lines below and replace todo 3 with parts of code * 1 get aggregatedvalue object 'obj' using cumulativedata gettotal * 2 get value using obj getlongvalue and add to the result ******************************************************************************************/ long steps = 0l; if result != null { list<cumulativedata> cumulativedatalist = result getcumulativedatalist ; if !cumulativedatalist isempty { for cumulativedata cumulativedata cumulativedatalist { //"todo 3 1 " //"todo 3 2 " } } } return steps; run unit tests for your convenience, you will find an additional unit tests package this will let you verify your code changes even without using a physical watch see instruction below on how to run unit tests right click on com samsung sdc21 stepcount test and execute run 'tests in 'com samsung sdc21 stepcount'' command if you completed all the tasks correctly, you will see all the unit tests passed successfully run the app after building the apk, you can run the application on a connected device to see real-life aggregated steps count measured by a smartwatch right after the app is started, it will request for the user permission allow the app to receive data of the activity afterwards, the application main screen will be shown it will automatically display today’s step count tap on refresh button to read current steps count from health platform you're done! congratulations! you have successfully achieved the goal of this code lab now, you can create a daily step counter app by yourself! if you're having trouble, you may download this file health step count complete code 119 79 kb learn more by going to health platform
Learn Code Lab
codelabtrack deadlift exercise on galaxy watch objective create a native app for galaxy watch, operating on wear os powered by samsung, using health services to track deadlift exercise this app measures repetition count, calories burned, and time spent during the exercise overview health services provides a simple and unified way for accessing a wide range of health and wellness related data with health services api, you will no longer need to develop your own algorithms processing sensors data in order to compute metrics like heart rate, steps counts, distance, calories burned, and other more these are now accessible through health services embedded on wearables operating on wear os powered by samsung see health platform descriptions for detailed information set up your environment you will need the following galaxy watch4 or newer android studio latest version recommended java se development kit jdk 11 or later sample code here is a sample code for you to start coding in this code lab download it and start your learning experience! health track deadlift sample code 132 83 kb turn on developer mode and adjust its settings on your watch, go to settings > about watch > software and tap on software version 5 times upon successful activation of developer mode, a toast message will display as on the image below afterwards, developer options will be visible under settings tap developer options and enable the following options adb debugging debug over wi-fi turn off automatic wi-fi connect your galaxy watch to wi-fi go to settings > connection > wi-fi and make sure that wi-fi is enabled from the list of available wi-fi networks, choose and connect to the same one as your pc when successfully connected, tap a wi-fi network name, swipe down, and note the ip address you will need this to connect your watch over adb from your pc connect your galaxy watch to android studio in android studio, go to terminal and type adb connect <ip address as mentioned in previous step> when prompted, tap always allow from this computer to allow debugging upon successful connection, you will see the following message in android studio’s terminal connected to <ip address of your watch> now, you can run the app directly on your watch start your project after downloading the sample code containing the project files, open your android studio and click open to open an existing project locate the downloaded android project deadlift from the directory and click ok check dependency and app manifest in the dependencies section of gradle scripts > build gradle module app file, see the appropriate dependency for health services dependencies { implementation 'androidx health health-services-client 1 0 0-beta03' // } notesince the library might update from time to time, it is recommended to choose the version suggested by android studio in androidmanifest xml file, note the following <queries> element <queries> <package android name="com google android wearable healthservices" /> </queries> section with requests for necessary permissions <uses-permission android name="android permission body_sensors" /> <uses-permission android name="android permission activity_recognition" /> check capabilities to check what can be measured during an exercise, you need to check its capabilities go to app > java > com samsung sdc21 deadlift open the deadliftutil java file and navigate to the checkcapabilities method an inner class c definition implements the methods of the futurecallback interface within this definition, define the onsuccess method to retrieve the exercise type capabilities public void onsuccess exercisecapabilities result { objects requirenonnull result ; log i tag, "got exercise capabilities" ; /*********************************************************************************** * [practice 1] define the onsuccess method * * - hint uncomment lines below and replace todo 1 * call getexercisetypecapabilities method of result object, * passing already initialized t as an argument **********************************************************************************/ final exercisetype t = exercisetype deadlift; // final exercisetypecapabilities capabilities = "todo 1" // final exerciseconfig builder builder = exerciseconfig builder t ; // builder setdatatypes capabilities getsupporteddatatypes ; // exerciseconfigbuilder = builder; } next, implement the findcapabilitesfuture method to get a callback with exercisecapabilities getcapabilitiesasync returns the exercisecapabilities of the exerciseclient for the device static listenablefuture<exercisecapabilities> findcapabilitiesfuture exerciseclient client { /******************************************************************************************* * [practice 1] create a listenablefuture object that will get a callback with * with exercise capabilities choose the correct method from exerciseclient * * - hint uncomment line and replace null with todo 2 * for checking capabilities use getcapabilitiesasync method ******************************************************************************************/ return null; //"todo 2"; } start the exercise inside the startexercise method, there is a call to the futures addcallback method this method adds a callback function that executes when the asynchronous operation of starting the exercise completes set an update callback for the exercise client within the onsuccess method of the callback function public void onsuccess void result { log i tag, "successfully started" ; /*************************************************************************** * [practice 2] set an update callback * * - hint uncomment lines below and fill todos * 1 make appropriate call of setupdatecallback method * and pass exerciseupdatelistener object as an argument * 2 change ismeasurementrunning flag value to true **************************************************************************/ // exerciseclient setupdatecallback "todo 3 1 " ; log i tag, "successfully set update listener" ; // "todo 3 2 " } in the deadlift java file, call the startexercise method in onbuttonclickhelper public void onbuttonclickhelper { /******************************************************************************************* * [practice 2] start the exercise using a method from deadliftutil java * * - hint uncomment line below and fill todo 4 * call startexercise method on util object * ****************************************************************************************/ // "todo 4" } get the results go to the deadliftutil java file, and in the getnewrepsvalue method, call the getlatestmetrics method from the exerciseupdate class to get the data collected during the exercise store the data in the resultlist, where the last element holds the most up-to-date value of all your repetitions public long getnewrepsvalue exerciseupdate update, deltadatatype<long, intervaldatapoint<long>> datatype { /******************************************************************************************* * [practice 3] get the data collected during exercise * * - hint uncomment lines below and fill todo 5 * call getlatestmetrics method of exerciseupdate object * then, get the data of appropriate type * for this, you can use dedicated method getdata , passing datatype as an argument * ****************************************************************************************/ // final list<intervaldatapoint<long>> resultlist = "todo 5" // if !resultlist isempty { // final int lastindex = resultlist size - 1; // return resultlist get lastindex getvalue ; // } return no_new_value; } run unit tests for your convenience, you will find an additional unit tests package this will let you verify your code changes even without using a physical watch see instruction below on how to run unit tests right click on com samsung sdc21 deadlift test > deadliftunittest and execute run 'deadliftunittest' command if you completed all the tasks correctly, you will see all the unit tests passed successfully run the app after building the apk, you can run the application on a connected device to measure actual deadlift parameters right after the app is started, it will request for the user permission allow the app to receive data of the activity afterwards, the application main screen will be shown before doing deadlifts, press the start button to track your exercise when done, tap on the stop button you're done! congratulations! you have successfully achieved the goal of this code lab now, you can create a deadlift exercise tracker app by yourself! if you're having trouble, you may download this file health track deadlift complete code 132 42 kb learn more by going to health platform
Learn Code Lab
codelabimplement keyevent callback by mapping air actions objective learn how to implement keyevent callback on your s pen remote by mapping the air actions to a car racing game overview s pen connects via bluetooth low energy ble to a device and the s pen framework manages the connection ble events are converted by the s pen framework into keyevents before sending to the app apps are able to handle s pen events by reusing existing keyevent callback without adding other interfaces collecting and sending s pen remote events to apps the s pen framework collects and manages keyevents to be received by the app, and are defined in xml format before making them public below is the process of the s pen remote event handling and sending s pen remote event-defined keyevents to apps ble event is sent to the s pen framework the s pen framework checks for the foreground app and looks for the keyevent that the app made public the found keyevent is sent to the app's keyevent callback the app performs the actions defined in the keyevent set up your environment you will need the following java se development kit 10 jdk or later android studio latest version recommended samsung galaxy device with s pen remote capability galaxy tab s6 series or newer galaxy s22 ultra or newer galaxy fold3 or newer sample code here is a sample code for you to start coding in this code lab download it and start your learning experience! air actions sample code 6 4 mb start your project in android studio, click open an existing android studio project locate the android project from the directory and click ok implement remote actions check for the activity to handle the keyevent in a manifest file, androidmanifest xml add <intent-filter> and <meta-data> elements to that activity androidmanifest xml resource file defining remoteactions must be specified for <meta-data> <?xml version="1 0" encoding="utf-8"?> <manifest xmlns android="http //schemas android com/apk/res/android" package="com example spenremote racingcar"> <application <activity android name=" mainactivity" <intent-filter> <action android name="com samsung android support remote_action" /> </intent-filter> <meta-data android name="com samsung android support remote_action" android resource="@xml/remote_action_sample"/> </activity> </application> </manifest> noteonly one remoteaction per app is allowed at the moment if you define remoteactions to several activities, all other except one may be ignored create an xml file under res/xml/ name the file with the same name as the resource specified previously create the desired <action> elements in the xml file created as seen below xml has a root element of <remote-actions>, and may include several <action> elements in addition, each <action> contains information about id, label, priority, trigger_key, etc if you want to map a default action to a specific gesture, you need to add a <preference> element <?xml version="1 0" encoding="utf-8"?> <remote-actions version="1 2"> <action id="pause_or_resume" label="@string/pause_or_resume" priority="1" trigger_key="space"> <preference name="gesture" value="click"/> <preference name="button_only" value="true"/> </action> <action id="move_left" label="@string/move_car_left" priority="2" trigger_key="dpad_left"> <preference name="gesture" value="swipe_left"/> <preference name="motion_only" value="true"/> </action> <action id="move_right" label="@string/move_car_right" priority="3" trigger_key="dpad_right"> <preference name="gesture" value="swipe_right"/> <preference name="motion_only" value="true"/> </action> <action id="restart" label="@string/restart" priority="4" trigger_key="ctrl+r"> <preference name="gesture" value="circle_cw|circle_ccw"/> <preference name="motion_only" value="true"/> </action> </remote-actions> implement keyevent callback apply the keyevent callback to the activity where remoteactions have been declared it is recommended to handle the sent keyevent at onkeydown tiplearn more about keyevent callback in android developers add the following keyevent callback as seen below space key pause or resume the racing game left key move the car to left direction right key move the car to right direction ctrl + r key restart the racing game @override public boolean onkeydown int keycode, keyevent event { if keycode == keyevent keycode_space { racingcar playstate state = racingcar getplaystate ; if state == racingcar playstate playing { pause ; } else { resume ; } } else if keycode == keyevent keycode_dpad_left { movecarto racingcar pos_left ; } else if keycode == keyevent keycode_dpad_right { movecarto racingcar pos_right ; } else if event getmetastate & keyevent meta_ctrl_on != 0 && keycode == keyevent keycode_r { restart ; } return super onkeydown keycode, event ; } notepay attention to cases when the child view consumes the keyevent for example, if the edittext is focused on a screen where the edittext co-exists, most keyevents will be consumed for text inputs or a cursor movement and they may not be sent to the activities or container layouts on this screen, you must specify the key code or key combination that the child view cannot consume run the app now, everything is ready when you install your app, make sure that your app icon appears properly in the settings, settings > advanced features > s pen > air actions you can now control the car in the game using air actions you're done! congratulations! you have successfully achieved the goal of this code lab now, you can map air actions events on a game or app by yourself! if you're having trouble, you may download this file air actions complete code 6 4 mb
tutorials iot
blogmatter is an open-source connectivity standard for smart home and internet of things (iot) devices. it is a secure, reliable, and seamless cross-platform protocol for connecting compatible devices and systems with one another. smartthings provides the matter virtual device application and the smartthings home apis to help you quickly develop matter devices and use the smartthings ecosystem without needing to build your own iot ecosystem. when matter was first introduced, because few devices supported it, platform companies struggled to test and optimize matter support on their own devices. to alleviate this issue, samsung smartthings developed the matter virtual device application, which can be used to test and optimize various device types, including those that have not yet been released. the matter virtual device is part of the matter open source project you can create and test matter devices virtually too. in this tutorial, you will learn how to create an occupancy sensor as a matter virtual device that you can control using the smartthings application. you will also gain an understanding of the concept of clusters on matter devices. for more information about smartthings matter, see matter in smartthings. prerequisites to follow along with this tutorial, you need the following hardware and software: host pc running windows 10 or higher or ubuntu 20.04 (x64) android studio (latest version recommended) java se development kit (jdk) 11 or higher devices connected to the same network: mobile device running android 8.0 oreo or higher mobile device with the smartthings application installed matter-enabled smartthings station onboarded with the same samsung account as the smartthings application ※ for ubuntu, to set up the development environment: step 1. turn on developer mode and enable usb debugging on your mobile device. step 2. install the required os-specific dependencies from your terminal: $ sudo apt-get install git gcc g++ pkg-config libssl-dev libdbus-1-dev \ libglib2.0-dev libavahi-client-dev ninja-build python3-venv python3-dev \ python3-pip unzip libgirepository1.0-dev libcairo2-dev libreadline-dev step 3. from the sdk manager in android studio, install sdk platform 26 and ndk version 22.1.7171670. step 4. register the ndk path to the path environment variable: export android_ndk_home=[ndk path] export path=$path:${android_ndk_home} step 5. install kotlin compiler (kotlinc) version 1.5.10. step 6. register the kotlinc path to the path environment variable. export kotlinc_home=[kotlinc path]/bin export path=$path:${kotlinc_home} implement the occupancy sensor device type to implement the occupancy sensor device type in the matter virtual device application: step 1. download the sample application project and open it in android studio. sample code - virtual device app (11.11mb) nov 21, 2023 step 2. build and run the sample application. the application implements an on/off switch device type as an example. step 3. go to the file path feature > main > java > com.matter.virtual.device.app.feature.main. step 4. to add the occupancy sensor device type to the application home screen, in the mainfragment.kt file, select the device type: notefor all code examples in this tutorial, look for "todo #' in the sample application to find the location where you need to add the code. // todo 1 mainuistate.start -> { val itemlist = listof( device.onoffswitch, // sample device type // todo 1 device.occupancysensor, // add the occupancy sensor ) retrieve cluster values clusters are the functional building block elements of the data model. a cluster can be an interface, a service, or an object class, and it is the lowest independent functional element in the data model. each matter device supports a defined set of relevant clusters that can interact with your preferred controller (such as smartthings). this allows for easy information retrieval, behavior setting, event notifications, and more. the following steps are implemented in the file occupancysensorviewmodel.kt at the path feature > sensor > java > com.matter.virtual.device.app.feature.sensor. to retrieve the relevant cluster values from the device through the viewmodel: step 1. retrieve the current occupancy status. the boolean value is used by occupancyfragment to update the ui. // todo 2 private val _occupancy: stateflow<boolean> = getoccupancyflowusecase() val occupancy: livedata<boolean> get() = _occupancy.aslivedata() step 2. retrieve the current battery status. the integer value is used by occupancyfragment to update the ui. //todo 3 private val _batterystatus: mutablestateflow<int> = getbatpercentremainingusecase() as mutablestateflow<int> val batterystatus: livedata<int> get() = _batterystatus.aslivedata() step 3. when the "occupancy" button in occupancyfragment is pressed, use the setoccupancyusecase() function to update the occupancy status boolean value. // todo 4 viewmodelscope.launch { timber.d("current value = ${_occupancy.value}") if (_occupancy.value) { timber.d("set value = false") setoccupancyusecase(false) } else { timber.d("set value = true") setoccupancyusecase(true) } } step 4. when the "battery" slider in occupancyfragment is moved, store the slider progress as the battery status. // todo 5 batterystatus.value = progress step 5. when the "battery" slider in occupancyfragment is moved, use the updatebatteryseekbarprogress() function to update the battery status value on the slider. use setbatpercentremainingusecase() to update the battery status integer value. // todo 6 viewmodelscope.launch { updatebatteryseekbarprogress(progress) setbatpercentremainingusecase(progress) } monitor cluster values the observe() function monitors for and reacts to changes in a cluster value. the following steps are implemented in the file occupancysensorfragment.kt at the path feature > sensor > java > com.matter.virtual.device.app.feature.sensor. to monitor changes in the virtual occupancy sensor’s cluster values: step 1. trigger updating the occupancy status of the virtual device when the ”occupancy” button is pressed. // todo 7 binding.occupancybutton.setonclicklistener { viewmodel.onclickbutton() } step 2. use the onprogresschanged() function to update the fragment ui through live data from the viewmodel. the onstoptrackingtouch() function triggers updating the battery status when touch tracking on the “battery” slider stops. // todo 8 binding.occupancysensorbatterylayout.titletext.text = getstring(r.string.battery) binding.occupancysensorbatterylayout.seekbardata = seekbardata(progress = viewmodel.batterystatus) binding.occupancysensorbatterylayout.seekbar.setonseekbarchangelistener( object : seekbar.onseekbarchangelistener { override fun onprogresschanged(seekbar: seekbar, progress: int, fromuser: boolean) { viewmodel.updatebatteryseekbarprogress(progress) } override fun onstarttrackingtouch(seekbar: seekbar) {} override fun onstoptrackingtouch(seekbar: seekbar) { viewmodel.updatebatterystatustocluster(seekbar.progress) } } ) step 3. monitor the occupancy status and update the fragment ui when it changes. // todo 9 viewmodel.occupancy.observe(viewlifecycleowner) { if (it) { binding.occupancyvaluetext.text = getstring(r.string.occupancy_state_occupied) binding.occupancybutton.setimageresource(r.drawable.ic_occupied) } else { binding.occupancyvaluetext.text = getstring(r.string.occupancy_state_unoccupied) binding.occupancybutton.setimageresource(r.drawable.ic_unoccupied) } } step 4. monitor the battery status and update the fragment ui when it changes. // todo 10 viewmodel.batterystatus.observe(viewlifecycleowner) { val text: string = getstring(r.string.battery_format, it) binding.occupancysensorbatterylayout.valuetext.text = html.fromhtml(text, html.from_html_mode_legacy) } test the virtual device to test the virtual occupancy sensor device: step 1. build and run the project on your android device. the application’s home screen shows the sample on/off switch device type and the occupancy sensor device type that you just implemented. step 2. to create a virtual occupancy sensor device, select occupancy sensor and follow the instructions to receive a qr code. step 3. within the smartthings application on the other mobile device, onboard the occupancy sensor by scanning the qr code. step 4. change the occupancy or battery status of the virtual occupancy sensor in the virtual device application. the values are synchronized to the smartthings application. conclusion this tutorial demonstrates how you can implement the occupancy sensor device type in the matter virtual device application and create a virtual occupancy sensor for testing purposes. to learn about implementing other device types, go to code lab (matter: create a virtual device and make an open source distribution). the code lab also describes how to contribute to the matter open source project.
HyoJung Lee
events game, uiux, health, mobile, galaxy watch, smarttv, marketplace, foldable
blogit's almost time again for the samsung developer conference (aka sdc). after a few years of limited travel, virtual-only events, and nasal swabs, we're excited to get back to a live event, if only for one day. as you may have seen on this site and in our social media accounts, sdc is scheduled for october 12, at the moscone conference center in san francisco. the keynote address and technical sessions from the live event will be streamed via youtube, and there will be additional virtual content available to view beginning october 13, on the conference web site. sdc is a special time for us at the samsung developers team worldwide. internally, we have members in many countries: south korea, philippines, the united kingdom, vietnam, brazil, poland, bangladesh, and the united states. we're all excited to come together each year to bring useful and informative content to you. we enjoy planning and staging the event each year and we all have great memories. in this post, we'll share some of our favorite experiences with you. behind the scenes we understand the boring details behind the scenes isn't as exciting to most, but for our events team, the challenge of planning and pulling off a major event is a thrill. most years, planning for sdc begins almost the moment the previous event is completed. the planners begin executing contracts with the venue, caterers, and the experiential vendor that handles all the small details. they meet weekly on a conference call, usually in the evenings for those in the us to talk with our counterparts in south korea. as the months move along, the teams secure contractors with audio-visual teams to run the massive wall of displays on the keynote stage, as well as the cameras in the rooms where sessions are held. we look through dozens of clothing catalogs to find apparel for attendees as well as employees. during these times, we plan out the social media notices, come up with topics for blog posts, and design the email campaigns that go out to hundreds of thousands of developers. we discuss the colors of signs in great detail to make sure each shade is exactly the right color. we talk to the technical teams to understand which new tech is ready for developers to use. we track down guest speakers from other companies to show how samsung works with so many partners. as the months go by, we're working more and more on sdc tasks. a few days prior to showtime, you will see many of our team on-site at the venue, setting up demo stations, wiping down counters, and making sure everything is "just right," so that you're amazed the moment you walk through those doors. best of galaxy store awards beginning in 2018, the samsung developers team started the best of galaxy store awards program as a way to show our appreciation for those developers and designers who bring their products to galaxy store. some of the top names in the world of gaming, productivity, and social media have received the awards. to name a few: riot games' league of legends: wild rift (2021 best strategy game) epic games' fortnite (2020 game of the year) spotify (2020 bixby capsule of the year) gameloft asphalt 9 (2019 best racing game) tiktok (2019 best social app) disney heroes (2018 best game) best of galaxy store winners at sdc while the 2018 and 2019 awards were presented live at sdc, the covid pandemic required us to make the awards show a virtual event. you can watch the 2020 and 2021 awards on youtube. the 2022 awards are scheduled for december 6, 2022, on youtube. stay tuned to the samsung developers channels on twitter, facebook, linkedin, and youtube to watch the awards show when it premieres. for a full list of samsung best of galaxy store awards winners, click here. before and after hours sdc isn't just all business though—the organizers and attendees also love to have fun. before the keynote, attendees could join groups stretching and going for a run through the city streets. others opted for calm and quiet with yoga at the expo hall stage. staying fit at sdc a tech conference wouldn't be complete without an after-hours party and sdc is no different. in 2014, the sdc crowd went to san francisco's famed exploratorium, where they experimented with science projects among tables of excellent food and drinks. attendees in 2016 experienced the beautiful asian art museum in san francisco. in 2017, attendees walked virtually through a murder mystery with samsung gear vr headsets. the 2019 sdc brought more excitement to the after-hours party. as the event was held at the end of october, the theme was "day of the dev," playing on the name of the holiday celebrated in november. a vr-powered interactive journey led players through a spooky experience, while halloween-themed goodies were available throughout the expo hall. a foggy mist permeated the place, while characters from the vr journey appeared in real life to the delight of the crowd. day of the dev at sdc technical sessions no matter your interests, if you're into tech, sdc probably has a topic that will pique your curiosity. whether you are into mobile design, voice control, smart devices, enterprise security, streaming media, or a good old-fashioned shoot-em-up game, you will find plenty of technical sessions to satisfy your need to know more. foldables and security are popular topics at sdc after you've taken in the experts' ideas in the technical sessions, you can start building your own ideas on samsung's platforms in the code lab area of the expo hall. at the code lab, you can talk with the actual developers of many of samsung's best products and learn from them. this interactive experience is also available to anyone at any time on the samsung developers web site. keynote and spotlight session the keynote presentation is always the subject of great speculation on the internet for days prior to sdc. samsung electronics president and ceo dj koh is a favorite each year. do you remember the 2018 sdc at moscone west, when senior vice president justin denison walked on stage to present the galaxy fold, the first foldable mobile device? that is one of many exciting moments on the first day of the event. revealing the galaxy fold the sdc keynote includes other memorable moments, such as the announcement of one ui, which brought a sensible and consistent design ethos to samsung mobile and wearable devices. bixby cto adam cheyer used his time on stage to show the power of ai, while also amazing and amusing the audience with his sleight-of-hand. the second day starts off with the spotlight session. the spotlight session is where samsung focuses on companies making a successful partnership with samsung platforms and products. compared to the flash and excitement of the keynote, the spotlight session is where executives and developers share their experiences with their peers. spotlight session highlights—behind the scenes with vitalik buterin; on stage with tim sweeney and john hanke some of the more memorable moments of the spotlight sessions include hosting a fireside chat of games and how to monetize them on mobile platforms. this session included epic games ceo tim sweeney and niantic labs ceo john hanke. another memorable spotlight session brought ethereum co-founder vitalik buterin to the stage with samsung's john jun to talk about the possibilities of blockchain for mobile devices. one final memory of the sdc spotlight session that's special to those of us on the samsung developers team, aside from putting all this together for you, was from 2018. the week before the event, one of the teams' members proposed to use the note9 with s pen to take a photo on stage and send the photo to twitter. in three days, they had the prototype working and tested. the team convinced vp yoon lee to perform this live demo on stage to close the event. as you can see below, the demo worked flawlessly. wrapping up after sdc is finished, the samsung developers team is there to put everything away. demo machines are disassembled and our booth is sent to the warehouse. we pack up leftover t-shirts and make sure we left the venue cleaner than we found it. after that, we have a well-earned party for ourselves and a good night's sleep. thank you for reading through our memories of sdc events in the past. please join us online, october 12, 2022, at 10 am pt, for the next samsung developer conference keynote. let us know your favorite moments from sdc. join us on twitter, facebook, linkedin, and youtube to continue the discussion.
tutorials game, mobile
blogintro foldable technology for mobile is a ground-breaking experience not only for users, but also for developers. the presence of many form factors, like immersive display, app continuity, flex mode, and ux optimization, challenge developers to think outside of the box to adapt to this technology. there are already a large number of blogs talking about general application considerations, but what about gaming on a foldable device? in this blog, we look at the challenges and new opportunities foldable devices present for mobile game development. this blog focuses on unity and unreal engine as they are the most common game engines for mobile development. however, a lot of the information applies to other engines as well. app continuity and multi-window mode firstly, let's establish that the large internal display is called the main display whilst the smaller external display is called the cover display. app continuity and multi-window mode are two key features of foldable smartphones. with app continuity, you can seamlessly transition between the cover display to the main display without needing to reopen the app. with multi-window, you can run multiple apps at once and multitask like never before. app continuity moving an app between the two displays affects the size, density, and aspect ratio of the display it can use. app continuity is enabled and disabled from the android manifest of the app: the <activity> element has a new attribute called resizeableactivity. if not set, this attribute defaults to true, thus enabling app continuity and assuming the app fully supports both app continuity and multi-window mode. if set to true then the application automatically attempts to resize when moving between displays, as shown in the video below. if set to false then the system still allows you to transition from the cover display to the main display but does not attempt to resize the application. instead, a new button appears, allowing the user to restart the application at a time of their choosing, as shown below. when the app transitions between the two displays, the activity is destroyed and recreated. as such, the app data needs to be stored and then used to restore the previous state. from testing, both unity and unreal engine appear to handle this process already. however, if you are developing on a custom engine, it is worth confirming that your engine/app can handle this. continue on cover screen by default, foldable devices simply lock the device when closing the main display. however, it is possible for users to disable this functionality for certain apps. in the device's display settings, there is an option called "continue on cover screen" that has to be enabled by the user. entering this menu displays a list of all applications on the device and enables users to set specific applications to not lock the device when closing the main display. if an application has resizeableactivity set to false then the option to enable this functionality is greyed out and is not available. if your application supports resizing and app continuity then you should make sure to test that this works as users may wish to enable this functionality on their device. multi-window mode multi-window mode can allow up to three apps to run at the same time in a split-screen arrangement (see left image) or for two apps to run in pop-up mode which keeps one app full-screen but creates another app in a smaller pop-up window (see right image). just like app continuity, this is enabled using the attribute resizeableactivity in the android manifest. if resizeableactivity is not set then it defaults to true. so again, it is recommended that you set this yourself to ensure that your app works as intended. app continuity without multi-window mode if you would like your app to support app continuity but don't want it to be used by the multi-window mode, then this is possible. first, you should set the resizableactivity attribute to false to disable both app continuity and multi-window mode. next use the following <meta-data> element in your <activity> element: <meta-data android:name="android.supports_size_changes" android:value="true" /> this re-enables the app continuity feature without enabling multi-window mode. game engine features to use if using existing game engines then there are several existing features that are useful if developing for foldable devices. this section provides a high-level look at these features. for more in-depth information, i recommend visiting the engine's documentation. unity unity is a very good engine for developing on foldable devices, requiring little to no setup to enable features for foldable devices. the engine automatically handles resizing of the application without any modifications required. the resizeableactivity attribute is controlled by an option in the player settings: resizable window. when enabled, resizeableactivity appears to be set to true; when disabled, resizeableactivity appears to be set to false. note this option is not available in older versions of unity. if this option is not present then you have to set the resizeableactivity manually. the engine also provides a very robust ui scaling system that helps to reduce the amount of work required to create a ui that works across both the cover display and main display. the canvas scaler and anchor system work very well with foldable devices and work to resize and position elements consistently across the two displays, thus preventing developers from having to create two ui designs (one for cover display and one for main display). unreal engine 4 unreal engine 4 is another good engine for developing on foldable devices, although it requires a little more work to get it set up for foldable devices. first of all, unreal engine 4 by default disables the resize event on android devices, however, it is possible to re-enable it in device profiles using the console variable: r.enablenativeresizeevent = 1 unreal engine 4 by default also has a max aspect ratio of 2.1. this is, however, too small for the cover display of some foldable devices which can result in black bars on either side of the image. fortunately, unreal engine makes this value easily changeable in the project settings: platform -> android -> max aspect ratio from my testing, 2.8 is a good value. however, i recommend users experiment to find the best value. unreal engine's umg (unreal motion graphics ui designer) has a comprehensive set of tools for creating responsive ui designs. this system automatically scales ui elements to fit the screen size, and the anchor system is also very useful for ensuring the ui elements are positioned correctly between the two displays. samsung remote test lab no matter what engine you use, the best way to ensure your app works well on a foldable device is to test it on a foldable device. samsung remote test lab has a range of foldable devices available for developers to test their applications on if getting hold of a physical device is too difficult or expensive. all you need to do is create a samsung account and you can start using these devices for testing. android jetpack windowmanager despite being very good engines for foldable game development, neither unity nor unreal currently provide information about the current state of the foldable device (that is, is it open/closed/halfway?, where is the fold positioned?, what is the fold's orientation? and so forth). however, android has recently created a new library as a part of their android jetpack libraries that enables developers to access this information and make use of it in their apps. android jetpack in their own words is "a suite of libraries to help developers follow best practices, reduce boilerplate code, and write code that works consistently across android versions and devices so that developers can focus on the code they care about." windowmanager is a new library from the android jetpack suite, intended to help application developers support new device form factors and multi-window environments. the library had its 1.0.0 release in january 2022, and targeted foldable devices but—according to the documentation—future versions will extend to more display types and window features. more technical resources this blogpost has an accompanying technical blogpost and code lab tutorial, demonstrating how to use the android jetpack windowmanager with both unity and unreal to take advantage of the flex mode feature of samsung's foldable devices. i recommend starting with the jetpack windowmanager blogpost to learn how to set up the windowmanager in java: https://developer.samsung.com/galaxy-gamedev/blog/en-us/2022/07/20/how-to-use-jetpack-window-manager-in-android-game-dev then, follow it up with the code labs to learn how to make use of the windowmanager to implement a simple flex mode setup in either unreal or unity: https://developer.samsung.com/codelab/gamedev/flex-mode-unreal.html https://developer.samsung.com/codelab/gamedev/flex-mode-unity.html also, visit our game developer community to join the discussion around mobile gaming and foldable devices. click here to find out more about other design considerations when designing apps for foldable devices and large screens. final thoughts foldable devices provide a richer experience than regular phones. hopefully, this blogpost and accompanying tutorial have provided you with the necessary information to begin taking advantage of these new form factors and start providing users a richer foldable experience. additional resources on the samsung developers site the samsung developers site has many resources for developers looking to build for and integrate with samsung devices and services. stay in touch with the latest news by creating a free account and subscribing to our monthly newsletter. visit the galaxy store games page for information on bringing your game to galaxy store and visit the marketing resources page for information on promoting and distributing your android apps. finally, our developer forum is an excellent way to stay up-to-date on all things related to the galaxy ecosystem.
Lochlann Henry Ramsay-Edwards
We use cookies to improve your experience on our website and to show you relevant advertising. Manage you settings for our cookies below.
These cookies are essential as they enable you to move around the website. This category cannot be disabled.
These cookies collect information about how you use our website. for example which pages you visit most often. All information these cookies collect is used to improve how the website works.
These cookies allow our website to remember choices you make (such as your user name, language or the region your are in) and tailor the website to provide enhanced features and content for you.
These cookies gather information about your browser habits. They remember that you've visited our website and share this information with other organizations such as advertisers.
You have successfully updated your cookie preferences.