1.0.8 • Published 1 month ago

react-native-tone-framework v1.0.8

Weekly downloads
-
License
MIT
Repository
github
Last release
1 month ago

React Native Tone Framework

Introduction:

Tonelisten is an React Native framework that can be used to integrate with React Native based Android and iOS applications. It was primarily written in Javascript, Kotlin for Android and Javascript and swift for iOS. The main concept behind Tonelisten is to display information to the user when it detects specific frequencies of tones being played around the user's device microphone.

Pre-requisites:

  • Client key: Obtain the client key from Tone Framework official Site.
  • Tonelisten Framework: The Tonelisten Framework’s npm package can be obtained from npm package site.
  • Android: Android API level 22 or above required.
  • iOS: iOS version 12 or above required.

The following shows how to integrate the SDK using NPM:

  • To begin, open the terminal with your project directory.
  • Execute:
 npm install react-native-tone-framework
  • This will add Tonelisten react native framework to your project.

For iOS:

Install Pod:

  • On the project source path, open the terminal.
  • Use the below command,
  pod deintegrate

the above comment will remove the existing pod references from the project.

  • Use the below command,
  pod install

this will install the dependencies.

Permission:

  • You need to add “Background modes” capabilities to your project to allow using microphone and location service in the background.
  • Ensure you have the following entries in your ‘Info.plist’ file,
  • ‘NSMicrophoneUsageDescription’: A string describing the usage of requesting access to the microphone.
  • ‘NSLocationWhenInUseUsageDescription’: A string describing the usage of requesting location access.
  • Add the above permissions on your ‘Info.plist’ file like the following below,
  <key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
  <string>We use the location to provide accurate and relative information for users</string>
  <key>NSLocationAlwaysUsageDescription</key>
  <string>We use the location to provide accurate and relative information for users</string>
  <key>NSLocationWhenInUseUsageDescription</key>
  <string>We use the location to provide accurate and relative information for users</string>
  <key>NSMicrophoneUsageDescription</key>
  <string>This app requires microphone access to enable voice commands.</string>

For Android:

Import SDK:

  • Add the following permission to your Android Manifest:
<manifest>
  <uses-permission android:name="android.permission.INTERNET"/>
  <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
  <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
  <uses-permission android:name="android.permission.VIBRATE"/>
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
  <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
</manifest>
  • Add the following Dependency in Android Build.gradle:

Groovy Gradle:

implementation 'com.google.code.gson:gson:2.10.1'

Kotlin Gradle:

implementation(“com.google.code.gson:gson:2.10.1”)

Now Import the methods you need to call from the framework.

For Example:

import { multiply, setClientID, initFramework, onToneDetected, start, stop } from 'react-native-tone-framework';
  • Navigate to your Android Directory, app/src/main/java/com/sample/package/
  • Here, In your MainActivity, extend ToneReceiver, and Implement onReceiveTone() method.
  • In onCreate() method of your MainActivity, initialize ToneBroadcastReceiver() class to a variable.
override fun onCreate(savedInstanceState: Bundle?) {
  setTheme(R.style.AppTheme)
  super.onCreate(null)
  br = ToneBroadcastReceiver(this)
}
  • Then, in onStart() method, create a intent filter with string value of com.strutbebetter.tonelisten.broadcast.TONERESPONSE and register a receiver passing context, broadastReceiver and receiver flag.
override fun onStart() {
   super.onStart()
   val filter: IntentFilter = IntentFilter("com.strutbebetter.tonelisten.broadcast.TONERESPONSE")
   ContextCompat.registerReceiver(this, br!!, filter, ContextCompat.RECEIVER_EXPORTED)
}
  • In onDestroy() method method unregister the registered BroadcastReceiver.
override fun onDestroy() {
super.onDestroy()
this.unregisterReceiver(br!!)
}
  • Now, create a new model class, with three variables, actionType, actionUrl and isBadCode.
  • Create a new File named, ToneBroadcastReceiver and add the following code:
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.IBinder
import android.util.Log


