• Learn
    • Code Lab
    • Foldables and Large Screens
    • One UI Beta
    • Samsung Developers Podcasts
  • Develop
    • Mobile/Wearable
    • Galaxy GameDev
    • Galaxy Themes
    • Galaxy Watch
    • Health
    • Samsung Blockchain
    • Samsung DeX
    • Samsung IAP
    • Samsung Internet
    • Samsung Pay
    • Samsung Wallet
    • View All
      • Galaxy AR Emoji
      • Galaxy Accessory
      • Galaxy Edge
      • Galaxy Z
      • Galaxy Performance
      • Galaxy FM Radio
      • Galaxy S Pen Remote
      • Galaxy Sensor Extension
      • PENUP
      • Samsung Automation
      • Samsung Neural
      • Samsung TEEGRIS
      • Samsung eSE SDK
    • Visual Display
    • Smart TV
    • Smart Hospitality Display
    • Smart Signage
    • Digital Appliance
    • Family Hub
    • Platform
    • Bixby
    • Knox
    • SmartThings
    • Tizen.NET
  • Design
    • Design System
    • One UI
    • One UI Watch
    • Smart TV
  • Distribute
    • Galaxy Store
    • TV Seller Office
    • Galaxy Store Games
    • Samsung Podcasts
  • Support
    • Developer Support
    • Remote Test Lab
    • Issues and Bugs Channel
    • Samsung Android USB Driver
    • Galaxy Emulator Skin
  • Connect
    • Blog
    • News
    • Forums
    • Events
    • Samsung Developer Conference
    • SDC22
    • SDC21
    • SDC19 and Previous Events
  • Sign In
Top Global Search Form
Recommendation
  • Blog
  • Code Lab
  • Foldable and Large Screen Optimization
  • Forums
  • Galaxy Emulator Skin
  • Galaxy GameDev
  • Health
  • Remote Test Lab
  • Samsung Developer Conference
  • SDC22
  • Watch Face Studio
