├── library
├── consumer-rules.pro
├── .gitignore
├── src
│ └── main
│ │ ├── java
│ │ └── com
│ │ │ └── fraggjkee
│ │ │ └── smsconfirmationview
│ │ │ ├── StringExt.kt
│ │ │ ├── smsretriever
│ │ │ ├── SmsParser.kt
│ │ │ ├── SmsRetrieverContract.kt
│ │ │ └── SmsRetrieverReceiver.kt
│ │ │ ├── BindingAdapters.kt
│ │ │ ├── ActionModeCallback.kt
│ │ │ ├── AndroidExtensions.kt
│ │ │ ├── SmsConfirmationViewExt.kt
│ │ │ ├── SymbolView.kt
│ │ │ ├── SmsConfirmationViewStyleUtils.kt
│ │ │ └── SmsConfirmationView.kt
│ │ └── res
│ │ ├── menu
│ │ └── context_menu.xml
│ │ └── values
│ │ ├── dimens.xml
│ │ └── attrs.xml
├── proguard-rules.pro
└── build.gradle
├── sample
├── .gitignore
├── src
│ └── main
│ │ ├── res
│ │ ├── values
│ │ │ ├── strings.xml
│ │ │ ├── colors.xml
│ │ │ └── styles.xml
│ │ ├── mipmap-hdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ ├── mipmap-mdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ ├── mipmap-xhdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxhdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxxhdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ ├── mipmap-anydpi-v26
│ │ │ ├── ic_launcher.xml
│ │ │ └── ic_launcher_round.xml
│ │ ├── layout
│ │ │ └── activity_main.xml
│ │ ├── drawable-v24
│ │ │ └── ic_launcher_foreground.xml
│ │ └── drawable
│ │ │ └── ic_launcher_background.xml
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ └── com
│ │ └── fraggjkee
│ │ └── smsconfirmationview
│ │ └── sample
│ │ └── MainActivity.kt
├── proguard-rules.pro
└── build.gradle
├── jitpack.yml
├── images
├── demo.png
├── screenshot1.png
└── screenshot2.png
├── settings.gradle
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradle.properties
├── gradlew.bat
├── .gitignore
├── README.md
├── gradlew
└── LICENSE
/library/consumer-rules.pro:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/sample/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/jitpack.yml:
--------------------------------------------------------------------------------
1 | jdk:
2 | - openjdk17
--------------------------------------------------------------------------------
/library/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/images/demo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fraggjkee/sms-confirmation-view/HEAD/images/demo.png
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':library'
2 | include ':sample'
3 | rootProject.name = "SmsConfirmationView"
4 |
--------------------------------------------------------------------------------
/images/screenshot1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fraggjkee/sms-confirmation-view/HEAD/images/screenshot1.png
--------------------------------------------------------------------------------
/images/screenshot2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fraggjkee/sms-confirmation-view/HEAD/images/screenshot2.png
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fraggjkee/sms-confirmation-view/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/sample/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | SmsConfirmationView
3 |
4 |
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fraggjkee/sms-confirmation-view/HEAD/sample/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fraggjkee/sms-confirmation-view/HEAD/sample/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fraggjkee/sms-confirmation-view/HEAD/sample/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fraggjkee/sms-confirmation-view/HEAD/sample/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fraggjkee/sms-confirmation-view/HEAD/sample/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fraggjkee/sms-confirmation-view/HEAD/sample/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fraggjkee/sms-confirmation-view/HEAD/sample/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fraggjkee/sms-confirmation-view/HEAD/sample/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fraggjkee/sms-confirmation-view/HEAD/sample/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fraggjkee/sms-confirmation-view/HEAD/sample/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/library/src/main/java/com/fraggjkee/smsconfirmationview/StringExt.kt:
--------------------------------------------------------------------------------
1 | package com.fraggjkee.smsconfirmationview
2 |
3 | internal fun String.digits(): String = filter { char -> char.isDigit() }
--------------------------------------------------------------------------------
/sample/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #6200EE
4 | #3700B3
5 | #03DAC5
6 |
7 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
4 | networkTimeout=10000
5 | validateDistributionUrl=true
6 | zipStoreBase=GRADLE_USER_HOME
7 | zipStorePath=wrapper/dists
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/library/src/main/res/menu/context_menu.xml:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/library/src/main/java/com/fraggjkee/smsconfirmationview/smsretriever/SmsParser.kt:
--------------------------------------------------------------------------------
1 | package com.fraggjkee.smsconfirmationview.smsretriever
2 |
3 | internal object SmsParser {
4 |
5 | // TODO this might require improvement/refactoring
6 | fun parseOneTimeCode(message: String, codeLength: Int): String? {
7 | val regex = "\\d{$codeLength}".toRegex()
8 | return regex.find(message)?.value
9 | }
10 | }
--------------------------------------------------------------------------------
/sample/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/library/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | 8dp
5 | 2dp
6 | 42dp
7 | 48dp
8 | 22sp
9 | 2dp
10 |
11 |
12 |
--------------------------------------------------------------------------------
/library/src/main/java/com/fraggjkee/smsconfirmationview/smsretriever/SmsRetrieverContract.kt:
--------------------------------------------------------------------------------
1 | package com.fraggjkee.smsconfirmationview.smsretriever
2 |
3 | import android.app.Activity
4 | import android.content.Context
5 | import android.content.Intent
6 | import androidx.activity.result.contract.ActivityResultContract
7 | import com.google.android.gms.auth.api.phone.SmsRetriever
8 |
9 | internal class SmsRetrieverContract : ActivityResultContract() {
10 |
11 | override fun createIntent(context: Context, input: Intent): Intent = input
12 |
13 | override fun parseResult(resultCode: Int, intent: Intent?): String? {
14 | if (resultCode != Activity.RESULT_OK || intent == null) {
15 | return null
16 | }
17 |
18 | return intent.getStringExtra(SmsRetriever.EXTRA_SMS_MESSAGE)
19 | }
20 | }
--------------------------------------------------------------------------------
/library/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/sample/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/sample/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
11 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/sample/src/main/java/com/fraggjkee/smsconfirmationview/sample/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package com.fraggjkee.smsconfirmationview.sample
2 |
3 | import android.os.Bundle
4 | import android.widget.Toast
5 | import androidx.appcompat.app.AppCompatActivity
6 | import com.fraggjkee.smsconfirmationview.SmsConfirmationView
7 |
8 | class MainActivity : AppCompatActivity() {
9 |
10 | override fun onCreate(savedInstanceState: Bundle?) {
11 | super.onCreate(savedInstanceState)
12 | setContentView(R.layout.activity_main)
13 |
14 | val view = findViewById(R.id.sms_code_view)
15 | view.onChangeListener = SmsConfirmationView.OnChangeListener { code, isComplete ->
16 | Toast.makeText(this, "value: $code, isComplete: $isComplete", Toast.LENGTH_SHORT)
17 | .show()
18 | }
19 |
20 | view.startListeningForIncomingMessages()
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/library/src/main/java/com/fraggjkee/smsconfirmationview/smsretriever/SmsRetrieverReceiver.kt:
--------------------------------------------------------------------------------
1 | package com.fraggjkee.smsconfirmationview.smsretriever
2 |
3 | import android.content.BroadcastReceiver
4 | import android.content.Context
5 | import android.content.Intent
6 | import com.google.android.gms.auth.api.phone.SmsRetriever
7 | import com.google.android.gms.common.api.CommonStatusCodes
8 | import com.google.android.gms.common.api.Status
9 |
10 | internal abstract class SmsRetrieverReceiver : BroadcastReceiver() {
11 |
12 | override fun onReceive(context: Context, intent: Intent) {
13 | if (SmsRetriever.SMS_RETRIEVED_ACTION != intent.action) return
14 |
15 | val extras = intent.extras
16 | val smsRetrieverStatus = extras?.get(SmsRetriever.EXTRA_STATUS) as? Status
17 | if (smsRetrieverStatus?.statusCode == CommonStatusCodes.SUCCESS) {
18 | val consentIntent: Intent? = extras.getParcelable(SmsRetriever.EXTRA_CONSENT_INTENT)
19 | consentIntent?.let { onConsentIntentRetrieved(it) }
20 | }
21 | }
22 |
23 | abstract fun onConsentIntentRetrieved(intent: Intent)
24 | }
--------------------------------------------------------------------------------
/sample/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 | apply plugin: 'kotlin-android'
3 |
4 | android {
5 | namespace 'com.fraggjkee.smsconfirmationview.sample'
6 | compileSdk = 36
7 |
8 | compileOptions {
9 | sourceCompatibility JavaVersion.VERSION_17
10 | targetCompatibility JavaVersion.VERSION_17
11 | }
12 |
13 | defaultConfig {
14 | applicationId "com.fraggjkee.smsconfirmationview"
15 | minSdkVersion 23
16 | targetSdkVersion 36
17 | versionCode 1
18 | versionName "1.0"
19 |
20 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
21 | }
22 |
23 | buildTypes {
24 | release {
25 | minifyEnabled false
26 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
27 | }
28 | }
29 | }
30 |
31 | dependencies {
32 | implementation project(path: ':library')
33 | // implementation "com.github.fraggjkee:sms-confirmation-view:1.7.1"
34 | implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
35 | implementation "androidx.appcompat:appcompat:1.7.1"
36 | implementation "com.google.android.material:material:1.13.0"
37 | }
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx2048m
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 | # AndroidX package structure to make it clearer which packages are bundled with the
15 | # Android operating system, and which are packaged with your app"s APK
16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
17 | android.useAndroidX=true
18 | # Automatically convert third-party libraries to use AndroidX
19 | android.enableJetifier=true
20 | # Kotlin code style for this project: "official" or "obsolete":
21 | kotlin.code.style=official
22 |
--------------------------------------------------------------------------------
/library/src/main/res/values/attrs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/library/src/main/java/com/fraggjkee/smsconfirmationview/BindingAdapters.kt:
--------------------------------------------------------------------------------
1 | @file:Suppress("unused")
2 |
3 | package com.fraggjkee.smsconfirmationview
4 |
5 | import androidx.databinding.BindingAdapter
6 | import androidx.databinding.InverseBindingAdapter
7 | import androidx.databinding.InverseBindingListener
8 |
9 | @BindingAdapter("enteredCode")
10 | fun setEnteredCode(view: SmsConfirmationView, code: String?) {
11 | val viewCode = view.enteredCode
12 | if (viewCode.isEmpty() && code.isNullOrEmpty()) return
13 | if (viewCode == code) return
14 |
15 | view.enteredCode = code.orEmpty()
16 | }
17 |
18 | @InverseBindingAdapter(attribute = "enteredCode")
19 | fun getEnteredCode(view: SmsConfirmationView): String = view.enteredCode
20 |
21 | @BindingAdapter(
22 | "onChangeListener",
23 | "enteredCodeAttrChanged",
24 | requireAll = false
25 | )
26 | fun setListener(
27 | view: SmsConfirmationView,
28 | listener: SmsConfirmationView.OnChangeListener?,
29 | attrListener: InverseBindingListener?
30 | ) {
31 | if (attrListener == null) {
32 | view.onChangeListener = listener
33 | } else {
34 | view.onChangeListener = SmsConfirmationView.OnChangeListener { code, isComplete ->
35 | listener?.onCodeChange(code, isComplete)
36 | attrListener.onChange()
37 | }
38 | }
39 | }
--------------------------------------------------------------------------------
/sample/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
29 |
30 |
--------------------------------------------------------------------------------
/sample/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
9 |
15 |
18 |
21 |
22 |
23 |
24 |
30 |
31 |
--------------------------------------------------------------------------------
/library/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 | apply plugin: 'kotlin-android'
3 | apply plugin: 'kotlin-kapt'
4 | apply plugin: 'maven-publish'
5 |
6 | android {
7 | namespace 'com.fraggjkee.smsconfirmationview'
8 | compileSdk = 36
9 |
10 | defaultConfig {
11 | minSdkVersion 23
12 | targetSdkVersion 36
13 |
14 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
15 | consumerProguardFiles "consumer-rules.pro"
16 | }
17 |
18 | compileOptions {
19 | sourceCompatibility JavaVersion.VERSION_17
20 | targetCompatibility JavaVersion.VERSION_17
21 | }
22 |
23 | buildTypes {
24 | release {
25 | minifyEnabled false
26 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
27 | }
28 | }
29 |
30 | buildFeatures {
31 | dataBinding true
32 | }
33 | }
34 |
35 | dependencies {
36 | implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
37 | implementation "com.google.android.material:material:1.13.0"
38 |
39 | // Required for automatic code retrieval from SMS (Consent API)
40 | // https://developers.google.com/identity/sms-retriever/user-consent/overview
41 | implementation "com.google.android.gms:play-services-auth:21.4.0"
42 | implementation "com.google.android.gms:play-services-auth-api-phone:18.3.0"
43 |
44 | // Contains modern "Start activity/fragment for result" APIs which are
45 | // required for SMS retrieval feature
46 | implementation "androidx.activity:activity-ktx:1.12.0"
47 | implementation "androidx.fragment:fragment-ktx:1.8.9"
48 | }
49 |
50 | publishing {
51 | publications {
52 | release(MavenPublication) {
53 | groupId = 'com.fraggjkee'
54 | artifactId = 'smsconfirmationview'
55 | version = '1.8.2'
56 |
57 | afterEvaluate {
58 | from components.release
59 | }
60 | }
61 | }
62 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/fraggjkee/smsconfirmationview/ActionModeCallback.kt:
--------------------------------------------------------------------------------
1 | package com.fraggjkee.smsconfirmationview
2 |
3 | import android.content.ClipDescription.MIMETYPE_TEXT_HTML
4 | import android.content.ClipDescription.MIMETYPE_TEXT_PLAIN
5 | import android.content.ClipboardManager
6 | import android.content.Context
7 | import android.view.ActionMode
8 | import android.view.Menu
9 | import android.view.MenuItem
10 | import androidx.core.content.getSystemService
11 |
12 | internal class ActionModeCallback(
13 | context: Context,
14 | private val onPaste: (String) -> Unit
15 | ) : ActionMode.Callback {
16 |
17 | private val clipboard = requireNotNull(context.getSystemService())
18 |
19 | override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean {
20 | return if (clipboard.hasTextClip) {
21 | mode.menuInflater.inflate(R.menu.context_menu, menu)
22 | true
23 | } else {
24 | false
25 | }
26 | }
27 |
28 | override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean {
29 | if (item.itemId == R.id.paste) {
30 | clipboard.plainTextClip?.let { plainTextClip -> onPaste(plainTextClip) }
31 | }
32 | mode.finish()
33 | return true
34 | }
35 |
36 | override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean = false
37 | override fun onDestroyActionMode(mode: ActionMode?) = Unit
38 | }
39 |
40 | private val ClipboardManager.hasTextClip: Boolean
41 | get() {
42 | val primaryClipDescription = primaryClipDescription
43 | return if (hasPrimaryClip().not() || primaryClipDescription == null) {
44 | false
45 | } else {
46 | primaryClipDescription.hasMimeType(MIMETYPE_TEXT_PLAIN) ||
47 | primaryClipDescription.hasMimeType(MIMETYPE_TEXT_HTML)
48 | }
49 | }
50 |
51 | private val ClipboardManager.plainTextClip: String?
52 | get() =
53 | if (hasTextClip) primaryClip?.getItemAt(0)?.text?.toString()
54 | else null
55 |
56 |
--------------------------------------------------------------------------------
/library/src/main/java/com/fraggjkee/smsconfirmationview/AndroidExtensions.kt:
--------------------------------------------------------------------------------
1 | package com.fraggjkee.smsconfirmationview
2 |
3 | import android.content.BroadcastReceiver
4 | import android.content.Context
5 | import android.content.ContextWrapper
6 | import android.content.IntentFilter
7 | import android.graphics.Color
8 | import android.os.Build
9 | import android.view.View
10 | import android.view.inputmethod.InputMethodManager
11 | import androidx.annotation.AttrRes
12 | import androidx.annotation.ColorInt
13 | import androidx.appcompat.app.AppCompatActivity
14 | import com.google.android.material.color.MaterialColors
15 |
16 | @ColorInt
17 | internal fun Context.getThemeColor(@AttrRes attrRes: Int): Int {
18 | return MaterialColors.getColor(this, attrRes, Color.BLACK)
19 | }
20 |
21 | internal fun View.showKeyboard() {
22 | val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
23 | imm.showSoftInput(this, 0)
24 | }
25 |
26 | internal fun View.hideKeyboard() {
27 | val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
28 | imm.hideSoftInputFromWindow(this.windowToken, 0)
29 | }
30 |
31 | // https://stackoverflow.com/a/32973351/984014
32 | internal fun View.getActivity(): AppCompatActivity? {
33 | var context = context
34 | while (context is ContextWrapper) {
35 | if (context is AppCompatActivity) {
36 | return context
37 | }
38 | context = context.baseContext
39 | }
40 | return null
41 | }
42 |
43 | internal fun Context.registerReceiver(
44 | receiver: BroadcastReceiver,
45 | intentFilter: IntentFilter,
46 | permission: String
47 | ) {
48 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
49 | @Suppress("UnspecifiedRegisterReceiverFlag")
50 | registerReceiver(
51 | receiver,
52 | intentFilter,
53 | permission,
54 | null
55 | )
56 | } else {
57 | registerReceiver(
58 | receiver,
59 | intentFilter,
60 | permission,
61 | null,
62 | Context.RECEIVER_EXPORTED
63 | )
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%"=="" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%"=="" set DIRNAME=.
29 | @rem This is normally unused
30 | set APP_BASE_NAME=%~n0
31 | set APP_HOME=%DIRNAME%
32 |
33 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
34 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
35 |
36 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
37 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
38 |
39 | @rem Find java.exe
40 | if defined JAVA_HOME goto findJavaFromJavaHome
41 |
42 | set JAVA_EXE=java.exe
43 | %JAVA_EXE% -version >NUL 2>&1
44 | if %ERRORLEVEL% equ 0 goto execute
45 |
46 | echo.
47 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
48 | echo.
49 | echo Please set the JAVA_HOME variable in your environment to match the
50 | echo location of your Java installation.
51 |
52 | goto fail
53 |
54 | :findJavaFromJavaHome
55 | set JAVA_HOME=%JAVA_HOME:"=%
56 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
57 |
58 | if exist "%JAVA_EXE%" goto execute
59 |
60 | echo.
61 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
62 | echo.
63 | echo Please set the JAVA_HOME variable in your environment to match the
64 | echo location of your Java installation.
65 |
66 | goto fail
67 |
68 | :execute
69 | @rem Setup the command line
70 |
71 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
72 |
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if %ERRORLEVEL% equ 0 goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | set EXIT_CODE=%ERRORLEVEL%
85 | if %EXIT_CODE% equ 0 set EXIT_CODE=1
86 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
87 | exit /b %EXIT_CODE%
88 |
89 | :mainEnd
90 | if "%OS%"=="Windows_NT" endlocal
91 |
92 | :omega
93 |
--------------------------------------------------------------------------------
/library/src/main/java/com/fraggjkee/smsconfirmationview/SmsConfirmationViewExt.kt:
--------------------------------------------------------------------------------
1 | @file:Suppress("unused")
2 |
3 | package com.fraggjkee.smsconfirmationview
4 |
5 | /**
6 | * @see R.styleable.SmsConfirmationView_scv_codeLength
7 | */
8 | var SmsConfirmationView.codeLength: Int
9 | set(value) {
10 | require(value >= 0) { "invalid code length - $value" }
11 | this.style = style.copy(codeLength = value)
12 | }
13 | get() = style.codeLength
14 |
15 | /**
16 | * @see R.styleable.SmsConfirmationView_scv_symbolsSpacing
17 | */
18 | var SmsConfirmationView.symbolsSpacing: Int
19 | set(value) {
20 | this.style = style.copy(symbolsSpacing = value)
21 | }
22 | get() = style.symbolsSpacing
23 |
24 | /**
25 | * @see R.styleable.SmsConfirmationView_scv_showCursor
26 | */
27 | var SmsConfirmationView.showCursor: Boolean
28 | set(value) {
29 | val updatedStyle = style.symbolViewStyle.copy(
30 | showCursor = value
31 | )
32 | this.style = style.copy(symbolViewStyle = updatedStyle)
33 | }
34 | get() = style.symbolViewStyle.showCursor
35 |
36 | /**
37 | * @see R.styleable.SmsConfirmationView_scv_pasteEnabled
38 | */
39 | var SmsConfirmationView.isPasteEnabled: Boolean
40 | set(value) {
41 | this.style = style.copy(isPasteEnabled = value)
42 | }
43 | get() = style.isPasteEnabled
44 |
45 | /**
46 | * @see R.styleable.SmsConfirmationView_scv_symbolWidth
47 | */
48 | var SmsConfirmationView.symbolWidth: Int
49 | set(value) {
50 | val updatedStyle = style.symbolViewStyle.copy(
51 | width = value
52 | )
53 | this.style = style.copy(symbolViewStyle = updatedStyle)
54 | }
55 | get() = style.symbolViewStyle.width
56 |
57 | /**
58 | * @see R.styleable.SmsConfirmationView_scv_symbolHeight
59 | */
60 | var SmsConfirmationView.symbolHeight: Int
61 | set(value) {
62 | val updatedStyle = style.symbolViewStyle.copy(
63 | height = value
64 | )
65 | this.style = style.copy(symbolViewStyle = updatedStyle)
66 | }
67 | get() = style.symbolViewStyle.height
68 |
69 | /**
70 | * @see R.styleable.SmsConfirmationView_scv_symbolTextColor
71 | */
72 | var SmsConfirmationView.symbolTextColor: Int
73 | set(value) {
74 | val updatedStyle = style.symbolViewStyle.copy(
75 | textColor = value
76 | )
77 | this.style = style.copy(symbolViewStyle = updatedStyle)
78 | }
79 | get() = style.symbolViewStyle.textColor
80 |
81 | /**
82 | * @see R.styleable.SmsConfirmationView_scv_symbolTextSize
83 | */
84 | var SmsConfirmationView.symbolTextSize: Int
85 | set(value) {
86 | val updatedStyle = style.symbolViewStyle.copy(
87 | textSize = value
88 | )
89 | this.style = style.copy(symbolViewStyle = updatedStyle)
90 | }
91 | get() = style.symbolViewStyle.textSize
92 |
93 | /**
94 | * @see R.styleable.SmsConfirmationView_scv_symbolBackgroundColor
95 | */
96 | var SmsConfirmationView.symbolBackgroundColor: Int
97 | set(value) {
98 | val updatedStyle = style.symbolViewStyle.copy(
99 | backgroundColor = value
100 | )
101 | this.style = style.copy(symbolViewStyle = updatedStyle)
102 | }
103 | get() = style.symbolViewStyle.backgroundColor
104 |
105 | /**
106 | * @see R.styleable.SmsConfirmationView_scv_symbolBorderColor
107 | */
108 | var SmsConfirmationView.symbolBorderColor: Int
109 | set(value) {
110 | val updatedStyle = style.symbolViewStyle.copy(
111 | borderColor = value
112 | )
113 | this.style = style.copy(symbolViewStyle = updatedStyle)
114 | }
115 | get() = style.symbolViewStyle.borderColor
116 |
117 | /**
118 | * @see R.styleable.SmsConfirmationView_scv_symbolBorderActiveColor
119 | */
120 | var SmsConfirmationView.symbolBorderActiveColor: Int
121 | set(value) {
122 | val updatedStyle = style.symbolViewStyle.copy(
123 | borderColorActive = value
124 | )
125 | this.style = style.copy(symbolViewStyle = updatedStyle)
126 | }
127 | get() = style.symbolViewStyle.borderColorActive
128 |
129 | /**
130 | * @see R.styleable.SmsConfirmationView_scv_symbolBorderWidth
131 | */
132 | var SmsConfirmationView.symbolBorderWidth: Int
133 | set(value) {
134 | val updatedStyle = style.symbolViewStyle.copy(
135 | borderWidth = value
136 | )
137 | this.style = style.copy(symbolViewStyle = updatedStyle)
138 | }
139 | get() = style.symbolViewStyle.borderWidth
140 |
141 | /**
142 | * @see R.styleable.SmsConfirmationView_scv_symbolBorderCornerRadius
143 | */
144 | var SmsConfirmationView.symbolBorderCornerRadius: Float
145 | set(value) {
146 | val updatedStyle = style.symbolViewStyle.copy(
147 | borderCornerRadius = value
148 | )
149 | this.style = style.copy(symbolViewStyle = updatedStyle)
150 | }
151 | get() = style.symbolViewStyle.borderCornerRadius
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Created by https://www.gitignore.io/api/java,macos,linux,gradle,windows,android,androidstudio
2 | # Edit at https://www.gitignore.io/?templates=java,macos,linux,gradle,windows,android,androidstudio
3 |
4 | ### Android ###
5 | # Built application files
6 | *.apk
7 | *.ap_
8 | *.aab
9 |
10 | # Files for the ART/Dalvik VM
11 | *.dex
12 |
13 | # Java class files
14 | *.class
15 |
16 | # Generated files
17 | bin/
18 | gen/
19 | out/
20 | release/
21 |
22 | # Gradle files
23 | .gradle/
24 | build/
25 |
26 | # Local configuration file (sdk path, etc)
27 | local.properties
28 |
29 | # Proguard folder generated by Eclipse
30 | proguard/
31 |
32 | # Log Files
33 | *.log
34 |
35 | # Android Studio Navigation editor temp files
36 | .navigation/
37 |
38 | # Android Studio captures folder
39 | captures/
40 |
41 | # IntelliJ
42 | *.iml
43 | .idea/
44 |
45 | # Keystore files
46 | # Uncomment the following lines if you do not want to check your keystore files in.
47 | #*.jks
48 | #*.keystore
49 |
50 | # External native build folder generated in Android Studio 2.2 and later
51 | .externalNativeBuild
52 |
53 | # Google Services (e.g. APIs or Firebase)
54 | # google-services.json
55 |
56 | # Freeline
57 | freeline.py
58 | freeline/
59 | freeline_project_description.json
60 |
61 | # fastlane
62 | fastlane/report.xml
63 | fastlane/Preview.html
64 | fastlane/screenshots
65 | fastlane/test_output
66 | fastlane/readme.md
67 |
68 | # Version control
69 | vcs.xml
70 |
71 | # lint
72 | lint/intermediates/
73 | lint/generated/
74 | lint/outputs/
75 | lint/tmp/
76 | # lint/reports/
77 |
78 | ### Android Patch ###
79 | gen-external-apklibs
80 | output.json
81 |
82 | # Replacement of .externalNativeBuild directories introduced
83 | # with Android Studio 3.5.
84 | .cxx/
85 |
86 | ### Java ###
87 | # Compiled class file
88 |
89 | # Log file
90 |
91 | # BlueJ files
92 | *.ctxt
93 |
94 | # Mobile Tools for Java (J2ME)
95 | .mtj.tmp/
96 |
97 | # Package Files #
98 | *.jar
99 | *.war
100 | *.nar
101 | *.ear
102 | *.zip
103 | *.tar.gz
104 | *.rar
105 |
106 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
107 | hs_err_pid*
108 |
109 | ### Linux ###
110 | *~
111 |
112 | # temporary files which can be created if a process still has a handle open of a deleted file
113 | .fuse_hidden*
114 |
115 | # KDE directory preferences
116 | .directory
117 |
118 | # Linux trash folder which might appear on any partition or disk
119 | .Trash-*
120 |
121 | # .nfs files are created when an open file is removed but is still being accessed
122 | .nfs*
123 |
124 | ### macOS ###
125 | # General
126 | .DS_Store
127 | .AppleDouble
128 | .LSOverride
129 |
130 | # Icon must end with two \r
131 | Icon
132 |
133 | # Thumbnails
134 | ._*
135 |
136 | # Files that might appear in the root of a volume
137 | .DocumentRevisions-V100
138 | .fseventsd
139 | .Spotlight-V100
140 | .TemporaryItems
141 | .Trashes
142 | .VolumeIcon.icns
143 | .com.apple.timemachine.donotpresent
144 |
145 | # Directories potentially created on remote AFP share
146 | .AppleDB
147 | .AppleDesktop
148 | Network Trash Folder
149 | Temporary Items
150 | .apdisk
151 |
152 | ### Windows ###
153 | # Windows thumbnail cache files
154 | Thumbs.db
155 | Thumbs.db:encryptable
156 | ehthumbs.db
157 | ehthumbs_vista.db
158 |
159 | # Dump file
160 | *.stackdump
161 |
162 | # Folder config file
163 | [Dd]esktop.ini
164 |
165 | # Recycle Bin used on file shares
166 | $RECYCLE.BIN/
167 |
168 | # Windows Installer files
169 | *.cab
170 | *.msi
171 | *.msix
172 | *.msm
173 | *.msp
174 |
175 | # Windows shortcuts
176 | *.lnk
177 |
178 | ### Gradle ###
179 | .gradle
180 |
181 | # Ignore Gradle GUI config
182 | gradle-app.setting
183 |
184 | # Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored)
185 | !gradle-wrapper.jar
186 |
187 | # Cache of project
188 | .gradletasknamecache
189 |
190 | # # Work around https://youtrack.jetbrains.com/issue/IDEA-116898
191 | # gradle/wrapper/gradle-wrapper.properties
192 |
193 | ### Gradle Patch ###
194 | **/build/
195 |
196 | ### AndroidStudio ###
197 | # Covers files to be ignored for android development using Android Studio.
198 |
199 | # Built application files
200 |
201 | # Files for the ART/Dalvik VM
202 |
203 | # Java class files
204 |
205 | # Generated files
206 |
207 | # Gradle files
208 |
209 | # Signing files
210 | .signing/
211 |
212 | # Local configuration file (sdk path, etc)
213 |
214 | # Proguard folder generated by Eclipse
215 |
216 | # Log Files
217 |
218 | # Android Studio
219 | /*/build/
220 | /*/local.properties
221 | /*/out
222 | /*/*/build
223 | /*/*/production
224 | *.ipr
225 | *.swp
226 |
227 | # Android Patch
228 |
229 | # External native build folder generated in Android Studio 2.2 and later
230 |
231 | # NDK
232 | obj/
233 |
234 | # IntelliJ IDEA
235 | *.iws
236 | /out/
237 |
238 | # OS-specific files
239 | .DS_Store?
240 |
241 | # Legacy Eclipse project files
242 | .classpath
243 | .project
244 | .cproject
245 | .settings/
246 |
247 | # Mobile Tools for Java (J2ME)
248 |
249 | # Package Files #
250 |
251 | # virtual machine crash logs (Reference: http://www.java.com/en/download/help/error_hotspot.xml)
252 |
253 | ## Plugin-specific files:
254 |
255 | # mpeltonen/sbt-idea plugin
256 | .idea_modules/
257 |
258 | # JIRA plugin
259 | atlassian-ide-plugin.xml
260 |
261 | # Crashlytics plugin (for Android Studio and IntelliJ)
262 | com_crashlytics_export_strings.xml
263 | crashlytics.properties
264 | crashlytics-build.properties
265 | fabric.properties
266 |
267 | ### AndroidStudio Patch ###
268 |
269 | !/gradle/wrapper/gradle-wrapper.jar
270 |
271 | # End of https://www.gitignore.io/api/java,macos,linux,gradle,windows,android,androidstudio
272 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # SmsConfirmationView [](https://jitpack.io/#fraggjkee/sms-confirmation-view)
2 | A custom Android's `View` implementing all the necessary UI for a typical "enter SMS / PIN code" flow. Can be used for verification of any digit-based codes (SMS verification, PIN verification, etc.).
3 |
4 | Supports **automatic code retrieval from incoming SMS messages**. This feature is implemented using the [Consent API](https://developers.google.com/identity/sms-retriever/user-consent/overview).
5 |
6 | Supports **copy-pasting from the clipboard** by showing a floating pop-up in response to a long press event (similarly to `EditText`).
7 |
8 | You may find my initial motivations & a little bit more detailed information in this [Medium post](https://medium.com/swlh/implementing-the-complete-sms-verification-flow-using-consent-api-in-android-ae0327f74658).
9 |
10 |
11 |
12 |
13 | # Installation
14 | **Step 1.** Add the JitPack repository to your build file. Add it in your root build.gradle at the end of repositories:
15 | ```gradle
16 | allprojects {
17 | repositories {
18 | ...
19 | maven { url 'https://jitpack.io' }
20 | }
21 | }
22 | ```
23 | **Step 2.** Add the dependency
24 | ```gradle
25 | dependencies {
26 | implementation "com.github.fraggjkee:sms-confirmation-view:1.8.2"
27 | }
28 | ```
29 |
30 | # Usage
31 | Add `SmsConfirmationView` to your XML layout:
32 | ```xml
33 |
37 | ```
38 |
39 | ...and then just listen for its updates in your `Activity` or `Fragment`:
40 |
41 | ```kotlin
42 | val view: SmsConfirmationView = findViewById(R.id.sms_code_view)
43 | view.onChangeListener = SmsConfirmationView.OnChangeListener { code, isComplete ->
44 | // TODO...
45 | }
46 | ```
47 |
48 | You cal also get/set the code using the `enteredCode` property.
49 |
50 | # DataBinding
51 | This SMS verification view supports Android's DataBinding framework, including its two-way version. The list of available adapters can be found [here](https://github.com/fraggjkee/sms-confirmation-view/blob/master/library/src/main/java/com/fraggjkee/smsconfirmationview/BindingAdapters.kt).
52 |
53 | # Customization
54 |
55 | Here's the list of available XML attributes:
56 |
57 | - `scv_codeLength`: expected confirmation code length. Default value = [4](https://github.com/fraggjkee/SmsConfirmationView/blob/fb2be87c0510a10a95b343f79380de72f6fe7742/library/src/main/java/com/fraggjkee/smsconfirmationview/SmsConfirmationView.kt#L186)
58 | - `scv_showCursor`: controls whether the blinking cursor should be displayed for an active symbol. Default value = `true`. Uses the color specified by `scv_symbolBorderActiveColor`.
59 | - `scv_pasteEnabled`: enables or disables Copy/Paste support. Default value = `true`.
60 | - `scv_symbolsSpacing`: gap between individual symbol subviews. Default value = [8dp](https://github.com/fraggjkee/SmsConfirmationView/blob/fb2be87c0510a10a95b343f79380de72f6fe7742/library/src/main/res/values/dimens.xml#L4)
61 | - `scv_symbolWidth`: width of each individual symbol cell. Default value = [42dp](https://github.com/fraggjkee/SmsConfirmationView/blob/fb2be87c0510a10a95b343f79380de72f6fe7742/library/src/main/res/values/dimens.xml#L6)
62 | - `scv_symbolHeight`: height of each individual symbol cell. Default value = [48dp](https://github.com/fraggjkee/SmsConfirmationView/blob/fb2be87c0510a10a95b343f79380de72f6fe7742/library/src/main/res/values/dimens.xml#L7)
63 | - `scv_symbolTextColor`: text color used to draw text within symbol subviews. Default value = `?attr/colorOnSurface` or `Color.BLACK` if such attribute is not defined in your app's theme.
64 | - `scv_symbolTextSize`: text size used within symbol subviews. Default value = [22sp](https://github.com/fraggjkee/SmsConfirmationView/blob/fb2be87c0510a10a95b343f79380de72f6fe7742/library/src/main/res/values/dimens.xml#L8)
65 | - `scv_symbolTextFont`: text font used within symbol subviews. Default value = theme default font
66 | - `scv_symbolBackgroundColor`: filler color for symbol subviews. Default value = `?attr/colorSurface` or `Color.BLACK` if such attribute is not defined in your app's theme.
67 | - `scv_symbolBorderColor`: color to use for symbol subview's stroke outline. Default value = `?attr/colorSurface` or `Color.BLACK` if such attribute is not defined in your app's theme.
68 | - `scv_symbolBorderActiveColor`: color to use for symbol subview's stroke outline for an active symbol. Default value = `scv_symbolBorderColor`.
69 | - `scv_symbolBorderWidth`: thickness of the stroke used to draw symbol subview's border. Default value = [2dp](https://github.com/fraggjkee/SmsConfirmationView/blob/fb2be87c0510a10a95b343f79380de72f6fe7742/library/src/main/res/values/dimens.xml#L9)
70 | - `scv_symbolBorderCornerRadius`: corner radius for symbol subview's border. Default value = [2dp](https://github.com/fraggjkee/SmsConfirmationView/blob/fb2be87c0510a10a95b343f79380de72f6fe7742/library/src/main/res/values/dimens.xml#L5)
71 |
72 | All of these attributes can also be changed **programmatically** (XML customization is the preferred way though), check out the list of available extensions [here](https://github.com/fraggjkee/SmsConfirmationView/blob/master/library/src/main/java/com/fraggjkee/smsconfirmationview/SmsConfirmationViewExt.kt).
73 |
74 | # SMS Detection modes
75 | - `app:scv_smsDetectionMode="disabled"`: Prevents the view from using SMS Consent API, i.e. this option simply disables automatic SMS detection.
76 | - `app:scv_smsDetectionMode="auto"`: Default option. `SmsConfirmationView` will try to use SMS Consent API to detect incoming messages and extract confirmation codes out of the messages.
77 | - `app:scv_smsDetectionMode="manual"`: Like `auto` but gives you more control when to actually start listening for incoming messages via `startListeningForIncomingMessages` method. Can be useful in some cases as SMS Consent API cannot be active for more than 5 minutes.
78 |
79 | License
80 | ----
81 | Apache 2.0
82 |
--------------------------------------------------------------------------------
/sample/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/library/src/main/java/com/fraggjkee/smsconfirmationview/SymbolView.kt:
--------------------------------------------------------------------------------
1 | package com.fraggjkee.smsconfirmationview
2 |
3 | import android.animation.Animator
4 | import android.animation.ArgbEvaluator
5 | import android.animation.ObjectAnimator
6 | import android.annotation.SuppressLint
7 | import android.content.Context
8 | import android.graphics.Canvas
9 | import android.graphics.Paint
10 | import android.graphics.Rect
11 | import android.graphics.RectF
12 | import android.graphics.Typeface
13 | import android.util.Size
14 | import android.view.View
15 | import androidx.annotation.ColorInt
16 | import androidx.annotation.Px
17 |
18 | private const val textPaintAlphaAnimDuration = 25L
19 | private const val borderPaintAlphaAnimDuration = 150L
20 |
21 | private const val cursorAlphaAnimDuration = 500L
22 | private const val cursorAlphaAnimStartDelay = 200L
23 |
24 | private const val cursorSymbol = "|"
25 |
26 | @SuppressLint("ViewConstructor")
27 | internal class SymbolView(context: Context, private val symbolStyle: Style) : View(context) {
28 |
29 | data class State(
30 | val symbol: Char? = null,
31 | val isActive: Boolean = false
32 | )
33 |
34 | var state: State = State()
35 | set(value) {
36 | if (field == value) return
37 | field = value
38 | updateState(state)
39 | }
40 |
41 | private val showCursor: Boolean = symbolStyle.showCursor
42 | private val desiredW: Int = symbolStyle.width
43 | private val desiredH: Int = symbolStyle.height
44 | private val textSizePx: Int = symbolStyle.textSize
45 | private val cornerRadius: Float = symbolStyle.borderCornerRadius
46 |
47 | private val backgroundPaint: Paint = Paint().apply {
48 | color = symbolStyle.backgroundColor
49 | style = Paint.Style.FILL
50 | }
51 | private val borderPaint: Paint = Paint().apply {
52 | isAntiAlias = true
53 | color = symbolStyle.borderColor
54 | style = Paint.Style.STROKE
55 | strokeWidth = symbolStyle.borderWidth.toFloat()
56 | }
57 | private val textPaint: Paint = Paint().apply {
58 | isAntiAlias = true
59 | color = symbolStyle.textColor
60 | textSize = textSizePx.toFloat()
61 | typeface = Typeface.DEFAULT_BOLD
62 | textAlign = Paint.Align.CENTER
63 | }
64 |
65 | private var textSize: Size = calculateTextSize('0')
66 |
67 | private val backgroundRect = RectF()
68 |
69 | private var textAnimator: Animator? = null
70 |
71 | @Suppress("SameParameterValue")
72 | private fun calculateTextSize(symbol: Char): Size {
73 | val textBounds = Rect()
74 | textPaint.getTextBounds(symbol.toString(), 0, 1, textBounds)
75 | return Size(textBounds.width(), textBounds.height())
76 | }
77 |
78 | private fun updateState(state: State) = with(state) {
79 | textAnimator?.cancel()
80 | if (symbol == null && isActive && showCursor) {
81 | textPaint.color = symbolStyle.borderColorActive
82 | textAnimator = ObjectAnimator.ofInt(textPaint, "alpha", 255, 255, 0, 0)
83 | .apply {
84 | duration = cursorAlphaAnimDuration
85 | startDelay = cursorAlphaAnimStartDelay
86 | repeatCount = ObjectAnimator.INFINITE
87 | repeatMode = ObjectAnimator.REVERSE
88 | addUpdateListener { invalidate() }
89 | }
90 | } else {
91 | textPaint.color = symbolStyle.textColor
92 | val startAlpha = if (symbol == null) 255 else 127
93 | val endAlpha = if (symbol == null) 0 else 255
94 | textAnimator = ObjectAnimator.ofInt(textPaint, "alpha", startAlpha, endAlpha)
95 | .apply {
96 | duration = textPaintAlphaAnimDuration
97 | addUpdateListener { invalidate() }
98 | }
99 | }
100 |
101 | textAnimator?.start()
102 | animateBorderColorChange(isActive)
103 | }
104 |
105 | private fun animateBorderColorChange(isActive: Boolean) {
106 | val borderColor = symbolStyle.borderColor
107 | val borderColorActive = symbolStyle.borderColorActive
108 | if (borderColor == borderColorActive) {
109 | return
110 | }
111 |
112 | val colorFrom =
113 | if (isActive) borderColor
114 | else borderColorActive
115 | val colorTo =
116 | if (isActive) borderColorActive
117 | else borderColor
118 | ObjectAnimator.ofObject(borderPaint, "color", ArgbEvaluator(), colorFrom, colorTo)
119 | .apply {
120 | duration = borderPaintAlphaAnimDuration
121 | addUpdateListener { invalidate() }
122 | }
123 | .start()
124 | }
125 |
126 | override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
127 | val w = resolveSizeAndState(desiredW, widthMeasureSpec, 0)
128 | val h = resolveSizeAndState(desiredH, heightMeasureSpec, 0)
129 | setMeasuredDimension(w, h)
130 | }
131 |
132 | override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
133 | super.onLayout(changed, left, top, right, bottom)
134 | val borderWidthHalf = borderPaint.strokeWidth / 2
135 | backgroundRect.left = borderWidthHalf
136 | backgroundRect.top = borderWidthHalf
137 | backgroundRect.right = measuredWidth.toFloat() - borderWidthHalf
138 | backgroundRect.bottom = measuredHeight.toFloat() - borderWidthHalf
139 | }
140 |
141 | override fun onDraw(canvas: Canvas) {
142 | canvas.drawRoundRect(
143 | backgroundRect,
144 | cornerRadius,
145 | cornerRadius,
146 | backgroundPaint
147 | )
148 |
149 | canvas.drawRoundRect(
150 | backgroundRect,
151 | cornerRadius,
152 | cornerRadius,
153 | borderPaint
154 | )
155 |
156 | canvas.drawText(
157 | if (state.isActive && showCursor) cursorSymbol else state.symbol?.toString() ?: "",
158 | backgroundRect.width() / 2 + borderPaint.strokeWidth / 2,
159 | backgroundRect.height() / 2 + textSize.height / 2 + borderPaint.strokeWidth / 2,
160 | textPaint
161 | )
162 | }
163 |
164 | data class Style(
165 | val showCursor: Boolean,
166 | @Px val width: Int,
167 | @Px val height: Int,
168 | @ColorInt val backgroundColor: Int,
169 | @ColorInt val borderColor: Int,
170 | @ColorInt val borderColorActive: Int,
171 | @Px val borderWidth: Int,
172 | val borderCornerRadius: Float,
173 | @ColorInt val textColor: Int,
174 | @Px val textSize: Int,
175 | val typeface: Typeface = Typeface.DEFAULT_BOLD
176 | )
177 | }
178 |
--------------------------------------------------------------------------------
/library/src/main/java/com/fraggjkee/smsconfirmationview/SmsConfirmationViewStyleUtils.kt:
--------------------------------------------------------------------------------
1 | package com.fraggjkee.smsconfirmationview
2 |
3 | import android.content.Context
4 | import android.graphics.Typeface
5 | import android.os.Build
6 | import android.util.AttributeSet
7 | import androidx.core.content.res.ResourcesCompat
8 | import com.google.android.material.R as MaterialR
9 |
10 | internal object SmsConfirmationViewStyleUtils {
11 |
12 | private var defaultStyle: SmsConfirmationView.Style? = null
13 |
14 | fun getDefault(context: Context): SmsConfirmationView.Style {
15 | if (defaultStyle == null) {
16 | val resources = context.resources
17 | val symbolViewStyle = SymbolView.Style(
18 | showCursor = true,
19 | width = resources.getDimensionPixelSize(R.dimen.symbol_view_width),
20 | height = resources.getDimensionPixelSize(R.dimen.symbol_view_height),
21 | backgroundColor = context.getThemeColor(MaterialR.attr.colorSurface),
22 | borderColor = context.getThemeColor(androidx.appcompat.R.attr.colorPrimary),
23 | borderColorActive = context.getThemeColor(androidx.appcompat.R.attr.colorPrimary),
24 | borderWidth = resources.getDimensionPixelSize(R.dimen.symbol_view_stroke_width),
25 | borderCornerRadius = resources.getDimension(R.dimen.symbol_view_corner_radius),
26 | textColor = context.getThemeColor(MaterialR.attr.colorOnSurface),
27 | textSize = resources.getDimensionPixelSize(R.dimen.symbol_view_text_size)
28 | )
29 | defaultStyle = SmsConfirmationView.Style(
30 | codeLength = SmsConfirmationView.DEFAULT_CODE_LENGTH,
31 | symbolsSpacing = resources.getDimensionPixelSize(R.dimen.symbols_spacing),
32 | symbolViewStyle = symbolViewStyle,
33 | isPasteEnabled = true
34 | )
35 | }
36 | return defaultStyle!!
37 | }
38 |
39 | fun getFromAttributes(
40 | attrs: AttributeSet,
41 | context: Context
42 | ): SmsConfirmationView.Style {
43 |
44 | val defaultStyle: SmsConfirmationView.Style = getDefault(context)
45 | val defaultSymbolStyle: SymbolView.Style = defaultStyle.symbolViewStyle
46 | val typedArray =
47 | context.theme.obtainStyledAttributes(attrs, R.styleable.SmsConfirmationView, 0, 0)
48 |
49 | return with(typedArray) {
50 | val showCursor: Boolean = getBoolean(
51 | R.styleable.SmsConfirmationView_scv_showCursor,
52 | defaultSymbolStyle.showCursor
53 | )
54 | val isPasteEnabled: Boolean = getBoolean(
55 | R.styleable.SmsConfirmationView_scv_pasteEnabled,
56 | defaultStyle.isPasteEnabled
57 | )
58 | val symbolWidth: Int = getDimensionPixelSize(
59 | R.styleable.SmsConfirmationView_scv_symbolWidth,
60 | defaultSymbolStyle.width
61 | )
62 | val symbolHeight: Int = getDimensionPixelSize(
63 | R.styleable.SmsConfirmationView_scv_symbolHeight,
64 | defaultSymbolStyle.height
65 | )
66 | val symbolBackgroundColor: Int = getColor(
67 | R.styleable.SmsConfirmationView_scv_symbolBackgroundColor,
68 | defaultSymbolStyle.backgroundColor
69 | )
70 | val symbolBorderColor: Int = getColor(
71 | R.styleable.SmsConfirmationView_scv_symbolBorderColor,
72 | defaultSymbolStyle.borderColor
73 | )
74 | val symbolBorderActiveColor: Int = getColor(
75 | R.styleable.SmsConfirmationView_scv_symbolBorderActiveColor,
76 | symbolBorderColor
77 | )
78 | val symbolBorderWidth: Int = getDimensionPixelSize(
79 | R.styleable.SmsConfirmationView_scv_symbolBorderWidth,
80 | defaultSymbolStyle.borderWidth
81 | )
82 | val symbolTextColor: Int = getColor(
83 | R.styleable.SmsConfirmationView_scv_symbolTextColor,
84 | defaultSymbolStyle.textColor
85 | )
86 | val symbolTextSize: Int = getDimensionPixelSize(
87 | R.styleable.SmsConfirmationView_scv_symbolTextSize,
88 | defaultSymbolStyle.textSize
89 | )
90 | val cornerRadius: Float = getDimension(
91 | R.styleable.SmsConfirmationView_scv_symbolBorderCornerRadius,
92 | defaultSymbolStyle.borderCornerRadius
93 | )
94 | val codeLength: Int = getInt(
95 | R.styleable.SmsConfirmationView_scv_codeLength,
96 | defaultStyle.codeLength
97 | )
98 | val symbolsSpacingPx: Int = getDimensionPixelSize(
99 | R.styleable.SmsConfirmationView_scv_symbolsSpacing,
100 | defaultStyle.symbolsSpacing
101 | )
102 | val smsDetectionMode: SmsConfirmationView.SmsDetectionMode = getInt(
103 | R.styleable.SmsConfirmationView_scv_smsDetectionMode,
104 | SmsConfirmationView.SmsDetectionMode.AUTO.ordinal
105 | ).let { SmsConfirmationView.SmsDetectionMode.values()[it] }
106 |
107 |
108 | val symbolTextFont = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
109 | getFont(R.styleable.SmsConfirmationView_scv_symbolTextFont)
110 | ?: Typeface.DEFAULT_BOLD
111 | } else {
112 | val resId = getResourceId(R.styleable.SmsConfirmationView_scv_symbolTextFont, -1)
113 | if (resId == -1) {
114 | Typeface.DEFAULT_BOLD
115 | } else {
116 | ResourcesCompat.getFont(context, resId) ?: Typeface.DEFAULT_BOLD
117 | }
118 | }
119 |
120 | recycle()
121 |
122 | SmsConfirmationView.Style(
123 | codeLength = codeLength,
124 | isPasteEnabled = isPasteEnabled,
125 | symbolsSpacing = symbolsSpacingPx,
126 | symbolViewStyle = SymbolView.Style(
127 | showCursor = showCursor,
128 | width = symbolWidth,
129 | height = symbolHeight,
130 | backgroundColor = symbolBackgroundColor,
131 | borderColor = symbolBorderColor,
132 | borderColorActive = symbolBorderActiveColor,
133 | borderWidth = symbolBorderWidth,
134 | borderCornerRadius = cornerRadius,
135 | textColor = symbolTextColor,
136 | textSize = symbolTextSize,
137 | typeface = symbolTextFont
138 | ),
139 | smsDetectionMode = smsDetectionMode
140 | )
141 | }
142 | }
143 | }
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | #
4 | # Copyright © 2015-2021 the original authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | #
21 | # Gradle start up script for POSIX generated by Gradle.
22 | #
23 | # Important for running:
24 | #
25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
26 | # noncompliant, but you have some other compliant shell such as ksh or
27 | # bash, then to run this script, type that shell name before the whole
28 | # command line, like:
29 | #
30 | # ksh Gradle
31 | #
32 | # Busybox and similar reduced shells will NOT work, because this script
33 | # requires all of these POSIX shell features:
34 | # * functions;
35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»;
37 | # * compound commands having a testable exit status, especially «case»;
38 | # * various built-in commands including «command», «set», and «ulimit».
39 | #
40 | # Important for patching:
41 | #
42 | # (2) This script targets any POSIX shell, so it avoids extensions provided
43 | # by Bash, Ksh, etc; in particular arrays are avoided.
44 | #
45 | # The "traditional" practice of packing multiple parameters into a
46 | # space-separated string is a well documented source of bugs and security
47 | # problems, so this is (mostly) avoided, by progressively accumulating
48 | # options in "$@", and eventually passing that to Java.
49 | #
50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
52 | # see the in-line comments for details.
53 | #
54 | # There are tweaks for specific operating systems such as AIX, CygWin,
55 | # Darwin, MinGW, and NonStop.
56 | #
57 | # (3) This script is generated from the Groovy template
58 | # https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
59 | # within the Gradle project.
60 | #
61 | # You can find Gradle at https://github.com/gradle/gradle/.
62 | #
63 | ##############################################################################
64 |
65 | # Attempt to set APP_HOME
66 |
67 | # Resolve links: $0 may be a link
68 | app_path=$0
69 |
70 | # Need this for daisy-chained symlinks.
71 | while
72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
73 | [ -h "$app_path" ]
74 | do
75 | ls=$( ls -ld "$app_path" )
76 | link=${ls#*' -> '}
77 | case $link in #(
78 | /*) app_path=$link ;; #(
79 | *) app_path=$APP_HOME$link ;;
80 | esac
81 | done
82 |
83 | # This is normally unused
84 | # shellcheck disable=SC2034
85 | APP_BASE_NAME=${0##*/}
86 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
87 | APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
88 |
89 | # Use the maximum available, or set MAX_FD != -1 to use that value.
90 | MAX_FD=maximum
91 |
92 | warn () {
93 | echo "$*"
94 | } >&2
95 |
96 | die () {
97 | echo
98 | echo "$*"
99 | echo
100 | exit 1
101 | } >&2
102 |
103 | # OS specific support (must be 'true' or 'false').
104 | cygwin=false
105 | msys=false
106 | darwin=false
107 | nonstop=false
108 | case "$( uname )" in #(
109 | CYGWIN* ) cygwin=true ;; #(
110 | Darwin* ) darwin=true ;; #(
111 | MSYS* | MINGW* ) msys=true ;; #(
112 | NONSTOP* ) nonstop=true ;;
113 | esac
114 |
115 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
116 |
117 |
118 | # Determine the Java command to use to start the JVM.
119 | if [ -n "$JAVA_HOME" ] ; then
120 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
121 | # IBM's JDK on AIX uses strange locations for the executables
122 | JAVACMD=$JAVA_HOME/jre/sh/java
123 | else
124 | JAVACMD=$JAVA_HOME/bin/java
125 | fi
126 | if [ ! -x "$JAVACMD" ] ; then
127 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
128 |
129 | Please set the JAVA_HOME variable in your environment to match the
130 | location of your Java installation."
131 | fi
132 | else
133 | JAVACMD=java
134 | if ! command -v java >/dev/null 2>&1
135 | then
136 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
137 |
138 | Please set the JAVA_HOME variable in your environment to match the
139 | location of your Java installation."
140 | fi
141 | fi
142 |
143 | # Increase the maximum file descriptors if we can.
144 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
145 | case $MAX_FD in #(
146 | max*)
147 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
148 | # shellcheck disable=SC2039,SC3045
149 | MAX_FD=$( ulimit -H -n ) ||
150 | warn "Could not query maximum file descriptor limit"
151 | esac
152 | case $MAX_FD in #(
153 | '' | soft) :;; #(
154 | *)
155 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
156 | # shellcheck disable=SC2039,SC3045
157 | ulimit -n "$MAX_FD" ||
158 | warn "Could not set maximum file descriptor limit to $MAX_FD"
159 | esac
160 | fi
161 |
162 | # Collect all arguments for the java command, stacking in reverse order:
163 | # * args from the command line
164 | # * the main class name
165 | # * -classpath
166 | # * -D...appname settings
167 | # * --module-path (only if needed)
168 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
169 |
170 | # For Cygwin or MSYS, switch paths to Windows format before running java
171 | if "$cygwin" || "$msys" ; then
172 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
173 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
174 |
175 | JAVACMD=$( cygpath --unix "$JAVACMD" )
176 |
177 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
178 | for arg do
179 | if
180 | case $arg in #(
181 | -*) false ;; # don't mess with options #(
182 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
183 | [ -e "$t" ] ;; #(
184 | *) false ;;
185 | esac
186 | then
187 | arg=$( cygpath --path --ignore --mixed "$arg" )
188 | fi
189 | # Roll the args list around exactly as many times as the number of
190 | # args, so each arg winds up back in the position where it started, but
191 | # possibly modified.
192 | #
193 | # NB: a `for` loop captures its iteration list before it begins, so
194 | # changing the positional parameters here affects neither the number of
195 | # iterations, nor the values presented in `arg`.
196 | shift # remove old arg
197 | set -- "$@" "$arg" # push replacement arg
198 | done
199 | fi
200 |
201 |
202 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
203 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
204 |
205 | # Collect all arguments for the java command:
206 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
207 | # and any embedded shellness will be escaped.
208 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
209 | # treated as '${Hostname}' itself on the command line.
210 |
211 | set -- \
212 | "-Dorg.gradle.appname=$APP_BASE_NAME" \
213 | -classpath "$CLASSPATH" \
214 | org.gradle.wrapper.GradleWrapperMain \
215 | "$@"
216 |
217 | # Stop when "xargs" is not available.
218 | if ! command -v xargs >/dev/null 2>&1
219 | then
220 | die "xargs is not available"
221 | fi
222 |
223 | # Use "xargs" to parse quoted args.
224 | #
225 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed.
226 | #
227 | # In Bash we could simply go:
228 | #
229 | # readarray ARGS < <( xargs -n1 <<<"$var" ) &&
230 | # set -- "${ARGS[@]}" "$@"
231 | #
232 | # but POSIX shell has neither arrays nor command substitution, so instead we
233 | # post-process each arg (as a line of input to sed) to backslash-escape any
234 | # character that might be a shell metacharacter, then use eval to reverse
235 | # that process (while maintaining the separation between arguments), and wrap
236 | # the whole thing up as a single "set" statement.
237 | #
238 | # This will of course break if any of these variables contains a newline or
239 | # an unmatched quote.
240 | #
241 |
242 | eval "set -- $(
243 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
244 | xargs -n1 |
245 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
246 | tr '\n' ' '
247 | )" '"$@"'
248 |
249 | exec "$JAVACMD" "$@"
250 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/library/src/main/java/com/fraggjkee/smsconfirmationview/SmsConfirmationView.kt:
--------------------------------------------------------------------------------
1 | package com.fraggjkee.smsconfirmationview
2 |
3 | import android.content.BroadcastReceiver
4 | import android.content.Context
5 | import android.content.Intent
6 | import android.content.IntentFilter
7 | import android.os.Parcel
8 | import android.os.Parcelable
9 | import android.text.InputType
10 | import android.util.AttributeSet
11 | import android.view.ActionMode
12 | import android.view.KeyEvent
13 | import android.view.ViewGroup
14 | import android.view.inputmethod.BaseInputConnection
15 | import android.view.inputmethod.EditorInfo
16 | import android.view.inputmethod.InputConnection
17 | import android.view.inputmethod.InputConnectionWrapper
18 | import android.widget.LinearLayout
19 | import android.widget.Space
20 | import androidx.activity.result.ActivityResultCallback
21 | import androidx.activity.result.ActivityResultLauncher
22 | import androidx.core.view.children
23 | import androidx.core.view.postDelayed
24 | import androidx.fragment.app.Fragment
25 | import androidx.fragment.app.findFragment
26 | import androidx.lifecycle.Lifecycle
27 | import com.fraggjkee.smsconfirmationview.smsretriever.SmsParser
28 | import com.fraggjkee.smsconfirmationview.smsretriever.SmsRetrieverContract
29 | import com.fraggjkee.smsconfirmationview.smsretriever.SmsRetrieverReceiver
30 | import com.google.android.gms.auth.api.phone.SmsRetriever
31 | import com.google.android.gms.auth.api.phone.SmsRetrieverClient
32 |
33 | class SmsConfirmationView @JvmOverloads constructor(
34 | context: Context,
35 | attrs: AttributeSet? = null,
36 | defStyleAttr: Int = 0
37 | ) : LinearLayout(context, attrs, defStyleAttr) {
38 |
39 | /**
40 | * Getter & setter for the entered code. For setter, only digits are accepted so non-digit
41 | * symbols will be ignored.
42 | */
43 | var enteredCode: String = ""
44 | set(value) {
45 | val digits = value.digits()
46 | require(digits.length <= codeLength) { "enteredCode=$digits is longer than $codeLength" }
47 | field = digits
48 | onChangeListener?.onCodeChange(
49 | code = digits,
50 | isComplete = digits.length == codeLength
51 | )
52 | updateState()
53 | }
54 |
55 | /**
56 | * Change listener for the entered code. Will be called for all possible changes:
57 | * manual typing, pasting, SMS auto-detection, etc.
58 | */
59 | var onChangeListener: OnChangeListener? = null
60 |
61 | internal var style: Style = SmsConfirmationViewStyleUtils.getDefault(context)
62 | set(value) {
63 | if (field == value) return
64 | field = value
65 | removeAllViews()
66 | updateState()
67 | }
68 |
69 | private val smsDetectionMode: SmsDetectionMode get() = style.smsDetectionMode
70 |
71 | private var isReceiverRegistered: Boolean = false
72 | private val smsBroadcastReceiver: BroadcastReceiver = object : SmsRetrieverReceiver() {
73 | override fun onConsentIntentRetrieved(intent: Intent) {
74 | smsRetrieverResultLauncher?.run {
75 | hideKeyboard()
76 | launch(intent)
77 | }
78 | }
79 | }
80 |
81 | private val activityResultCallback = ActivityResultCallback { smsContent ->
82 | val view = this@SmsConfirmationView
83 | smsContent?.takeIf { it.isBlank().not() }
84 | ?.let { sms ->
85 | view.enteredCode = SmsParser.parseOneTimeCode(sms, view.codeLength).orEmpty()
86 | }
87 | }
88 |
89 | private val actionModeCallback: ActionMode.Callback = ActionModeCallback(context) { text ->
90 | enteredCode = text.digits().take(codeLength)
91 | }
92 |
93 | private var smsRetrieverResultLauncher: ActivityResultLauncher? = null
94 |
95 | private val symbolSubviews: Sequence
96 | get() = children.filterIsInstance()
97 |
98 | init {
99 | orientation = HORIZONTAL
100 | isFocusable = true
101 | isFocusableInTouchMode = true
102 |
103 | style =
104 | if (attrs == null) SmsConfirmationViewStyleUtils.getDefault(context)
105 | else SmsConfirmationViewStyleUtils.getFromAttributes(attrs, context)
106 | updateState()
107 |
108 | if (smsDetectionMode != SmsDetectionMode.DISABLED) {
109 | // Registering here results in attaching to a parent Activity. We'll do
110 | // one more attempt from onAttachedToWindow to recheck if actual parent is a
111 | // Fragment.
112 | smsRetrieverResultLauncher = getActivity()
113 | ?.takeIf { it.lifecycle.currentState < Lifecycle.State.STARTED }
114 | ?.registerForActivityResult(SmsRetrieverContract(), activityResultCallback)
115 | }
116 |
117 | setOnClickListener {
118 | if (requestFocus()) {
119 | showKeyboard()
120 | }
121 | }
122 | setOnLongClickListener {
123 | showPopupMenuIfNeeded()
124 | true
125 | }
126 | }
127 |
128 | private fun updateState() {
129 | val codeLengthChanged = codeLength != symbolSubviews.count()
130 | if (codeLengthChanged) {
131 | setupSymbolSubviews()
132 | }
133 |
134 | val viewCode = symbolSubviews.map { it.state.symbol }
135 | .filterNotNull()
136 | .joinToString(separator = "")
137 | val isViewCodeOutdated = enteredCode != viewCode
138 | if (isViewCodeOutdated) {
139 | symbolSubviews.forEachIndexed { index, view ->
140 | view.state = SymbolView.State(
141 | symbol = enteredCode.getOrNull(index),
142 | isActive = (enteredCode.length == index)
143 | )
144 | }
145 | }
146 | }
147 |
148 | private fun setupSymbolSubviews() {
149 | removeAllViews()
150 |
151 | for (i in 0 until codeLength) {
152 | val symbolView = SymbolView(context, style.symbolViewStyle)
153 | symbolView.state = SymbolView.State(isActive = (i == enteredCode.length))
154 | addView(symbolView)
155 |
156 | if (i < codeLength.dec()) {
157 | val space = Space(context).apply {
158 | layoutParams = ViewGroup.LayoutParams(style.symbolsSpacing, 0)
159 | }
160 | addView(space)
161 | }
162 | }
163 | }
164 |
165 | private fun showPopupMenuIfNeeded() {
166 | if (style.isPasteEnabled.not()) return
167 | startActionMode(actionModeCallback, ActionMode.TYPE_FLOATING)
168 | }
169 |
170 | override fun onAttachedToWindow() {
171 | super.onAttachedToWindow()
172 |
173 | setOnKeyListener { _, keyCode, event -> handleKeyEvent(keyCode, event) }
174 | postDelayed(KEYBOARD_AUTO_SHOW_DELAY) {
175 | requestFocus()
176 | showKeyboard()
177 | }
178 |
179 | if (smsDetectionMode == SmsDetectionMode.DISABLED) return
180 | runCatching { findFragment() }
181 | .getOrNull()
182 | ?.takeIf { it.lifecycle.currentState < Lifecycle.State.RESUMED }
183 | ?.let { parentFragment ->
184 | smsRetrieverResultLauncher = parentFragment.registerForActivityResult(
185 | SmsRetrieverContract(),
186 | activityResultCallback
187 | )
188 | }
189 |
190 | if (smsDetectionMode == SmsDetectionMode.AUTO) {
191 | startListeningForIncomingMessagesInternal()
192 | }
193 | }
194 |
195 | private fun handleKeyEvent(keyCode: Int, event: KeyEvent): Boolean = when {
196 | event.action != KeyEvent.ACTION_DOWN -> false
197 | event.isDigitKey() -> {
198 | val enteredSymbol = event.keyCharacterMap.getNumber(keyCode)
199 | appendSymbol(enteredSymbol)
200 | true
201 | }
202 |
203 | event.keyCode == KeyEvent.KEYCODE_DEL -> {
204 | removeLastSymbol()
205 | true
206 | }
207 |
208 | event.keyCode == KeyEvent.KEYCODE_ENTER -> {
209 | hideKeyboard()
210 | true
211 | }
212 |
213 | else -> false
214 | }
215 |
216 | private fun KeyEvent.isDigitKey(): Boolean {
217 | return keyCode in KeyEvent.KEYCODE_0..KeyEvent.KEYCODE_9
218 | }
219 |
220 | private fun appendSymbol(symbol: Char) {
221 | if (enteredCode.length == codeLength) {
222 | return
223 | }
224 |
225 | this.enteredCode = enteredCode + symbol
226 | }
227 |
228 | private fun removeLastSymbol() {
229 | if (enteredCode.isEmpty()) {
230 | return
231 | }
232 |
233 | this.enteredCode = enteredCode.substring(0, enteredCode.length - 1)
234 | }
235 |
236 | override fun onCheckIsTextEditor(): Boolean = true
237 |
238 | override fun onCreateInputConnection(outAttrs: EditorInfo): InputConnection {
239 | with(outAttrs) {
240 | inputType = InputType.TYPE_CLASS_NUMBER
241 | imeOptions = EditorInfo.IME_ACTION_DONE
242 | }
243 | return object : InputConnectionWrapper(BaseInputConnection(this, false), true) {
244 |
245 | override fun deleteSurroundingText(beforeLength: Int, afterLength: Int): Boolean {
246 | return if (beforeLength == 1 && afterLength == 0) {
247 | sendKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL))
248 | && sendKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DEL))
249 | } else super.deleteSurroundingText(beforeLength, afterLength)
250 | }
251 | }
252 | }
253 |
254 | override fun onDetachedFromWindow() {
255 | super.onDetachedFromWindow()
256 | if (isReceiverRegistered) {
257 | context.unregisterReceiver(smsBroadcastReceiver)
258 | }
259 | }
260 |
261 | /**
262 | * Trigger [SmsRetrieverClient.startSmsUserConsent] method which will make the view
263 | * listen for incoming messages for the next 5 minutes.
264 | *
265 | * Can only be used with [SmsDetectionMode.MANUAL]
266 | */
267 | fun startListeningForIncomingMessages() {
268 | if (smsDetectionMode != SmsDetectionMode.MANUAL) {
269 | throw IllegalStateException(
270 | "startListeningForIncomingMessages can only be used with SmsDetectionMode.MANUAL"
271 | )
272 | }
273 | startListeningForIncomingMessagesInternal()
274 | }
275 |
276 | private fun startListeningForIncomingMessagesInternal() {
277 | context.registerReceiver(
278 | smsBroadcastReceiver,
279 | IntentFilter(SmsRetriever.SMS_RETRIEVED_ACTION),
280 | SmsRetriever.SEND_PERMISSION
281 | )
282 |
283 | SmsRetriever.getClient(context).startSmsUserConsent(null)
284 |
285 | isReceiverRegistered = true
286 | }
287 |
288 | override fun onSaveInstanceState(): Parcelable {
289 | val superState: Parcelable? = super.onSaveInstanceState()
290 | return SavedState(superState, enteredCode)
291 | }
292 |
293 | override fun onRestoreInstanceState(state: Parcelable) {
294 | if (state !is SavedState) {
295 | super.onRestoreInstanceState(state)
296 | return
297 | }
298 |
299 | super.onRestoreInstanceState(state.superState)
300 | enteredCode = state.enteredCode
301 | }
302 |
303 | private class SavedState(
304 | superState: Parcelable?,
305 | val enteredCode: String
306 | ) : BaseSavedState(superState) {
307 |
308 | override fun writeToParcel(out: Parcel, flags: Int) {
309 | super.writeToParcel(out, flags)
310 | out.writeString(enteredCode)
311 | }
312 | }
313 |
314 | /**
315 | * Interface definition for a callback invoked when the entered code changes.
316 | */
317 | fun interface OnChangeListener {
318 | /**
319 | * Called when the entered code changes.
320 | * @param code new value of the entered code
321 | * @param isComplete true when the [code]'s length matches [codeLength] and false otherwise
322 | */
323 | fun onCodeChange(code: String, isComplete: Boolean)
324 | }
325 |
326 | internal data class Style(
327 | val codeLength: Int,
328 | val isPasteEnabled: Boolean,
329 | val symbolsSpacing: Int,
330 | val symbolViewStyle: SymbolView.Style,
331 | val smsDetectionMode: SmsDetectionMode = SmsDetectionMode.AUTO
332 | )
333 |
334 | internal enum class SmsDetectionMode {
335 | /**
336 | * Prevent [SmsConfirmationView] from using SMS Consent API, i.e. this option
337 | * simply disables automatic SMS detection.
338 | */
339 | DISABLED,
340 |
341 | /**
342 | * Default option. [SmsConfirmationView] will try to use SMS Consent API to
343 | * detect incoming messages and read confirmation codes from it.
344 | */
345 | AUTO,
346 |
347 | /**
348 | * Like [AUTO] but gives you more control when to actually start listening for
349 | * incoming messages via [startListeningForIncomingMessages]. Can be useful in
350 | * some cases as SMS Consent API cannot be active for more than 5 minutes.
351 | */
352 | MANUAL
353 | }
354 |
355 | companion object {
356 | internal const val DEFAULT_CODE_LENGTH = 4
357 | private const val KEYBOARD_AUTO_SHOW_DELAY = 500L
358 | }
359 | }
360 |
--------------------------------------------------------------------------------