class ToneBroadcastReceiver(private var toneReceiver: ToneReceiver): BroadcastReceiver()  {


   private val TAG = "BroadcastReceiver"


   override fun onReceive(context: Context?, intent: Intent) {
       Log.d(TAG, "ToneBroadcastReceiver: " + intent.getStringExtra("actionType"))
       toneReceiver.onReceiveTone(intent)
   }


   override fun peekService(myContext: Context?, service: Intent?): IBinder {
       return super.peekService(myContext, service)
   }
}


interface ToneReceiver {
   fun onReceiveTone(intent: Intent?)
}
  • Now, create a file for your react module, then Navigate to your Application class.
  • In that Application class, link your module class to your react native application, by adding packages.add(MyReactPackage()) inside getPackages() method.
  • Then create a new private class inside your Application class, and inherit ReactPackage inside createNativeModules() method add your module class, modules.add(MainModule(reactApplicationContext)).
private class MyReactPackage : ReactPackage {
 override fun createNativeModules(reactApplicationContext: ReactApplicationContext): MutableList<NativeModule> {
   val modules: MutableList<NativeModule> = ArrayList<NativeModule>()
   modules.add(MainModule(reactApplicationContext))
   return modules
 }


 override fun createViewManagers(p0: ReactApplicationContext): MutableList<ViewManager<View, ReactShadowNode<*>>> {
   return Collections.emptyList()
 }
}
  • Inside your module class, create a method, with intent in its params.
  • Now navigate to your MainActivity, inside the onReceiveTone() method, pass the intent to the method created in your module class.
override fun onReceiveTone(intent: Intent?) {
   if (intent != null) {
       val reactContext = reactInstanceManager.currentReactContext
       val myModule: MainModule? = reactContext?.getNativeModule(MainModule::class.java)
       myModule?.passIntentToModule(intent)
   }
}
  • Now, in your Module class, get data from intent, you can get actionType, actionUrl and isBadCode from that intent.
  • Then you can use isBadCode to check whether the detected ToneTag was the wrong one, and actionType contains the type of the content received from API.
  • Create a model, and add actionType, actionUrl, and body to the model, for Body, you can pass the data you want.
  • Then convert the model into JsonString, and then you can create an event to emit the JsonString from Native code to Javascript code.
@ReactMethod
fun passIntentToModule(intent: Intent) {
   dataIntent = intent
   if (!intent.getBooleanExtra("isBadCode", false)) {
       val toneModel = ToneModel(intent.getStringExtra("actionType"), intent.getStringExtra("actionUrl"),"ToneDemo")
       val gson = Gson()
       val dataArray: String = gson.toJson(toneModel)
       reactApplicationContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
           .emit("ToneDetected", dataArray)
   } else {
       Log.d("passIntentToModule", "passIntentToModule: Bad Code")
   }
}
  • In App.js, add a DeviceEventEmitter listener to listen for data emitted from native code, so use the key value as you set in emit method, then call the onToneDetected() and pass the value the you get from the listener.
  • Now in your App() method in App.js file, Utilize React.useEffect hook in a React functional component to perform several actions.
  • Use that function, and call initFramework() to initialize Tone Framework.
  • Call setClientID() method, and pass client ID as string in Params.
  • Then call Start() method to start the Tone Framework.
  • The Stop() method can be called to stop the Tone Framework.

License

MIT