All Search Form
Recommendation
    Suggestion
      All Search Form
      Filter
      Filter
      Filter
      • ALL
      • DOCS
      • SDK
      • API REFERENCE
      • CODE LAB (25)
      • BLOG
      • NEWS/EVENTS
      • CODE LAB
        api reference code lab blog news/events
      1. Learn
      2. Code Lab

      codelab

      Configure an App to Enable Drag and Drop in Multi-Window

      configure an app to enable drag and drop in multi-window objective learn how to implement drag and drop on a note-taking app when in multi-window mode. overview in galaxy fold and it's latest versions, the advantage of its larger display is to split its screen and simultaneously use up to three apps. in multi-window mode, you can split the screen with one window being the main focus, and the other two windows off to the side. all three windows are active, not just the largest one. you can multitask in either landscape or portrait mode, giving you even more flexibility. when using multi-window, drag & drop is one of the useful features when multitasking. drag and drop allows you to easily move data from one app to another. to provide users with better multitasking experience on samsung's foldable devices, developers need to optimize their apps to work on multi-window mode. set up your environment you will need the following: java se development kit (jdk) 8 or later android studio (latest version recommended) samsung galaxy fold, z fold2, z fold3, or newer remote test lab (if physical device is not available) requirements: samsung account java runtime environment (jre) 7 or later with java web start internet environment where port 2600 is available sample code here is a sample code for you to start coding in this code lab. download it and start your learning experience! multi-window (drag & drop) sample code (19.27 mb) start your project open android studio and click open an existing project. locate the downloaded android project (simplenotes_dragdrop) from the directory and click ok. make the app resizable to ensure that the app works in multi-window mode, you need to add an attribute in the manifest’s <activity> element. if you set android:resizeableactivity to true, the activity can be launched in multi-window or in pop-up view, and adapt different screen size. android:resizeableactivity= "true" noteif this attribute is set to true, the activity can be launched in split-screen and freeform modes. otherwise, it will disable multi-window display. remember to handle the changes required to fit your ux in small windows when in multi-window mode. for this code lab, you do not need to worry about the ux as it is already handled. register a drag event listener in newnote.kt, register a drag event listener object by calling setondraglistener for both title and description view of the app. title.setondraglistener(ondraglistener) desc.setondraglistener(ondraglistenerdescription) store the action type to a variable declare a variable to store the action type for the incoming event. val action: int = event.getaction() get and drop the text data inside the dragevent.action_drop, get the item from clipdata and check the mime type. if the mime type is set to text/plain, get the text value from the item object and allow the operation of drop. otherwise, simply show a toast message. val item: item = event.getclipdata().getitemat(0) var mtype = event.clipdescription.getmimetype(0) if(mtype == "text/plain" || mtype== "text/html"){ // gets the text data from the item. dragdata = item.text.tostring() }else{ toast.maketext(applicationcontext,"operation not allowed"+mtype,toast.length_long).show() return@ondraglistener true } tipin this code lab, to simplify the demonstration of implementing drag and drop, mime type or media type is set to plain text only. run the app after building the apk, you can run the optimized note-taking app and start dragging and dropping texts between apps in multi-window mode. if you don’t have any physical device, you can also test it on a remote test lab device. notewatch this tutorial video and know how to easily test your app via remote test lab. you're done! congratulations! you have successfully achieved the goal of this code lab. now, you can implement drag and drop in your app for your foldable device by yourself! if you're having trouble, you may download this file: multi-window (drag & drop) complete code (19.33 mb) to learn more about developing apps for galaxy foldable devices, visit: www.developer.samsung.com/galaxy-z

      https://developer.samsung.com/codelab/galaxy-z/multi-window-drag-drop.html
      1. Learn
      2. Code Lab

      codelab

      Add Boarding Passes, Tickets, and Coupons

      add boarding passes, tickets, and coupons objective learn how to integrate the add to wallet functionality with partner services, enabling users to add boarding passes, tickets, and coupons to samsung wallet. partnership request to create, manage, and monitor performance of wallet cards with the samsung wallet partners portal, you must become an official samsung partner. once done, you can fully utilize this code lab. you can learn more by visiting samsung wallet partner onboarding process, here in samsung developers. notein accordance with the applicable samsung partner agreements, this code lab covers setup and use of the samsung wallet partners portal for purposes of integrating the add to wallet functionality with partner sites. the use cases and corresponding code samples included are representative examples only and should not be construed as either recommended or required. overview samsung wallet is the secure, go-everywhere app for your essentials — credit cards, boarding passes, tickets, coupons, and more. all in one spot, all accessible with one swipe. users can conveniently access the samsung wallet by swiping it up from the bottom of the screen. various wallet cards of partners can be added to the samsung wallet, allowing users to quickly and easily access partners' contents, such as: boarding passes: registered boarding passes can remind the user of boarding time and help during check-in. depending on the integration level, it can provide status information updates related to flights, such as boarding gate changes or cancellations. tickets: registered tickets can provide additional information about the event and an alarm before expiration. ticket cards support event commodities for performances, sports, movies, and entrance. coupons: registered coupons for various channels can provide alarms before expiration and update usage status. notedepending on your country or region, some card types are not supported. if you need assistance, please contact us at developer.samsung.com/dashboard/support. the image below shows the process of managing wallet cards: for detailed description, see manage wallet cards. set up your environment you will need the following: samsung wallet from galaxy store samsung galaxy device that supports samsung wallet samsung wallet partners portal account internet browser, such as chrome intellij idea community edition samsung public key, partner public key, and private key (see encryption setting) start your project open your internet browser and go to the following sample partner sites: boarding pass - https://codesandbox.io/s/sdc-boarding-pass-template-3c4o0c ticket - https://codesandbox.io/s/sdc-ticket-template-8lgph7 coupon - https://codesandbox.io/s/sdc-coupon-template-rrw0bt click fork on each project to copy and modify the code. once done, three projects are automatically copied to your codesandbox account. modify the index.html later for the add to wallet integration. notethe next steps require a samsung wallet partners portal account. if you wish to check and test the complete code of these sample partner sites, you can jump to you're done! section of this code lab. otherwise, you can proceed to learn the process of integrating add to wallet functionality. create wallet cards now, go to samsung wallet partners portal and sign in using your samsung partner account. on the left sidebar menu, click wallet cards > create wallet card and enter wallet card details for the boarding pass as below: in wallet card template, choose [wallet] boardingpass as card type and boarding pass > airline as a subcategory. select samsung wallet boarding pass > airline as the card template. then, click done. you can choose from various types of wallet card templates optimized for partners such as boarding pass, ticket, and coupon. once all the details are entered and the correct template is selected, click save to set the wallet card status to draft. launch wallet cards you can launch and request activation of the cards by clicking the launch button. upon agreeing to proceed, the launch button text changes to launched and the card status becomes verifying. apply the add to wallet script the samsung wallet partners portal includes generated add to wallet scripts for every wallet card created. these scripts can be copied and inserted into partner apps (web and android) or via email/mms. go to [add to wallet script guide] of the card(s) you created. click show to see the scripts for web integration and copy the script under web button (js) code sample. notea statistical image beacon is added to the script for tracking effect analysis. below are generated add to wallet scripts of wallet cards created for this code lab: boarding pass:<script src="https://us-cdn-gpp.stg.mcsvc.samsung.com/lib/wallet-card.js" type="text/javascript"></script> <div id="target_id"></div> <script> samsungwallet.addbutton({ partnercode: "4030093436155138240", cardid: "3fre4kmmboq00", cdata: "${card data as jwt}", rdclickurl: "https://us-rd.mcsvc.samsung.com/statistics/click/addtowlt?ep=c50c3754feb24833b30c10b275bb6ab8;cc=gc;ii=1287098641030840334;co=4030093436155138240;cp=1288017491089625089;si=24;pg=101212967375212546;pi=aqz68ebxsx6mv9jsazxzaa;tp=4030093501522138240;li=0", rdimpressionurl: "https://us-rd.mcsvc.samsung.com/statistics/impression/addtowlt?ep=c50c3754feb24833b30c10b275bb6ab8;cc=gc;ii=1287098641030840334;co=4030093436155138240;cp=1288017491089625089;si=24;pg=101212967375212546;pi=aqz68ebxsx6mv9jsazxzaa;tp=4030093501522138240;li=0", targetid: "target_id", buttonid: "button_id", }); </script> ticket:<script src="https://us-cdn-gpp.stg.mcsvc.samsung.com/lib/wallet-card.js" type="text/javascript"></script> <div id="target_id"></div> <script> samsungwallet.addbutton({ partnercode: "4030093436155138240", cardid: "3fre4mp5mui00", cdata: "${card data as jwt}", rdclickurl: "https://us-rd.mcsvc.samsung.com/statistics/click/addtowlt?ep=c50c3754feb24833b30c10b275bb6ab8;cc=gc;ii=1287098641034510350;co=4030093436155138240;cp=1288017491089625089;si=24;pg=101212967375212546;pi=aqz68ebxsx6mv9jsazxzaa;tp=4030093588496138240;li=0", rdimpressionurl: "https://us-rd.mcsvc.samsung.com/statistics/impression/addtowlt?ep=c50c3754feb24833b30c10b275bb6ab8;cc=gc;ii=1287098641034510350;co=4030093436155138240;cp=1288017491089625089;si=24;pg=101212967375212546;pi=aqz68ebxsx6mv9jsazxzaa;tp=4030093588496138240;li=0", targetid: "target_id", buttonid: "button_id", }); </script> coupon:<script src="https://us-cdn-gpp.stg.mcsvc.samsung.com/lib/wallet-card.js" type="text/javascript"></script> <div id="target_id"></div> <script> samsungwallet.addbutton({ partnercode: "4030093436155138240", cardid: "3fre4p0otdv00", cdata: "${card data as jwt}", rdclickurl: "https://us-rd.mcsvc.samsung.com/statistics/click/addtowlt?ep=c50c3754feb24833b30c10b275bb6ab8;cc=gc;ii=1287098641019830286;co=4030093436155138240;cp=1288017491089625089;si=24;pg=101212967375212546;pi=aqz68ebxsx6mv9jsazxzaa;tp=4030093644822138240;li=0", rdimpressionurl: "https://us-rd.mcsvc.samsung.com/statistics/impression/addtowlt?ep=c50c3754feb24833b30c10b275bb6ab8;cc=gc;ii=1287098641019830286;co=4030093436155138240;cp=1288017491089625089;si=24;pg=101212967375212546;pi=aqz68ebxsx6mv9jsazxzaa;tp=4030093644822138240;li=0", targetid: "target_id", buttonid: "button_id", }); </script> paste the copied add to wallet script into the index.html file of the sample partner site. then, add the attributes below, to the samsungwallet.addbutton function. target: "wallet", showforced: true target sets the button’s name to samsung wallet ("wallet") or samsung pay ("pay"). by default, the value is "wallet". showforced is a flag to show or hide the button. by default, the button is hidden. otherwise, set the flag value to true. noteincluding the javascript library in the head tag and adding the rest of the script to the body tag is recommended. yet, it works if you paste it as is. generate and input the cdata the add to wallet script does not automatically include the cdata (encrypted card data) as it requires encryption for security purposes. cdata is the actual content data of wallet card and it has several formats based on card type. you can use the sample cdata generator created to serve the purpose of this code lab only. download the cdata generation sample code. locate and open the downloaded file in intellij idea. in the project folder, go to src > main > java > jwtgenerator.java. input your partner id as partner_code string value. public class jwtgenerator { private static final string partner_code = "insert_your_partner_id"; //same with partnercode of add to wallet script next, go to resources > sample > certificate and replace the pem files with samsung public key, your public key, and private key (see encryption setting). build the project. right-click on jwtgenerator class and click run 'jwtgenerator.main()' to create the cdata. different cdata must be created for each of the sample partner sites of this code lab. notethe generated cdata won't expire and can only be used for code lab testing. cdata must expire 30 seconds after creation for security purposes in actual application. lastly, go back to the index.html of the partner site and paste the generated cdata to the cdata attribute value of the addbutton sub-item. test the add to wallet button you can test the add to wallet button functionality integrated to the sample partner sites, directly on a mobile device with the samsung wallet app. access the url provided by codesandbox on samsung internet or any browser. click the samsung wallet button in each app to add the boarding pass, ticket, and coupon cards to the samsung wallet. tipthe add to wallet button only works for mobile devices with samsung wallet or samsung pay app, so it is recommended to handle exceptions like this. also, you can add a qr code feature for your site. users can scan the qr code using a compatible mobile device when the site is accessed via desktop or laptop. noteyou can see and monitor wallet card statistics by going to the portal's dashboard > wallet card statistics. you're done! congratulations! you have successfully achieved the goal of this code lab topic. now, you can integrate the add to wallet with your website by yourself! if you're having trouble, you may check the complete code below: boarding pass - https://codesandbox.io/s/sdc-boarding-pass-complete-67kvwh ticket - https://codesandbox.io/s/sdc-ticket-complete-pb720c coupon - https://codesandbox.io/s/sdc-coupon-complete-3n0ugf to learn more about samsung wallet, visit: developer.samsung.com/wallet

      https://developer.samsung.com/codelab/wallet/add-to-wallet-interface.html
      1. Learn
      2. Code Lab

      codelab

      Configure an App to Enable Copy and Paste in Multi-Window

      configure an app to enable copy and paste in multi-window objective learn how to implement copy and paste on a note-taking app when in multi-window mode. overview in galaxy fold and it's latest versions, the advantage of its larger display is to split its screen and simultaneously use up to three apps. in multi-window mode, you can split the screen with one window being the main focus, and the other two windows off to the side. all three windows are active, not just the largest one. you can multitask in either landscape or portrait mode, giving you even more flexibility. when using multi-window, copy & paste is one of the useful features when multitasking. copy and paste is a common feature used by many, to duplicate an object and place it in a desired location. to provide users with better multitasking experience on samsung's foldable devices, developers need to optimize their apps to work on multi-window mode. set up your environment you will need the following: java se development kit (jdk) 8 or later android studio (latest version recommended) samsung galaxy fold, z fold2, z fold3, or newer remote test lab (if physical device is not available) requirements: samsung account java runtime environment (jre) 7 or later with java web start internet environment where port 2600 is available sample code here is a sample code for you to start coding in this code lab. download it and start your learning experience! multi-window (copy & paste) sample code (19.48 mb) start your project open android studio and click open an existing project. locate the downloaded android project (simplenotes_copypaste) from the directory and click ok. make the app resizable to ensure that the app works in multi-window mode, you need to add an attribute in the manifest’s <activity> element. if you set android:resizeableactivity to true, the activity can be launched in multi-window, pop-up view and adapt different screen size. android:resizeableactivity= "true" noteif this attribute is set to true, the activity can be launched in split-screen and free-form modes. otherwise, it will disable multi-window display. remember to handle the changes required to fit your ux in small windows when in multi-window mode. for this code lab, you do not need to worry about the ux as it is already handled. get a reference to clipboardmanager class clipboardmanager provides methods to get and set the current primary clipboard data expressed as a clipdata object, which defines the protocol for data exchange between applications. in newnote.kt, get a reference to clipboardmanager class by invoking getsystemservice(clipboard_service). val clipboard = getsystemservice(context.clipboard_service) as clipboardmanager complete the copy operation now, create a new clipdata of simple text using newplaintext of clipboardmanager and pass it on setprimaryclip to complete the copy operation. val clip: clipdata = clipdata.newplaintext("simple text", textdata) clipboard.setprimaryclip(clip) get the text data from the clipboard return the clipdata by getting the primaryclip data from the clipboard. from the primaryclip, acquire the item using getitemat(0). val itemtext = clipboard.primaryclip?.getitemat(0)?.text run the app after building the apk, you can run the optimized app and test it by copying and pasting texts between apps when in multi-window mode. if you don’t have any physical device, you can also test it on a remote test lab device. tipwatch this tutorial video and know how to easily test your app via remote test lab. you're done! congratulations! you have successfully achieved the goal of this code lab. now, you can implement multi-window features such as copy and paste in your app by yourself! if you're having trouble, you may download this file: multi-window (copy & paste) complete code (19.53 mb) to learn more about developing apps for galaxy foldable devices, visit: www.developer.samsung.com/galaxy-z

      https://developer.samsung.com/codelab/galaxy-z/multi-window-copy-paste.html
      1. Learn
      2. Code Lab

      codelab

      Implement Multi-Window Picture-in-Picture on a Video Player

      implement multi-window picture-in-picture on a video player objective learn how to implement multi-window picture-in-picture (pip) feature on a video player app for a seamless viewing experience on foldable devices. overview android allows activities of apps to launch in a small window called picture-in-picture (pip) since android 8.0. it is a type of multi-window mode primarily used for video playback. pip allows the user to continue watching in a small window pinned to a corner of the screen while browsing content on the main screen or navigating between apps. set up your environment you will need the following: java se development kit (jdk) 8 or later android studio (latest version recommended) samsung galaxy fold, z fold2, z fold3, or z fold4 remote test lab (if physical device is not available) requirements: samsung account java runtime environment (jre) 7 or later with java web start internet environment where port 2600 is available sample code here is a sample code for you to start coding in this code lab. download it and start your learning experience! pip video player sample code (13.30 mb) start your project after downloading the sample project files, follow the steps below to open your project: in android studio, click open. locate the downloaded android project (videoplayer_challenge) from the directory and click ok. configure android manifest to support pip notetake a look and check the files of your project before starting to code. you can implement picture-in-picture in your app by configuring the manifest file and calling the enterpictureinpicturemode method. moreover, you need to consider that the multi-window and app continuity features work correctly in pip mode. to prevent the activity from restarting, handle the layout configuration change for mainactivity in the androidmanifest.xml file. this will ensure that it will not restart when there are layout changes from pip mode to full screen and vice versa. android:configchanges="screensize|smallestscreensize|screenlayout|orientation" picture-in-picture is not supported by default in android apps. set android:supportspictureinpicture to true in the manifest file. android:supportspictureinpicture="true" switch your video player to pip mode you want to trigger pip mode in your video player app when the user taps the home button. to implement pip mode, go to java > com.xyz.codelab and make the following changes to the mainactivity.kt file: override fun onuserleavehint() { enterpipmode() } noteenterpipmode() is a user-defined method. you can view its full implementation in the provided sample code. call enterpictureinpicturemode method in enterpipmode(), you need to call enterpictureinpicturemode(pictureinpictureparams) method with params set in the previous lines. val pictureinpictureparams = pictureinpictureparams.builder().setaspectratio(rational).build() enterpictureinpicturemode(pictureinpictureparams) run the app after building the apk, you can now run the video player app, enhanced with a pip mode. test it by playing a video while browsing the main screen or navigating between apps in multi-window mode. if you don’t have any physical device, you can also test it on a remote test lab device. tipwatch this tutorial video and know how to easily test your app via remote test lab. you're done! congratulations! you have successfully achieved the goal of this code lab. now, you can implement multi-window picture-in-picture on a video player app for foldable devices by yourself! if you're having trouble, you may download this file: pip video player complete code (13.19 mb) to learn more about developing apps for galaxy foldable devices, visit: developer.samsung.com/galaxy-z

      https://developer.samsung.com/codelab/galaxy-z/picture-in-picture.html
      1. Learn
      2. Code Lab

      codelab

      Integrate In-App Payment with Merchant Apps

      integrate in-app payment with merchant apps objective learn how to integrate in-app payment with your merchant apps using samsung pay sdk. partnership request to use the samsung pay sdk, you must become an official samsung partner. once done, you can fully utilize this code lab. you can learn more about the partnership process by visiting samsung pay page, here in samsung developers. notein accordance with the applicable samsung partner agreements, this code lab covers setup and use of the samsung pay sdk for purposes of integrating the samsung pay app with partner apps. the use cases and corresponding code samples included are representative examples only and should not be construed as either recommended or required. overview the samsung pay sdk is an application framework for integrating selected samsung pay features with android-based partner apps on samsung devices. in-app payment, which allows customers to pay for products and services with samsung pay, is one of the operations supported alongside push provisioning and open favorite cards. partner apps can leverage the samsung pay sdk to perform different operations ― push provisioning and open favorite cards for issuers; in-app payment for merchants. key components include: partner app: app developed by merchant or issuer for making online or offline payments and provisioning payment cards through samsung pay samsung pay sdk: sdk integrated into the partner app for direct communication with samsung pay samsung pay app: pay app with which the samsung pay sdk communicates financial network: comprises the payment gateways, acquirers, card associations, and issuers that participate in transaction processing under agreement with the merchant most common use case for in-app payment: the merchant app allows the user to make payments with samsung pay. upon user selection of the samsung pay option, the merchant app calls the apis included in the samsung pay sdk to initiate a transaction with the samsung pay app. the samsung pay app responds with the tokenized payment information necessary to complete the transaction. the merchant app forwards this payment information to the designated payment gateway (pg), either directly through the merchant's web server or indirectly via the samsung-pg interface server for standard transaction processing. for more detailed information, see the official samsung pay sdk programming guide. set up your environment you will need the following: samsung wallet or samsung pay app (depending on the country) a compatible mobile device with android marshmallow 6.0 or android api level 23 (or later android os versions) samsung pay sdk 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! in-app payment sample code (162.23 kb) integrate the samsung pay sdk with your app the following steps comprise the general process for integrating the samsung pay sdk with your app: sign up for the samsung pay developers portal by clicking sign up and register your samsung account (or create it if you don't already have one), then sign in. follow the on-screen instructions for adding your app and creating a new service to generate the service id you'll need to use in your project, along with a debug-api-key (see understanding the debug api key and api level) download the samsung pay sdk by going to resources > sdk download. add the samsung pay sdk jar file (samsungpay.jar) to your android project using android studio or file explorer. develop your partner app with the required api calls and callbacks for samsung pay integration. upload a release version of your app to the samsung pay developers portal for approval. upon samsung approval, publish your partner app to the google play store and samsung galaxy apps. notethe service id is already provided in the sample code for this code lab. however, this service id is for test purposes only and cannot be used for an actual application or service. using the provided test service id enforces your app to use the fixed properties below: service id: 0915499788d6493aa3a038 package name: com.test.beta.pay app version: 1.0/ 1 (or higher) 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 (sampleonlinepay) from the directory and click ok. add the samsungpaysdk_2.18.00_release.jar file from the sdk's libs folder to your android project's libs folder. go to gradle scripts > build.gradle (module: sampleonlinepay.app) and enter the following to the dependencies block: implementation files('libs/samsungpaysdk_2.18.00_release.jar') if the target sdk version is 30 (android 11 or the r-os), you must include the following <queries> element in androidmanifest.xml. <queries> <package android:name="com.samsung.android.spay" /> </queries> configure the api level and enable release mode as of sdk version 1.4, enhanced version control management has been introduced to improve backward compatibility and handle api dependency from country and service type. for example, if a partner integrates the latest sdk—for instance, api level 2.18—but continues to use apis based on level 1.4, the partner app remains compatible with samsung pay apps supporting api level 1.4 without upgrading the samsung pay app. implement the following in application tag of androidmanifest.xml: <meta-data android:name="spay_sdk_api_level" android:value="2.17" /> // most recent sdk version is recommended to leverage the latest apis apps configured for debug or release mode can be registered on the samsung pay developers site to integrate samsung pay functionalities. debug mode – for testing and qa; requires spay_debug_api_key and allowed samsung account(s) in build to test. release mode – for market release to end users; does not need a debug key or an allowed list of samsung accounts in a samsung-approved build to run. for this code lab, enable release mode. <meta-data android:name="debug_mode" android:value="n" /> <!--set to y if debug mode--> <!-- uncomment if debug mode--> <!-- <meta-data android:name="spay_debug_api_key" android:value="" /> --> tipif you want to learn more about these two modes, see configuring debug mode. add an xml layout and modify the activity next, replace the xml layout in res > layout > activity_main.xml. this layout shows the sample item information such as image, name, and price. <?xml version="1.0" encoding="utf-8"?> <layout xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:android="http://schemas.android.com/apk/res/android"> <androidx.constraintlayout.widget.constraintlayout android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".mainactivity"> <imageview android:id="@+id/imageview" android:layout_width="350dp" android:layout_height="184dp" android:layout_margintop="100dp" app:layout_constraintend_toendof="parent" app:layout_constraintstart_tostartof="parent" app:layout_constrainttop_totopof="parent" android:src="@drawable/galaxy_z_flip4_image"/> <imageview android:id="@+id/samsung_pay_button" android:layout_width="wrap_content" android:layout_height="75dp" app:layout_constraintbottom_tobottomof="parent" app:layout_constraintend_toendof="parent" app:layout_constraintstart_tostartof="parent" android:src="@drawable/pay_rectangular_full_screen_black" android:visibility="invisible"/> <textview android:id="@+id/textview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margintop="10dp" android:text="galaxy z flip4" android:textsize="16sp" android:textstyle="bold" app:layout_constraintend_toendof="parent" app:layout_constraintstart_tostartof="parent" app:layout_constrainttop_tobottomof="@+id/imageview" /> <textview android:id="@+id/textview2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margintop="5dp" android:text="$990.99" android:textsize="14sp" app:layout_constraintend_toendof="parent" app:layout_constrainthorizontal_bias="0.517" app:layout_constraintstart_tostartof="parent" app:layout_constrainttop_tobottomof="@+id/textview" /> </androidx.constraintlayout.widget.constraintlayout> </layout> since you added a data binding layout, you need to inflate the xml file differently. go to java > com > test > beta > pay > mainactivity.kt, and declare the databinding variable in the mainactivity class. private lateinit var databinding: activitymainbinding replace the standard setcontentview declaration with the data binding version inside the oncreate method. databinding = databindingutil.setcontentview(this, r.layout.activity_main) check samsung pay status in the mainactivity, create the samsungpay instance. to determine if the device supports samsung pay and if the samsung pay button can be displayed as the user's payment option, check the samsung pay status. samsungpay() requires a valid partnerinfo from the merchant app, which consists of service id and service type. during onboarding, the samsung pay developers portal assigns the service id and service type. in the mainactivity, declare the partnerinfo variable. private lateinit var partnerinfo: partnerinfo then, set the partnerinfo in the oncreate method. val bundle = bundle() bundle.putstring(spaysdk.partner_service_type, spaysdk.servicetype.inapp_payment.tostring()) partnerinfo = partnerinfo(service_id, bundle) after setting partnerinfo, call the getsamsungpaystatus method via updatesamsungpaybutton function inside the oncreate method. updatesamsungpaybutton() the getsamsungpaystatus method of the samsungpay class must be called before using any other feature in the samsung pay sdk. write the updatesamsungpaybutton function as follows: private fun updatesamsungpaybutton() { val samsungpay = samsungpay(this, partnerinfo) samsungpay.getsamsungpaystatus(object : statuslistener { override fun onsuccess(status: int, bundle: bundle) { when (status) { spaysdk.spay_ready -> { databinding.samsungpaybutton.visibility = view.visible // perform your operation. } spaysdk.spay_not_ready -> { // samsung pay is supported but not fully ready. // if extra_error_reason is error_spay_app_need_to_update, // call gotoupdatepage(). // if extra_error_reason is error_spay_setup_not_completed, // call activatesamsungpay(). databinding.samsungpaybutton.visibility = view.invisible } spaysdk.spay_not_allowed_temporally -> { // if extra_error_reason is error_spay_connected_with_external_display, // guide user to disconnect it. databinding.samsungpaybutton.visibility = view.invisible } spaysdk.spay_not_supported -> { databinding.samsungpaybutton.visibility = view.invisible } else -> databinding.samsungpaybutton.visibility = view.invisible } } override fun onfail(errorcode: int, bundle: bundle) { databinding.samsungpaybutton.visibility = view.invisible toast.maketext(applicationcontext, "getsamsungpaystatus fail", toast.length_short).show() } }) } tipfor the list and detailed definition of status codes such as spay_ready, refer to checking samsung pay status. noteas of sdk version 1.5, if the device has android lollipop 5.1 (android api level 22) or earlier versions, the getsamsungpaystatus() api method returns a spay_not supported status code. merchant apps using sdk 1.4 or earlier must check their app's android version. activate the samsung pay app the samsungpay class provides an api method called activatesamsungpay() to activate the samsung pay app on the same device where the partner app is running. if the getsamsungpaystatus() returns spay_not_ready and the extra_error_reason is error_spay_setup_not_complete, the partner app needs to display an appropriate message to the user. then, call activatesamsungpay() to launch samsung pay app and request the user to sign in. in updatesamsungpaybutton function, add the code to call activatesamsungpay method via doactivatesamsungpay function when the status is spay_not_ready: // if extra_error_reason is error_spay_setup_not_completed, // call activatesamsungpay(). val extraerror = bundle.getint(samsungpay.extra_error_reason) if (extraerror == samsungpay.error_spay_setup_not_completed) { doactivatesamsungpay(spaysdk.servicetype.inapp_payment.tostring()) } create the doactivatesamsungpay function as below: private fun doactivatesamsungpay(servicetype: string) { val bundle = bundle() bundle.putstring(samsungpay.partner_service_type, servicetype) val partnerinfo = partnerinfo(service_id, bundle) val samsungpay = samsungpay(this, partnerinfo) samsungpay.activatesamsungpay() } create a transaction request upon successfully initializing the samsungpay class, the merchant app should create a transaction request with payment information. samsung pay offers two types of online payment sheet―normal and custom. the normal payment sheet has fixed display items ― items, tax, and shipping. the custom payment sheet offers more dynamic controls for customizing the ui, together with additional customer order and payment data. for this code lab, use the custom payment sheet and populate the fields in customsheetpaymentinfo to initiate a payment transaction. /* * make user's transaction details. * the merchant app should send paymentinfo to samsung pay via the applicable samsung pay sdk api method for the operation * being invoked. * upon successful user authentication, samsung pay returns the "payment info" structure and the result string. * the result string is forwarded to the pg for transaction completion and will vary based on the requirements of the pg used. * the code example below illustrates how to populate payment information in each field of the paymentinfo class. */ private fun maketransactiondetailswithsheet(): customsheetpaymentinfo? { val brandlist = brandlist val extrapaymentinfo = bundle() val customsheet = customsheet() customsheet.addcontrol(makeamountcontrol()) return customsheetpaymentinfo.builder() .setmerchantid("123456") .setmerchantname("sample merchant") .setordernumber("amz007mar") // if you want to enter address, please refer to the javadoc : // reference/com/samsung/android/sdk/samsungpay/v2/payment/sheet/addresscontrol.html .setaddressinpaymentsheet(customsheetpaymentinfo.addressinpaymentsheet.do_not_show) .setallowedcardbrands(brandlist) .setcardholdernameenabled(true) .setrecurringenabled(false) .setcustomsheet(customsheet) .setextrapaymentinfo(extrapaymentinfo) .build() } private fun makeamountcontrol(): amountboxcontrol { val amountboxcontrol = amountboxcontrol(amount_control_id, "usd") amountboxcontrol.additem(product_item_id, "item", 990.99, "") amountboxcontrol.additem(product_tax_id, "tax", 5.0, "") amountboxcontrol.additem(product_shipping_id, "shipping", 1.0, "") amountboxcontrol.setamounttotal(996.99, amountconstants.format_total_price_only) return amountboxcontrol } private val brandlist: arraylist<spaysdk.brand> get() { val brandlist = arraylist<spaysdk.brand>() brandlist.add(spaysdk.brand.visa) brandlist.add(spaysdk.brand.mastercard) brandlist.add(spaysdk.brand.americanexpress) brandlist.add(spaysdk.brand.discover) return brandlist } request payment with a custom payment sheet the startinapppaywithcustomsheet() method of the paymentmanager class is applied to request payment using a custom payment sheet in samsung pay. when you call the startinapppaywithcustomsheet() method, a custom payment sheet is displayed on the merchant app screen. from there, the user can select a registered card for payment and change the billing and shipping addresses as necessary. the payment sheet lasts for 5 minutes after calling the api. if the time limit expires, the transaction fails. in the mainactivity class, declare the paymentmanager variable. private lateinit var paymentmanager: paymentmanager then, in oncreate(), set an onclicklistener method before calling the updatesamsungpaybutton function to trigger the startinapppaywithcustomsheet function when the samsungpaybutton is clicked. databinding.samsungpaybutton.setonclicklistener { startinapppaywithcustomsheet() } lastly, create a function to call startinapppaywithcustomsheet() method of the paymentmanager class. /* * paymentmanager.startinapppaywithcustomsheet is a method to request online(in-app) payment with samsung pay. * partner app can use this method to make in-app purchase using samsung pay from their * application with custom payment sheet. */ private fun startinapppaywithcustomsheet() { paymentmanager = paymentmanager(applicationcontext, partnerinfo) paymentmanager.startinapppaywithcustomsheet( maketransactiondetailswithsheet(), transactioninfolistener ) } /* * customsheettransactioninfolistener is for listening callback events of online (in-app) custom sheet payment. * this is invoked when card is changed by the user on the custom payment sheet, * and also with the success or failure of online (in-app) payment. */ private val transactioninfolistener: paymentmanager.customsheettransactioninfolistener = object : paymentmanager.customsheettransactioninfolistener { // this callback is received when the user changes card on the custom payment sheet in samsung pay. override fun oncardinfoupdated(selectedcardinfo: cardinfo, customsheet: customsheet) { /* * called when the user changes card in samsung pay. * newly selected cardinfo is passed and partner app can update transaction amount based on new card (if needed). * call updatesheet() method. this is mandatory. */ paymentmanager.updatesheet(customsheet) } override fun onsuccess( response: customsheetpaymentinfo, paymentcredential: string, extrapaymentdata: bundle ) { /* * you will receive the payloads shown below in paymentcredential parameter * the output paymentcredential structure varies depending on the pg you're using and the integration model (direct, indirect) with samsung. */ toast.maketext(applicationcontext, "onsuccess() ", toast.length_short).show() } // this callback is received when the online payment transaction has failed. override fun onfailure(errorcode: int, errordata: bundle?) { toast.maketext(applicationcontext, "onfailure() ", toast.length_short).show() } } run the app after building the apk, you can run the sample merchant app and see how it connects to samsung pay upon clicking the button at the bottom of the screen. to thoroughly test the sample app, you must add at least one card to the samsung pay app. you're done! congratulations! you have successfully achieved the goal of this code lab. now, you can integrate in-app payment with your app by yourself! if you're having trouble, you may download this file: in-app payment complete code (525.20 kb) to learn more about developing apps for samsung pay devices, visit: developer.samsung.com/pay

      https://developer.samsung.com/codelab/pay/in-app-payment.html
      1. Learn
      2. Code Lab

      codelab

      Implement App Continuity and Optimize Large Screen UI of a Gallery App

      implement app continuity and optimize large screen ui of a gallery app objective learn how to apply app continuity and large screen optimization on a gallery app for seamless experience on foldable devices. overview samsung foldable devices have two different physical screens: the cover display and the larger main display. app continuity lets you experience a seamless transition between these displays. when using an app that supports app continuity, you can unfold the device and continue where you left off. with this feature, apps can run without interruption when it receives a configuration change event, such as when a device is folded or unfolded. it is essential to continue the operation by keeping the same state and location of the app after the transition. large screen optimization plays another significant role in terms of ux designing for foldable devices. the screens of foldable devices have a wide range of aspect ratios, careful ux design is needed to suit two different size displays. set up your environment you will need the following: java se development kit (jdk) 8 or later android studio (latest version recommended) samsung galaxy fold, z fold2, z fold3, or newer remote test lab (if physical device is not available) requirements: samsung account java runtime environment (jre) 7 or later with java web start internet environment where port 2600 is available sample code here is a sample code for you to start coding in this code lab. download it and start your learning experience! app continuity sample code (2.80 mb) start your project after downloading the sample code containing the project file for this code lab, open your android studio and click open an existing project. locate the downloaded android project from the directory and click ok. handle the configuration change to have a seamless experience when using a gallery app, the photo that is displayed after folding or unfolding the device should be the same as the previous. you need to store the position or id of the photo, as android destroys and recreate the activity when folding and unfolding the phone. use bundle with its key/value pair to store and restore the values. in addition, you need to consider the screen rotation in order to keep the app running, as android restarts the activity of the app after the configuration changes. let's first start to prevent the activity from restarting, by handling the configuration change for mainactivity in androidmanifest.xml file. android:configchanges="keyboardhidden|orientation|screensize" save the instance state by storing the data before the activity is destroyed when the screen changes from main to cover display or vice versa, android provides us an override method called onsaveinstancestate. it accepts a bundle as a parameter. use putint method to store data into key/value pair. override fun onsaveinstancestate(outstate: bundle) { outstate.putint("currentposition", currentimageposition) log.i("tag", "onsave "+currentimageposition) super.onsaveinstancestate(outstate) } retrieve the stored values when the app is first developed, the savedinstancestate will be null inside the oncreate method. if it is not null, you can retrieve the stored values from the bundle using getint and the key name you set up in the previous step while storing. if(savedinstancestate != null) { selectedimageview!!.setimageresource(images[savedinstancestate.getint("currentposition")]) customgalleryadapter!!.updateposition(images[savedinstancestate.getint("currentposition")]) currentimageposition = savedinstancestate.getint("currentposition") log.i("tag", "onsaved " + savedinstancestate.getint("currentposition")) } create a layout file for the main display the next thing to do, is to optimize the app's large screen ui. here, you will add a navigator for the photos when using the app in the main display, since it has more space. android offers an alternate resources option based on various criteria like display size, density, and other more. you can use two different layout files for each display using alternate resources of android. create a new directory in res in the form of [resource]-[qualifier] for cover display and main display. the appropriate version of the resource is shown automatically by the system based on the smallest width qualifier of sw. the cover display will be between sw240 and sw480, while the main display will be sw600. create a new directory named layout-sw600dp under the res directory and then create an xml file named activity_main. res/ layout/ activity_main.xml layout-sw600dp/ activity_main.xml add the layout code add the gallery layout code shown below, in layout-sw600dp/activity_main.xml file. <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.constraintlayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/linearlayout" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.xyz.gallery.mainactivity"> <imageview android:id="@+id/imageview" android:layout_width="wrap_content" android:layout_height="match_parent" android:gravity="center_vertical" app:layout_constraintend_toendof="parent" app:layout_constraintstart_tostartof="parent" app:layout_constrainttop_totopof="parent" /> <gallery android:id="@+id/allgallery" android:layout_width="fill_parent" android:layout_height="108dp" android:layout_marginbottom="4dp" android:gravity="fill" android:orientation="horizontal" android:padding="10dp" android:spacing="5dp" app:layout_constraintbottom_tobottomof="parent" app:layout_constraintend_toendof="parent" app:layout_constrainthorizontal_bias="0.0" app:layout_constraintstart_tostartof="parent" /> </androidx.constraintlayout.widget.constraintlayout> run the app after building the apk, you can run the gallery app and see how it change when you fold and unfold the device. if you don’t have any physical device, you can also test it on a remote test lab device. tipwatch this tutorial video and know how to easily test your app via remote test lab. noteapp continuity when folding the device, can be turned on for selected apps in settings (if the app supports app continuity). to continue using the gallery app on the cover display when you close your phone, go to settings> display > continue apps on cover screen > toggle on gallery app. foldable devices let you decide whether you want to see less or more content at the same time in the main display. to see the photo navigator added in the app, go to settings> display > screen layout and zoom > see more content at the same time. you're done! congratulations! you have successfully achieved the goal of this code lab. now, you can optimize your app to support continuity and large screen layout by yourself! if you're having trouble, you may download this file: app continuity complete code (24.44 mb) to learn more about developing apps for galaxy foldable devices, visit: www.developer.samsung.com/galaxy-z

      https://developer.samsung.com/codelab/galaxy-z/app-continuity.html
      1. Learn
      2. Code Lab

      codelab

      Use AR Emoji on Games and 3D Apps

      use ar emoji on games and 3d apps objective learn how to use ar emoji as character of games or 3d applications using galaxy ar emoji sdk for unity. partnership request to use the galaxy ar emoji sdk for unity, you must become an official samsung partner. once done, you can fully utilize this code lab. you can learn more about the partnership process by visiting galaxy ar emoji sdk page, here in samsung developers. overview galaxy ar emoji sdk for unity with your samsung galaxy device, you can use the ar emoji feature to create an animated 3d avatar from your selfie photo or from a selection of a few suggested characters. the avatar can display a range of emotions and body movements. the galaxy ar emoji sdk for unity enables you to use this said ar emoji avatar in your application, such as using it to represent a game character. tutorial process in this code lab, you will get to know about unity packages that can help you to use ar emoji avatars as character models in your unity application like games with simple code updates. you will first learn about the basic pipeline for creation of app with ar emoji character with ar emoji sdk by loading a character model and rendering on the mobile app. afterwards, you will learn a way of applying custom animation to the ar emoji character. you can make your own app with a simple sequence of operation and by following the steps in this code lab. moreover, you can learn about the character file import process and get to know more how you can maximize galaxy ar emoji sdk. set up your environment you will need the following: unity for windows (lts release 2020.3.xf1 or latest compatible version) editor for editing unity script (like visual studio) select different values to test how your game will look on monitors with different aspect ratios. this is set to free aspect by default. (recommended: 1024x2048) samsung galaxy device supporting ar emoji create your own ar emoji first, create your own ar emoji with the following steps: run camera application. click more > ar zone > ar emoji camera and the + button. take your selfie and choose your gender. edit your ar emoji. a. customize the looks, clothes, or accessories of your ar emoji. b. press next, once done. check your avatar in both mask mode and in ar emoji studio. create a unity project and configure the settings run unity and create an empty 3d sample project. go to build settings. a. file > build settings b. platform > android c. click switch platform specific package name and keystore are necessary for testing. in the next steps, it is explained in detail. go to edit > player settings > player > other settings > identification > override default package name and enable it. set the package name to samsung.com.fileprovidersample. go to edit > project setting > player > publishing settings. a. enable custom keystore. b. add keystore file (fileprovidersample.jks) with browser (included in docs folder of gettingaremojiv3.3.unitypackage). c. enter the keystore password: 123456 d. set the project key setting: alias: keyalias password: 123456 import packages run gettingaremojiv3.3.unitypackage, then click import. check the imported sample app. a. go to assets > scenes > gettingaremojisample scene. b. click canvas. import the next package, gltfimporterv3.3.unitypackage. integrate the gltf importer to the sample app go to the sample scene. a. click assets > scenes > gettingemojisample.unity. b. click canvas. copy gltfcomponent prefab into your app to use gltf component property. a. click assets > prefabs. b. drag gltfcomponent prefab to your scene. build and run go to file > build settings > build and run. launch the sample app in your device. a. click getavatarlist button and check the ar emoji list stored on the device. b. select one of them. c. click getavatarthumbnailuri button. d. confirm if the ar emoji thumbnail is showing. e. click getavatarzipuri button. f. check if it shows the ar emoji avatar. learn the basics of animation in unity animation system overview unity has a rich and sophisticated animation system (sometimes referred to as mecanim). while mecanim is recommended for use in most situations, unity has retained its legacy animation system, which existed before unity 4. when working with an older content created before unity 4, you may need to use the legacy animation system. animator controller to apply the animation to the model, you must have a basic knowledge of the animation controller. developers can easily control the animation with it. an animator controller allows you to arrange and maintain a set of animation clips and associated animation transitions for a character or object. in most cases it is normal to have multiple animations and switch between them when certain game conditions occur. for example, you could switch from a walk animation clip to a jump animation clip whenever the space bar is pressed. however, even if you only have a single animation clip, you still need to place it into an animator controller to use it on a gameobject. the animator controller has references to the animation clips used within it, and manages the various animation clips and the transitions between them using a state machine, which could be thought of as a flow-chart of animation clips and transitions, or a simple program written in a visual programming language within unity. here, the model is a loaded runtime, and then an animation controller component is added to the model. therefore, you will learn how to make an animation clip and apply a simple animation through a state machine. animation state machine unity’s animation state machines provide a way to see the overview all of the animation clips related to a particular character and allow various events in the game, such as user inputs, to trigger different animations. state machine transitions exist to help you simplify complex state machines. this allows you to have a higher level of abstraction over the state machine logic. each view in the animator window has an entry and exit node. the animator window specifies the state machine transitions. the entry node is used when transitioning into a state machine. it will be evaluated and will branch to the destination state according to the conditions set. in this way, the entry node can control which state the state machine begins in, by evaluating the state of your parameters when the state machine begins. because the state machine always has a default state, there will always be a default transition branching from the entry node to the default state. humanoid animations unity’s animation system also has numerous special features for handling humanoid characters which give you the ability to retarget humanoid animation from any source to your own character model, as well as adjusting muscle definitions. these special features are enabled by unity’s avatar system, where humanoid characters are mapped to a common internal format. one of the most powerful features of mecanim is retargeting of humanoid animations. this means that with relative ease, you can apply the same set of animations to various character models. retargeting is only possible for humanoid models, where an avatar has been configured because this gives a correspondence between the models’ bone structure. generate animation clips animation clips are one of the core elements to unity’s animation system. unity supports importing animation from external sources, and offers the ability to create animation clips from scratch within the editor using the animation window. animation data collection this code lab provides a tool that works with the model. before then, you need animation data. it can be made directly with a professional tool like maya and 3ds max or it can be obtained for free from mixamo. make the character walk get the animation data here from mixamo. a. select the walking animation data. b. click the download button. c. the download settings appears and the animation data can be obtained by setting the following: transfer the file to unity. this allows you to set the following settings in the inspector window. after changing the animation type to humanoid, click the apply button. it is automatically retargeted to the unity avatar system. the animation controller is basically set in the model. a. in resources > animations > avatar > controller, double click the player.controller, then you can see the animator window. b. the animation set by default is gangnam style. it’s recommended to change this to ik idle. c. next, apply the animation by dragging the walking animation to the button. make the transition from idle to walk. a. right-click the idle node. b. connect lines from idle node to the walk node. select the connecting line for transition (idle → walk). a. uncheck has exit time. b. set the parameter to bool. animation parameters are variables that are defined within an animator controller that can be accessed and assigned values from scripts. this is how a script can control or affect the flow of the state machine. c. add the condition of transition (idle → walk). select the connecting line for transition (walk → idle). repeat in the same way with previous steps. however, the condition of walk should be set to false. look for the button behaviour (script). in buttonbehaviour.cs, write a script that modifies parameters based on user input. add the following at the bottom of the existing code: public animator anim; public float speed = 1.0f; // update is called once per frame void update(){ if (input.getkey(keycode.space)){ if (anim == null){ if (gameobject.findgameobjectwithtag("gltfcomponent")){ debug.log("find gltfcomponent"); gameobject o = gameobject.findgameobjectwithtag("gltfcomponent"); gltfcomponent = o.getcomponent<unitygltf.gltfcomponent>(); } anim = gltfcomponent.getcomponent<animator>(); } } if (input.getkey(keycode.rightarrow)){ gltfcomponent.transform.rotation = quaternion.euler(0, 90, 0); gltfcomponent.transform.position += gltfcomponent.transform.forward * time.deltatime * speed; anim.setbool("walk", true); } else if (input.getkey(keycode.leftarrow)){ gltfcomponent.transform.rotation = quaternion.euler(0, -90, 0); gltfcomponent.transform.position += gltfcomponent.transform.forward * time.deltatime * speed; anim.setbool("walk", true); } else if (input.getkey(keycode.downarrow)){ gltfcomponent.transform.rotation = quaternion.euler(0, 180, 0); gltfcomponent.transform.position += gltfcomponent.transform.forward * time.deltatime * speed; anim.setbool("walk", true); } else if (input.getkey(keycode.uparrow)){ gltfcomponent.transform.rotation = quaternion.euler(0, 0, 0); gltfcomponent.transform.position += gltfcomponent.transform.forward * time.deltatime * speed; anim.setbool("walk", true); } else{ anim.setbool("walk", false); } } play and review the walking animation in the unity studio. a. press the spacebar on your keyboard and now you can operate the animation you set. b. try pressing the arrow keys of the keyboard, to make your ar emoji character move using the walking animation. you're done! congratulations! you have successfully achieved the goal of this code lab. now, you can create an ar emoji avatar and use it as a character in games or apps, all by yourself! learn more by going to galaxy ar emoji.

      https://developer.samsung.com/codelab/ar-emoji/game-character.html
      1. Learn
      2. Code Lab

      codelab

      Integrate IoT Devices into the SmartThings Ecosystem

      integrate iot devices into the smartthings ecosystem objective learn how to create your own iot device using smartthings sdk for direct connected devices. overview the smartthings sdk for direct connected devices is provided to ease the development of devices which operate with smartthings cloud and mobile application. it is small enough to work on resource limited embedded devices. in this code lab, you will learn how to create your own iot device profile at smartthings cloud and how to implement on your test device. it is explained into three parts. the first explains how you can register and deploy to test your own iot device profile in smartthings using the developer workspace. then, it demonstrates how to create your own iot device application with smartthings sdk. the last part shows how to onboard and control instances of your device with smartthings mobile application. noteyou will name the device as code lab example for this tutorial. set up your environment you will need the following: host pc this code lab is based on ubuntu linux (x64) toolchain and board support package (bsp) for micro-controller unit (mcu) board you will use an esp32-devkitc board. you may set up the environment by referring to this github repository. github repositories for the library and references or samples of smartthings sdk for direct connected devices for c $ git clone https://github.com/smartthingscommunity/st-device-sdk-c-ref.git $ cd st-cevice-sdk-c-ref $ python3 setup.py esp32 smartthings mobile application sample code here is a sample code for you to start coding in this code lab. download it and start your learning experience! smartthings sdk sample code (2.60 kb) alternatively, you may simply get it by git cloning or downloading a zip file from this github repository. register and deploy to test your device using the developer workspace, create a device profile and customize the instructions for onboarding the device on the smartthings mobile app, and deploy devices to be tested. these configurations can be edited up until the point you submit the device for publication in the production of the smartthings ecosystem. sign in to smartthings developers sign in to smartthings developer workspace using your samsung account. create new project you need to create an integration project for a direct connected device. create a new device project for device integration. select device integration, then direct-connected. afterwards, name your project respectively. add a device profile define your device’s functionalities with smartthings capability. first, navigate and select define device profile and then click create device profile. fill the required fields with respective values. afterwards, select a capability for your device. you can get more information about the capabilities available here. notethe health check capability is automatically added for all direct connected devices. it should not be removed. the required capabilities are: switch and health check add device onboarding the device onboarding guides device owners when their device is first registering and connecting to smartthings. you can customize the screens presented by adding a device onboarding profile. the ownership validation type is also defined at this stage. you may customize the screens displayed when the device onboards via the smartthings mobile app, or just use the default values. noteuse just works or button confirm for this example. add a product info the product info defines how this device is shown at smartthings mobile app catalog. you can define device’s category and its regional availability. deploy your device to test you can start testing by deploying your device to test. there are two ways to do this: via overview menu via test > test devices you will be able to see your device in the smartthings mobile app when in developer mode only after it has been deployed for testing. register test devices you can add the identity of device for authenticating it to the smartthings cloud. this requires device information like serial number and device public key (ed25519). since the maximum number of test device is limited per user, once you’ve reached it, you should remove the existing one. this example shows how to create ed25519 key pair with sdk tools. you can get device_info.json file as a result from tools/keygen/linux/output_{ serialnumber}. linux version of key generator (keygen) utility is located at st-iot-device-sdk-c-reference/iot-core/tools/keygen/ or st-device-sdk-c/tools/keygen/. serial number for testing device would be randomly generated by this tool which has stdk + 12-digit alphanumeric format: $ cd ~/workspace/st-device-sdk-c-ref/iot-core/tools/keygen/ $ python3 stdk-keygen.py –firmware switch_example_001 use following serial number and public key for the identity of your device in developer workspace. serial number: stdk**e90w***ucx public key: nfn5x***uqusq****zhobsfaaop9***kndlnjdjrew= copy stdk**e90w***ucx from keygen output and paste it into serial number field of register a test device page. copy public key string from keygen output (nfn5x***uqusq****zhobsfaaop9***kndlnjdjrew= in this example) and paste it into public key field. generate device qr code using the device qr code could be helpful while device onboarding. qr code should have format like below. refer here for more details. urlhttps://qr.samsungiots.com/?m={your mnid}&s={device onboardingid}&r={device serialnumber} {your mnid}: 4-digit alphanumeric mnid of your account {device onboardingid}: 3-digit number onboarding id, you can find it from your developer workspace project device onboarding > other info page {device serialnumber}: device serial number which is registered at your developer workspace project you can simply generate qr code with using below python script: import qrcode mnid = 'ffff' # "ffff" is an example. you should replace it with yours onboardingid = '111' # "111" is an example. you should replace it with yours serialnumber = 'stdktest0001' # "stdktest0001" is an exmaple. you should replace it with yours qrurl = 'https://qr.samsungiots.com/?m=' + mnid + '&s=' + onboardingid + '&r=' + serialnumber img = qrcode.make(qrurl) img.save(serialnumber + '.png') qrcode.qrcode(box_size=10, border=4) write device application open and edit sample device app currently, you are doing the code lab example, which is located at apps/esp32/code_lab_example directory in the github repository. download onboarding_profile.json from the overview of your device in developer workspace. copy onboarding_profile.json file into your application directory, apps/esp32/code_lab_example/main: $ cd ~/workspace/st-device-sdk-c-ref/apps/esp32/code_lab_example/main/ $ cp ~/downloads/onboarding_config.json copy device_info.json from tools/keygen/linux/output_{serialnumber} which contains your device specific information to application directory, apps/esp32/code_lab_example/main: $ cd ~/workspace/st-device-sdk-c-ref/iot-core/tools/keygen/ $ cp output_{serialnumber}/device_info.json ~/workspace/st-device-sdk-c-ref/apps/esp32/code_lab_example/main/ firmwareversion: version string privatekey: base64 encoded ed25519 private key. this value should be paired with what you registered to developer workspace. publickey: base64 encoded ed25519 public key. this value should be same with what you registered to developer workspace. serialnumber: this value should be same with what you registered to developer workspace { "deviceinfo": { "firmwareversion": "switch_example_001", "privatekey": "dh**jkmrd5x****bav+fgoxa3qzfnw3v****jhxomd0=", "publickey": "nfn5x***uqusq****zhobsfaaop9***kndlnjdjrew=", "serialnumber": "stdk**e90w***ucx" } } open sample application source code browse in apps/esp32/code_lab_example/main/ directory. open main.c file. write your device application code this example already has cloud connection functionality using smartthings sdk apis. void app_main(void) { /** easily integrate your direct connected device using the direct connected devices sdk. the sdk manages all mqtt topics and onboarding requirements, freeing you to focus on the capabilities of your device. that is, you can simply develop a basic application by just calling the apis provided by st_iot_core layer like below. // create a iot context 1. st_conn_init(); // create a handle to process capability 2. st_cap_handle_init(); (called in function 'capability_init') // register a callback function to process capability command when it comes from the smartthings server. 3. st_cap_cmd_set_cb(); (called in function 'capability_init') // process on-boarding procedure. there is nothing more to do on the app side than call the api. 4. st_conn_start(); */ unsigned char *onboarding_config = (unsigned char *) onboarding_config_start; unsigned int onboarding_config_len = onboarding_config_end - onboarding_config_start; unsigned char *device_info = (unsigned char *) device_info_start; unsigned int device_info_len = device_info_end - device_info_start; int err; iot_gpio_init(); xtaskcreate(app_main_task, "app_main_task", 4096, null, 10, null); //create a iot context iot_ctx = st_conn_init(onboarding_config, onboarding_config_len, device_info, device_info_len); if (iot_ctx != null) { err = st_conn_set_noti_cb(iot_ctx, iot_noti_cb, null); if (err) printf("fail to set notification callback function\n"); } else { printf("fail to create the iot_context\n"); } //create a handle to process capability and initialize capability info capability_init(); //connect to server err = st_conn_start(iot_ctx, (st_status_cb)&iot_status_cb, iot_status_all, null, null); if (err) { printf("fail to start connection. err:%d\n", err); } } complete your command callback function for each capability. the command callback function should contain your device control upon each command such as led on or off control. capability example for each capability would be helpful to handle attribute command for each capability. you can find it at apps/capability_example/main. static void update_switch_state(int switch_state) { const char* switch_value; if (switch_state == switch_on) { switch_value = caps_helper_switch.attr_switch.value_on; } else { switch_value = caps_helper_switch.attr_switch.value_off; } //todo: set switch attribute value and send // // example //=============================================================================== // cap_switch_data->set_switch_value(cap_switch_data, switch_value); // cap_switch_data->attr_switch_send(cap_switch_data); //=============================================================================== } static int get_switch_state(void) { const char* switch_value; int switch_state = switch_off; //todo: get switch attribute value // // example //=============================================================================== // switch_value = cap_switch_data->get_switch_value(cap_switch_data); // // if (!strcmp(switch_value, caps_helper_switch.attr_switch.value_on)) { // switch_state = switch_on; // } else if (!strcmp(switch_value, caps_helper_switch.attr_switch.value_off)) { // switch_state = switch_off; // } //=============================================================================== return switch_state; } static void cap_switch_cmd_cb(struct caps_switch_data *caps_data) { int switch_state = get_switch_state(); set_led_mode(switch_state); } static void capability_init() { //todo: initialize switch capability with using capability sample's initializae function // // example // //=============================================================================== // cap_switch_data = caps_switch_initialize(iot_ctx, "main", null, null); // if (cap_switch_data) { // const char *switch_init_value = caps_helper_switch.attr_switch.value_on; // // cap_switch_data->cmd_on_usr_cb = cap_switch_cmd_cb; // cap_switch_data->cmd_off_usr_cb = cap_switch_cmd_cb; // // cap_switch_data->set_switch_value(cap_switch_data, switch_init_value); // } //=============================================================================== } build, flash, and monitor you can build, flash, and monitor in the console with the following: $ cd ~/workspace/st-device-sdk-c-ref $ python3 build.py apps/esp32/code_lab_example $ python3 build.py apps/esp32/code_lab_example flash $ python3 build.py apps/esp32/code_lab_example monitor or $ cd ~/workspace/st-device-sdk-c-ref $ python3 build.py apps/esp32/code_lab_example flash monitor onboard and control the device via smartthings app onboarding a. enable developer mode developer mode should be enabled on smartthings mobile application. launch the smartthings app, go to dashboard > settings. long-press about smartthings for 20 seconds. enable the developer mode, then restart the smartthings app. you can find out more information here. b. add a new device go to add device and click my testing devices or scan qr code. you can now see and add your self-published devices. control by smartthings application a. device control from dashboard you can turn your device’s led on or off by clicking the button in the smartthings app. b. device control from plugin you can control various attributes and get more detailed information from the device plugin user interface. you're done! congratulations! you have successfully achieved the goal of this code lab. now, you can control your iot devices using the smartthings app all by yourself! if you're having trouble, you may download this file: smartthings device sdk complete code (2.49 kb)

      https://developer.samsung.com/codelab/smartthings/device-sdk.html
      1. Learn
      2. Code Lab

      codelab

      Measure Blood Oxygen Level on Galaxy Watch

      measure blood oxygen level on galaxy watch objective create a health app for galaxy watches powered by wear os, utilizing the new samsung privileged health sdk to trigger and obtain blood oxygen level (spo2) measurement results. partnership request in this code lab, you will use a specially prepared mock library. it has limited functionality and uses dummy data instead of real-time data. to get real values, you will need the full version of the samsung privileged health sdk library, which is available to registered samsung partners. apply as a partner by checking out the partner app program to get exclusive access to the samsung privileged health sdk. overview samsung privileged health 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 privileged health 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 (110.13 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 (basic) from the directory and click ok. check capabilities for the device to track data with the samsung privileged health 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); } check connection error resolution suppose a connection to the health tracking service attempt ends with an error. in that case, you can try to resolve it using the samsung privileged health sdk api. 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 side 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 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 privileged health sdk functionality * call gethealthtracker() on healthtrackingservice object * use healthtrackertype.spo2 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 completes, the listener has to be disconnected. since, due to battery drain, on-demand measurement should not last more than approximately 30 seconds. the measurement will cancel if the final blood oxygen level value is not delivered in time. it’s also worth noting that the sensor needs a few seconds to warm up and provide correct values, adding to the overall measurement time. the blood oxygen level values come in the ondatareceived callback of trackereventlistener. see below example of the code, in the spo2listener.java file, 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 will find an additional unit tests package. this will let you verify your code changes even without using a physical watch. see instructions below on how to run the unit tests: right click on com.samsung.sdc22.health.basic (test) and execute run 'tests in 'com.samsung.sdc22.health.basic'' 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 your blood oxygen level. right after the app is started, it will request user permission. allow the app to receive data from the body sensors. afterwards, it will show the application's main screen. to get the blood oxygen level value, 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 (109.86 kb) to learn more about samsung health, visit: developer.samsung.com/health

      https://developer.samsung.com/codelab/health/blood-oxygen.html
      1. Learn
      2. Code Lab

      codelab

      Open a New Desktop World on PC or Mac

      open a new desktop world on pc or mac objective optimize your application and its input capabilities on samsung dex. in addition, implement some features using samsung dex dual mode. overview since the launch of galaxy s8 and s8+, samsung galaxy flagship devices have supported the samsung dex feature that extends the functionality of a mobile device into the desktop environment. in this code lab, you will learn how to optimize their android apps for the next-gen samsung devices with enhanced interaction, desktop mode capability, and a better app experience. one of the advantages of samsung dex is that it does not require any sdks to launch apps in samsung dex. however, apps must support mouse functionality and multi-density. for better ux in dex mode, apps must adhere to a number of android best practices, such as multi-window feature support. desktop mode includes all the advanced multitasking features built in to the samsung dex ui. you can learn these through the tips and detailed instructions of this code lab. set up your environment you will need the following: android studio (latest version recommended) android sdk 24 or higher any samsung galaxy device that supports samsung dex for pc usb-c to usb-a cable (if applicable) sample code here is a sample code for you to start coding in this code lab. download it and start your learning experience! dex sample code (535.67 kb) install samsung dex for pc and open the project file samsung dex for pc is the next feature of samsung dex, giving you an uninterrupted experience between your phone and your computer, which is available for both windows os and macos. here, you can share a pc monitor, keyboard, and mouse on dex for pc. run installer for dex for pc to install. after completing the installation, connect your mobile device to your pc using a usb cable. open the downloaded sample code which contains the android project for this code lab. the base project provided has the following features: textviews to show information edittext(r.id.edittxt): to input the name text1(r.id.txt1): to show the sentence with the name entered at edittext text2(r.id.txt2): to show the size of window text3(r.id.txt3): to show the status if dex is enabled or not. by default, it’s not visible. in samsung dex, it can show some text. text4(r.id.txt4): to show how to change the size of the text via keyboard and mouse interaction buttons and switch to run other apps (for example, email) and subactivity enable mouse and keyboard interaction support to run your app in samsung dex, there is a minimum requirement. if apps block fake touch input in dex mode while allowing touch input, you may not use apps with a mouse or touchpad. here, you need to check whether the code for disabling mouse and keyboard interaction support are in the manifest or not. <uses-configuration android:reqtouchscreen="finger" /> <uses-feature android:name="android.hardware.touchscreen" android:required="true" /> notenever declare the touchscreen support to disable the mouse and keyboard interactions. enable resizable multi-window support to run in samsung dex, apps should support android multi-window – this enables minimizing, maximizing, and resizing. if multi-window is not supported, the app opens in a fixed-size window. for your app to have a pc-like experience, this needs to be considered. apps should target sdk 24 or higher. always check the targetsdkversion is set to 24 or a higher at build.gradle file. explicitly declare resizeableactivity to true in the manifest file to run in a resizable window: <activity … android:resizeableactivity="true"> </activity> the app can now run in a freeform or resizable multi-window just as resizeableactivity is declared to true explicitly in manifest. handle runtime configuration changes when resizing the window resizing the window causes runtime configuration changes similar to changing an orientation from portrait to landscape display. this may result in the application being forced to restart whenever resizing the window. the app shows a toast message whenever an app is created. therefore, after resizing, apps always show it and the sentence of text1 would be reset. to ensure that this does not happen, add a configchanges flag to the activity in the manifest. you can get more information from android's guide related to handling configuration changes as well as android's best practices on building a responsive design. first, add android:configchanges flag to activity in manifest. here, all configchanges flags prevent the app from restarting in samsung dex: <application … <activity ... <!-- dex todo the android:configchanges="colormode|orientation|screenlayout|screensize|smallestscreensize|keyboardhidden|keyboard"this used if you don't want android to kill and restart you activity when window is resized --> android:configchanges="colormode|orientation|screenlayout|screensize|smallestscreensize|keyboardhidden|keyboard" > ... </activity> </application> adding flags in manifest needs to be implemented because onconfigurationchanged callback method is called whenever configuration changes happen. sample application already has the method, named updatewindowsize(), to check the size (width and height) of window and update the textview (r.id.txt1) for showing the size of window. here, it calls the updatewindowsize() whenever call onconfiguration callback occurs: @override public void onconfigurationchanged(configuration newconfig) { super.onconfigurationchanged(newconfig); updatewindowsize(); } after this step, the app did not show the toast message after resizing the window and text1 was not set to default. check the status related to samsung dex your app can check whether samsung dex is enabled or not in mobile device. it is one of the most useful features of samsung dex. if your device supports samsung dex, and it is enabled, you can customize your app for dex mode. your app can also check whether it is running in your phone or in dex mode. in this case, you can customize your app to work differently depending on the mode it is using. here, you can make your app show the status if it is enabled or not and can add a text to show which display mode the app is running in. check whether samsung dex is enabled or not to check whether samsung dex is enabled or not, you need to use reflection method. check and implement the following code inside the isdexenabled(). if samsung dex is enabled, it returns the value of true. private boolean isdexenabled() { object desktopmodemanager = mcontext.getapplicationcontext().getsystemservice("desktopmode"); if (desktopmodemanager != null) { try { method getdesktopmodestatemethod = desktopmodemanager.getclass().getdeclaredmethod("getdesktopmodestate"); object desktopmodestate = getdesktopmodestatemethod.invoke(desktopmodemanager); class desktopmodestateclass = desktopmodestate.getclass(); method getenabledmethod = desktopmodestateclass.getdeclaredmethod("getenabled"); int enabled = (int) getenabledmethod.invoke(desktopmodestate); boolean isenabled = enabled == desktopmodestateclass.getdeclaredfield("enabled").getint(desktopmodestateclass); method getdisplaytypemethod = desktopmodestateclass.getdeclaredmethod("getdisplaytype"); int displaytype = (int) getdisplaytypemethod.invoke(desktopmodestate); return isenabled && displaytype == desktopmodestateclass.getdeclaredfield("display_type_dual").getint(desktopmodestateclass); } catch (nosuchfieldexception | nosuchmethodexception | illegalaccessexception | invocationtargetexception e) { // device does not support dex 3.0 return false; } } return false; } check which mode your app is currently running when checking which mode your app is running at, you also need to use reflection method. check and implement the following code inside isappcurrentlyrunningindex(). if your app is running at samsung dex mode, it returns the value of true. private boolean isappcurrentlyrunningindex() { configuration config = mcontext.getresources().getconfiguration(); try { class configclass = config.getclass(); if (configclass.getfield("sem_desktop_mode_enabled").getint(configclass) == configclass.getfield("semdesktopmodeenabled").getint(config)) { toast.maketext(mcontext, "isappcurrentlyrunningindex: true", toast.length_long).show(); return true; } } catch (exception ignored) { } return false; } change the prompt accordingly to enable samsung dex mode using the return value from above methods, change the sentence prompt for textview3. protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); if(isdexenabled()){ if(isappcurrentlyrunningindex()){ text3.settext("samsung dex enabled \nnow, your app is running in samsung dex"); } else { text3.settext("samsung dex enabled \nnow, your app is running in phone"); } } else { text3.settext("samsung dex not enabled"); } } implement keyboard features and combination keys if your app supports customized keyboard & mouse interactions aside from basic keyboard interactions, it can improve the user’s experience. in this step, you can try to add features to control the size for text4 with the combination of ctrl + mouse-wheel. add to check the status ctrl keys that has keyevent.keycode_ctrl_left and keyevent.keycode_ctrl_right as a keycode which would proceed to check its function when pressed and released. @override public boolean onkeydown(int keycode, keyevent event) { switch (keycode) { case keyevent.keycode_ctrl_left: case keyevent.keycode_ctrl_right: ctrlkeypressed = true; break; } return super.onkeydown(keycode, event); } @override public boolean onkeyup(int keycode, keyevent event) { switch (keycode) { case keyevent.keycode_ctrl_left: case keyevent.keycode_ctrl_right: ctrlkeypressed = false; break; } return super.onkeyup(keycode, event); } noteif you want to add more keyboard functionality, use the android guide for handling keyboard actions. enable ctrl + mouse-wheel combination to change the size of text. @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); text4.setongenericmotionlistener(new view.ongenericmotionlistener() { @override public boolean ongenericmotion(view view, motionevent motionevent) { int action = motionevent.getaction(); if((action == motionevent.action_scroll) && ctrlkeypressed) { float vscroll = motionevent.getaxisvalue(motionevent.axis_vscroll); if(vscroll < 0){ //wheel down text4.settextsize(typedvalue.complex_unit_px, text4.gettextsize()-1); } else{ //wheel up text4.settextsize(typedvalue.complex_unit_px, text4.gettextsize()+1); } } return false; } }); } run other apps on phone or dex display in dual mode samsung dex dual mode is a new feature of samsung dex starting with galaxy note9. with dex for pc support, samsung dex dual mode has become more useful. for example, the app makes an activity or another app launches at a specific display. in this step, we implement to execute the email app at a specific display via button. in the sample app, an email app can be launched on a specific monitor. implement to run an email app via button1 (r.id.btn1). @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); startemail = (button) findviewbyid(r.id.btn1); startemail.settext("start e-mail app"); startemail.setonclicklistener(this); } @override public void onclick(view view) { switch (view.getid()){ case r.id.btn1 : intent intent = getpackagemanager().getlaunchintentforpackage("com.google.android.gm"); intent.addflags(intent.flag_activity_new_task); startactivity(intent); break; } } make it decide which display the app will run using a switch. the code snippet below can provide the information for target display. // samsung dex display displaymanager dm = (displaymanager)getsystemservice(context.display_service); display[] displays = dm.getdisplays("com.samsung.android.hardware.display.category.desktop"); display targetdisplay = displays[0]; // phone display displaymanager dm = (displaymanager)getsystemservice(context.display_service); display targetdisplay = dm.getdisplay(display.default_display); the app needs to execute startactivity with the display information to get through activityoptions setlaunchdisplayid api. finally, we need to change the code to run the email app. @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); startemail = (button) findviewbyid(r.id.btn1); startemail.settext("start e-mail app"); startemail.setonclicklistener(this); sw = (switch)findviewbyid(r.id.switch1); sw.settext("dex display"); } @override public void onclick(view view) { display targetdisplay; displaymanager dm = (displaymanager)getsystemservice(context.display_service); if(sw.ischecked()) { display[] displays = dm.getdisplays("com.samsung.android.hardware.display.category.desktop"); targetdisplay = displays[0]; }else { targetdisplay = dm.getdisplay(display.default_display); } switch (view.getid()){ case r.id.btn1 : intent intent = getpackagemanager().getlaunchintentforpackage("com.google.android.gm"); if(isdexenabled()){ activityoptions options = activityoptions.makebasic(); options.setlaunchdisplayid(targetdisplay.getdisplayid()); startactivity(intent, options.tobundle()); } else { startactivity(intent); } break; } } utilize both phone and dex display on dual mode in samsung dex dual mode, your app can run different activities on both the phone display and dex display. in this case, you should consider a few things. first, you need to set target display like in previous step. here, you used the targetdisplay defined previously. second, to start an additional activity on multi-window, we need to add intent.flag_activity_new_task flag: intent intent2 = new intent(mainactivity.this,subactivity.class); intent2.setflags(intent.flag_activity_new_task); lastly, the meta-data should be added at manifest. <application> … <meta-data android:name="com.samsung.android.multidisplay.keep_process_alive" android:value="true" /> … </application> samsung dex (framework) does not allow a process to have tasks on multiple displays and contexts such as activities and services if they have the same displayid. for this reason, only one instance of the app can run and the older instance of the app will be closed if a new instance is launched. however, some apps, including activity or service, needs multiple instances in certain situations. this meta-data keeps an application alive and capable of running multiple instances. an app developer has a responsibility to use proper context to make proper uis, since the framework is not concerned about the process, application context, and package context. in the sample app, subactivity can run on a specific monitor. next, implement to start subactivity on the targetdisplay via button2(r.id.btn2): protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); startsubactivity = (button) findviewbyid(r.id.btn2); startsubactivity.settext("start \nsubactivity"); startsubactivity.setonclicklistener(this); } case r.id.btn2 : intent intent2 = new intent(mainactivity.this,subactivity.class); intent2.setflags(intent.flag_activity_new_task); if(isdexenabled()){ activityoptions options = activityoptions.makebasic(); options.setlaunchdisplayid(targetdisplay.getdisplayid()); startactivity(intent2, options.tobundle()); } else { startactivity(intent2); } break; test dual mode to open the email app and subactivity in either dex mode or in your phone, you may toggle the on dex display button in the app. when on dex display button is turned off, the email app and activity will be launched in the phone. otherwise, it will be opened in dex mode as seen below. you're done! congratulations! you have successfully achieved the goal of this code lab. now, you can optimize your app to be compatible with dex environment by yourself! keep in mind that you can modify your app to have a desktop-like experience without any restrictions or any sdk for samsung dex. if you're having trouble, you may download this file: dex complete code (8.60 mb)

      https://developer.samsung.com/codelab/dex/new-desktop-world.html
      No Search Results
      No Search results. Try using another keyword.
      • <<
      • <
      • 1
      • 2
      • 3
      • >
      • >>
      Samsung Developers
      Samsung Developers
      Quick Link
      • Android USB Driver
      • Code Lab
      • Galaxy Emulator Skin
      • Foldables and Large Screens
      • One UI Beta
      • Remote Test Lab
      • Samsung Developers Podcast
      Family Site
      • Bixby
      • Knox
      • Samsung Pay
      • SmartThings
      • Tizen
      • Samsung Research
      • Samsung Open Source
      • Samsung Dev Spain
      • Samsung Dev Brazil
      Legal
      • Terms
      • Privacy
      • Open Source License
      • Cookie Policy
      Social Communications
      • Facebook
      • Instagram
      • Twitter
      • YouTube
      • Buzzsprout
      • Rss
      • Linkedin
      • System Status
      • Site Map
      • System Status
      • Site Map
      • facebook
      • instagram
      • twitter
      • youtube
      • buzzsprout
      • rss
      • linkedin

      Copyright © 2023 SAMSUNG. All rights reserved.