JSONStreamabort-controlleracceptsacornacorn-jsxacorn-walkadd-streamagent-baseaggregate-errorajvanseransi-alignansi-escapesansi-fragmentsansi-regexansi-stylesanymatchappdirsjsargargparsearray-buffer-byte-lengtharray-ifyarray-includesarray-unionarray.prototype.findlastarray.prototype.flatarray.prototype.flatmaparray.prototype.maparray.prototype.toreversedarray.prototype.tosortedarraybuffer.prototype.slicearrifyasapast-typesastral-regexasync-limiterasync-retryavailable-typed-arraysbabel-corebabel-jestbabel-plugin-istanbulbabel-plugin-jest-hoistbabel-plugin-polyfill-corejs2babel-plugin-polyfill-corejs3babel-plugin-polyfill-regeneratorbabel-plugin-transform-flow-enumsbabel-preset-current-node-syntaxbabel-preset-jestbalanced-matchbase64-jsbasic-ftpbefore-after-hookbig-integerblboxenbplist-parserbrace-expansionbracesbrowserslistbserbufferbuffer-frombundle-namebytescacheable-lookupcacheable-requestcall-bindcaller-callsitecaller-pathcallsitescamelcasecamelcase-keyscaniuse-litechalkchar-regexchardetchrome-launcherchromium-edge-launcherci-infocjs-module-lexerclean-stackcli-boxescli-cursorcli-spinnerscli-widthcliuicloneclone-deepcocollect-v8-coveragecolor-convertcolor-namecolorettecommand-existscommandercommondircompare-funccompressiblecompressionconcat-mapconcat-streamconfig-chainconfigstoreconnectconventional-changelogconventional-changelog-angularconventional-changelog-atomconventional-changelog-codemirrorconventional-changelog-conventionalcommitsconventional-changelog-coreconventional-changelog-emberconventional-changelog-eslintconventional-changelog-expressconventional-changelog-jqueryconventional-changelog-jshintconventional-changelog-preset-loaderconventional-changelog-writerconventional-commits-filterconventional-commits-parserconventional-recommended-bumpconvert-source-mapcore-js-compatcore-util-iscosmiconfigcosmiconfig-typescript-loadercreate-jestcreate-requirecross-spawncrypto-random-stringcsstypedargsdata-uri-to-bufferdata-view-bufferdata-view-byte-lengthdata-view-byte-offsetdateformatdayjsdebugdecamelizedecamelize-keysdecompress-responsededentdeep-extenddeep-isdeepmergedefault-browserdefault-browser-iddefaultsdefer-to-connectdefine-data-propertydefine-lazy-propdefine-propertiesdegeneratordeldenodeifydepddeprecated-react-native-prop-typesdeprecationdestroydetect-newlinediffdiff-sequencesdir-globdoctrinedot-propeastasianwidthee-firstelectron-to-chromiumemitteryemoji-regexencodeurlend-of-streamenvinfoerror-exerror-stack-parsererrorhandleres-abstractes-array-method-boxes-properlyes-define-propertyes-errorses-get-iteratores-iterator-helperses-object-atomses-set-tostringtages-shim-unscopableses-to-primitiveescaladeescape-goatescape-htmlescape-string-regexpescodegeneslint-plugin-eslint-commentseslint-plugin-ft-floweslint-plugin-jesteslint-plugin-reacteslint-plugin-react-hookseslint-plugin-react-nativeeslint-plugin-react-native-globalseslint-scopeeslint-visitor-keysespreeesprimaesqueryesrecurseestraverseesutilsetagevent-target-shimexecaexitexpectexternal-editorfast-deep-equalfast-difffast-globfast-json-stable-stringifyfast-levenshteinfast-xml-parserfastqfb-watchmanfetch-blobfiguresfile-entry-cachefill-rangefinalhandlerfind-cache-dirfind-upflat-cacheflattedflow-enums-runtimeflow-parserfor-eachform-data-encoderformdata-polyfillfreshfs-extrafs.realpathfunction-bindfunction.prototype.namefunctions-have-namesgensyncget-caller-fileget-intrinsicget-package-typeget-pkg-repoget-streamget-symbol-descriptionget-urigit-raw-commitsgit-remote-origin-urlgit-semver-tagsgit-upgit-url-parsegitconfiglocalglobglob-parentglobal-dirsglobalsglobalthisglobbygopdgotgraceful-fsgraphemerhandlebarshard-rejectionhas-bigintshas-flaghas-property-descriptorshas-protohas-symbolshas-tostringtaghas-yarnhasownhermes-estreehermes-parserhermes-profile-transformerhosted-git-infohtml-escaperhttp-cache-semanticshttp-errorshttp-proxy-agenthttp2-wrapperhttps-proxy-agenthuman-signalsiconv-liteieee754ignoreimage-sizeimport-freshimport-lazyimport-localimurmurhashindent-stringinflightinheritsiniinquirerinternal-slotinterpretinvariantipip-addressis-absoluteis-argumentsis-array-bufferis-arrayishis-async-functionis-bigintis-boolean-objectis-callableis-ciis-core-moduleis-data-viewis-date-objectis-directoryis-dockeris-extglobis-finalizationregistryis-fullwidth-code-pointis-generator-fnis-generator-functionis-git-dirtyis-git-repositoryis-globis-inside-containeris-installed-globallyis-interactiveis-mapis-negative-zerois-npmis-numberis-number-objectis-objis-path-cwdis-path-insideis-plain-objis-plain-objectis-regexis-relativeis-setis-shared-array-bufferis-sshis-streamis-stringis-symbolis-text-pathis-typed-arrayis-typedarrayis-unc-pathis-unicode-supportedis-weakmapis-weakrefis-weaksetis-windowsis-wslis-yarn-globalisarrayisexeisobjectissue-parseristanbul-lib-coverageistanbul-lib-instrumentistanbul-lib-reportistanbul-lib-source-mapsistanbul-reportsiterate-iteratoriterate-valueiterator.prototypejest-changed-filesjest-circusjest-clijest-configjest-diffjest-docblockjest-eachjest-environment-nodejest-get-typejest-haste-mapjest-leak-detectorjest-matcher-utilsjest-message-utiljest-mockjest-pnp-resolverjest-regex-utiljest-resolvejest-resolve-dependenciesjest-runnerjest-runtimejest-snapshotjest-utiljest-validatejest-watcherjest-workerjetifierjoijs-tokensjs-yamljsbnjsc-androidjsc-safe-urljscodeshiftjsescjson-bufferjson-parse-better-errorsjson-parse-even-better-errorsjson-schema-traversejson-stable-stringify-without-jsonifyjson-stringify-safejson5jsonfilejsonparsejsx-ast-utilskeyvkind-ofkleurlatest-versionlevenlevnlighthouse-loggerlines-and-columnsload-json-filelocate-pathlodashlodash.camelcaselodash.capitalizelodash.debouncelodash.escaperegexplodash.isfunctionlodash.ismatchlodash.isplainobjectlodash.isstringlodash.kebabcaselodash.mergelodash.mergewithlodash.snakecaselodash.startcaselodash.throttlelodash.uniqlodash.uniqbylodash.upperfirstlog-symbolslogkittyloose-envifylowercase-keyslru-cachemacos-releasemake-dirmake-errormakeerrormap-objmarkymemoize-onemeowmerge-streammerge2metrometro-babel-transformermetro-cachemetro-cache-keymetro-configmetro-coremetro-file-mapmetro-minify-tersermetro-resolvermetro-runtimemetro-source-mapmetro-symbolicatemetro-transform-pluginsmetro-transform-workermicromatchmimemime-dbmime-typesmimic-fnmimic-responsemin-indentminimatchminimistminimist-optionsmkdirpmodify-valuesmsmute-streamnatural-comparenatural-compare-litenegotiatorneo-asyncnetmasknew-github-release-urlnocachenode-abort-controllernode-dirnode-domexceptionnode-fetchnode-int64node-releasesnode-stream-zipnormalize-package-datanormalize-pathnormalize-urlnpm-run-pathnullthrowsob1object-assignobject-inspectobject-keysobject.assignobject.entriesobject.fromentriesobject.hasownobject.valueson-finishedon-headersonceonetimeopenoptionatororaos-nameos-tmpdirp-cancelablep-limitp-locatep-mapp-trypac-proxy-agentpac-resolverpackage-jsonparent-moduleparse-jsonparse-pathparse-urlparseurlpath-existspath-is-absolutepath-keypath-parsepath-typepicocolorspicomatchpifypiratespkg-dirpossible-typed-array-namesprelude-lsprettier-linter-helperspretty-formatprocess-nextick-argspromisepromise.allsettledpromptsprop-typesproto-listprotocolsproxy-agentproxy-from-envpumppunycodepupapure-randqqueuequeue-microtaskquick-lrurange-parserrcreact-devtools-corereact-isreact-refreshreact-shallow-rendererread-pkgread-pkg-upreadable-streamreadlinerecastrechoirredentreflect.getprototypeofregenerateregenerate-unicode-propertiesregenerator-runtimeregenerator-transformregexp.prototype.flagsregexpu-coreregistry-auth-tokenregistry-urlregjsparserrequire-directoryrequire-from-stringrequire-main-filenameresolveresolve-alpnresolve-cwdresolve-fromresolve-globalresolve.exportsresponselikerestore-cursorretryreusifyrimrafrun-applescriptrun-asyncrun-parallelrxjssafe-array-concatsafe-buffersafe-regex-testsafer-bufferschedulersemversemver-diffsendserialize-errorserve-staticset-blockingset-function-lengthset-function-namesetprototypeofshallow-cloneshebang-commandshebang-regexshell-quoteshelljsside-channelsignal-exitsisteransislashslice-ansismart-buffersockssocks-proxy-agentsource-mapsource-map-supportspdx-correctspdx-exceptionsspdx-expression-parsespdx-license-idssplitsplit2sprintf-jsstack-utilsstackframestacktrace-parserstatusesstdin-discarderstop-iteration-iteratorstring-lengthstring-natural-comparestring-widthstring.prototype.matchallstring.prototype.trimstring.prototype.trimendstring.prototype.trimstartstring_decoderstrip-ansistrip-bomstrip-final-newlinestrip-indentstrip-json-commentsstrnumsudo-promptsupports-colorsupports-preserve-symlinks-flagsynckittemptemp-dirtersertest-excludetext-extensionstext-tablethroatthroughthrough2titleizetmptmplto-fast-propertiesto-regex-rangetoidentifiertr46trim-newlinests-nodetslibtsutilsturbo-darwin-arm64type-checktype-detecttype-festtyped-array-buffertyped-array-byte-lengthtyped-array-byte-offsettyped-array-lengthtypedarraytypedarray-to-bufferuglify-jsunbox-primitiveunc-path-regexunicode-canonical-property-names-ecmascriptunicode-match-property-ecmascriptunicode-match-property-value-ecmascriptunicode-property-aliases-ecmascriptunique-stringuniversal-user-agentuniversalifyunpipeuntildifyupdate-browserslist-dbupdate-notifieruri-jsurl-joinutil-deprecateutils-mergev8-compile-cache-libv8-to-istanbulvalidate-npm-package-licensevaryvlqvm2walkerwcwidthweb-streams-polyfillwebidl-conversionswhatwg-fetchwhatwg-urlwhichwhich-boxed-primitivewhich-builtin-typewhich-collectionwhich-modulewhich-typed-arraywidest-linewildcard-matchwindows-releaseword-wrapwordwrapwrap-ansiwrappywrite-file-atomicwsxdg-basedirxtendy18nyallistyamlyargsyargs-parserynyocto-queue
1.0.8

1 month ago

1.0.7

1 month ago

1.0.6

1 month ago

1.0.5

1 month ago

1.0.4

1 month ago

1.0.3

1 month ago

1.0.2

1 month ago

1.0.1

1 month ago

1.0.0

1 month ago