Auto Read OTP from SMS - android

I am trying to Read Sms by using this method. But my application is not reading Message.
The Code i have tried yet.
Permission :
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" />
Activity (Main Code) :
class OtpActivity : AppCompatActivity(), View.OnClickListener {
private var smsVerifyCatcher: SmsVerifyCatcher? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_otp)
smsVerifyCatcher = SmsVerifyCatcher(this, OnSmsCatchListener { message ->
val code = parseCode(message)//Parse verification code
Log.e("Code", code)
//then you can send verification code to server
})
smsVerifyCatcher!!.setPhoneNumberFilter("0902249") // I passed 10 digit number here
smsVerifyCatcher!!.setFilter("Ashish") // For extra i added Filter for name
}
private fun parseCode(message: String): String {
val p = Pattern.compile("\\b\\d{4}\\b")
val m = p.matcher(message)
var code = ""
while (m.find()) {
code = m.group(0)
}
return code
}
override fun onStart() {
super.onStart()
smsVerifyCatcher!!.onStart()
}
override fun onStop() {
super.onStop()
smsVerifyCatcher!!.onStop()
}
}

It's not a good idea because of this Reminder SMS/Call Log Policy Changes.
The recomended way is using SMS Retriever API from Google Play Services. See the Automatic SMS Verification with the SMS Retriever API.
Notice though that your server needs to send the messages following a few rules (message starts with "<#>", includes the OTP plus additional information and ends up with a hash identifying your app).

Related

Android 11 - CallRedirectionService not getting triggered

We need to invoke a service when an outgoing call is placed so that we can use the target number to show certain additional information. As per Android documentation, CallRedirectionService should be used. However, after declaring a custom service as depicted in documentation, we find that the custom service is not getting triggered. Please let us know what we are doing wrong. Appreciate your help.
I referred to this link as well but not clear on the answer. There is a mention to role acquisition but I did not find that in Android documentation. Please direct me to the relevant page if available.
CallRedirectionService Implementation not working
Manifest.xml
<service android:name="<mypackage>.CustomCallService"
android:permission="android.permission.BIND_CALL_REDIRECTION_SERVICE">
<intent-filter>
<action android:name="android.telecom.CallRedirectionService"/>
</intent-filter>
</service>
Custom service code
#Override
public void onPlaceCall(#NonNull Uri handle, #NonNull PhoneAccountHandle initialPhoneAccount, boolean allowInteractiveResponse) {
System.out.println("Outgoing:" + initialPhoneAccount + ":" + handle); //Call does not reach here
placeCallUnmodified();
}
In Kotlin:
Your implementation of the CallRedirectionService seems correct. I understand that the only step missing is the role request and acquisition.
You can prompt the user to give you the CallRedirectionService role by using the RoleManager class.
In this example below, we are requesting this role as soon as the MainActivity is created:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
if (!isRedirection())
roleAcquire(RoleManager.ROLE_CALL_REDIRECTION)
}
}
The following functions shall be used:
private fun isRedirection(): Boolean {
return isRoleHeldByApp(RoleManager.ROLE_CALL_REDIRECTION)
}
private fun isRoleHeldByApp(roleName: String): Boolean {
val roleManager: RoleManager? = getSystemService(RoleManager::class.java)
return roleManager!!.isRoleHeld(roleName)
}
private fun roleAcquire(roleName: String) {
val roleManager: RoleManager?
if (roleAvailable(roleName)) {
roleManager = getSystemService(RoleManager::class.java)
val intent = roleManager.createRequestRoleIntent(roleName)
startActivityForResult(intent, 1)
} else {
Toast.makeText(
this,
"Redirection call with role in not available",
Toast.LENGTH_SHORT
).show()
}
}
private fun roleAvailable(roleName: String): Boolean {
val roleManager: RoleManager? = getSystemService(RoleManager::class.java)
return roleManager!!.isRoleAvailable(roleName)
}

Callbacks not working for TikTok Login kit on Android

I have been following the documentation for integrating TikTok's login kit for Android. Here is my complete Activity for receiving the callbacks from the IAPIEventHandler interfact provided by the TikTok SDK:
internal class ATikTokAuth : BaseActivity(), IApiEventHandler {
private val clientKey = TIKTOK_CLIENT_KEY
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.a_tik_tok_auth)
val tiktokOpenConfig = TikTokOpenConfig(clientKey)
TikTokOpenApiFactory.init(tiktokOpenConfig)
val tikTokOpenApi = TikTokOpenApiFactory.create(this)
tikTokOpenApi.handleIntent(intent, this)
val request = Authorization.Request()
request.scope = "user.info.basic"
request.state = "starting"
request.callerLocalEntry = "com.package.name.ATikTokAuth"
tikTokOpenApi.authorize(request)
}
override fun onReq(request: BaseReq?) {
Timber.d("onRequest called: ${request?.extras}")
}
override fun onResp(resp: BaseResp?) {
Timber.d("onResponse: isSuccess: ${resp?.isSuccess} If not, error: ${resp?.errorMsg}")
if (resp is Authorization.Response) {
val code = resp.authCode
Timber.d("onResponse authcode: $code ")
requestAccessToken(resp.authCode)
}
}
override fun onErrorIntent(intent: Intent?) {
Timber.d("onErrorIntent ${intent?.extras}")
}
}
Running this code creates the webview for the user to select a means to log in to TikTok and connect that their TikTok account to my app, but after authorization the user is returned to this activity without onResp being called. onErrorIntent() is called when the webview is launched, but the intent has no data and thus no information useful for debugging.
Also, Although the documentation initializes TikTokOpenConfig like this:
TikTokOpenConfig tiktokOpenConfig = new TikTokOpenConfig(clientKey);
TikTokOpenApiFactory.init(new TikTokOpenConfig(tiktokOpenConfig));
The TikTokOpenConfig only takes a string argument of clientKey, so I assumed it should be
val tiktokOpenConfig = TikTokOpenConfig(clientKey)
TikTokOpenApiFactory.init(tiktokOpenConfig)
I saw no other way since the code in the documentation wouldn't even compile
TikTok is declared as
implementation 'com.bytedance.ies.ugc.aweme:opensdk-oversea-external:0.2.0.2'
in my manifest. What am I doing wrong?
You should add android:exported="true" in manifest file.
<activity
android:name=".ATikTokAuth"
android:exported="true">
</activity>
I moved the initialization of tikTokOpenConfig
val tiktokOpenConfig = TikTokOpenConfig(clientKey)
TikTokOpenApiFactory.init(tiktokOpenConfig)
into a custom App class.

native android not connecting to socket.io

I am trying to connect my server deployed in heroko. But as you can see in the code below, i can't connect to my server. I tried it in web (with just html,javascript) and i am able to connect.
But in android using kotlin, i can't connect. I tried adding android:usesCleartextTraffic but doesn't work. Did anyone faced this issue ?
class MainActivity : AppCompatActivity() {
private val TAG = "mytag"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val socket = IO.socket("https://nesib-api.herokuapp.com/")
socket.connect()
Log.d(TAG, "socked connected : "+ socket.connected()) // always returns false
socket.on(Socket.EVENT_CONNECT){
Log.d(TAG, "connected ! ") // this method never fires
}
}
}
Write <uses-permission android:name="android.permission.INTERNET" /> in your AndroidManifest.xml.

Google Nearby - Connections API - Discovery not working

so recently my friends and i thought about creating an app that allows somewhat of realtime communication between the connected devices, without the need of a webserver. More explicitily, it should be an app, where a single device (master/host) create a game/session and multiple devices (slaves/clients) can join. after establishing all necessary connections (4-5 clients), the host should be able to broadcast data to the clients. Hence i researched a bit and if i understand it correctly the best guess for android are either the WiFi direct oder the google nearby connections api.
Q1. Is this the most simple approach to the desired goal ? or is this already too deep?
So i played a bit around with the connections api, i made a simple application and just used the code from the Nearby Documentation. Since im new to Kotlin, it could also be a rather simple mistake, however after a 2 hours, i swapped back to java with the same error. when the clients try to discover the host, they triggered their OnFailureListener. I tried to search for a solution online (including SO), but i could not find any useful information.
Im testing the application on a HTC ONE M8 and a Samsung Galaxy S7. To Ensure the Nearby Connection API features should work I also downloaded 2 example apps and those worked just fine. I tried how these handled the usage of the api but could not find the important part.
Q2. Where do i use the API wrong ? Or is it really just a error in the coding ?
MainActivity.kt
private const val TAG = android.R.attr.packageNames.toString() + "/Filter"
class MainActivity : AppCompatActivity() {
private lateinit var connectionClient : ConnectionsClient
private val payloadCallback = object : PayloadCallback() {
override fun onPayloadReceived(p0: String, p1: Payload) {
Toast.makeText(applicationContext, "Payload Received", Toast.LENGTH_SHORT).show()
}
override fun onPayloadTransferUpdate(p0: String, p1: PayloadTransferUpdate) {
Toast.makeText(applicationContext, "Payload Transfer Update", Toast.LENGTH_SHORT).show()
}
}
private val connPoint = object : ConnectionLifecycleCallback() {
override fun onConnectionInitiated(p0: String, p1: ConnectionInfo) {
connectionClient.acceptConnection(p0, payloadCallback)
Log.i(TAG, "OnConnectionInitiated")
}
override fun onConnectionResult(p0: String, p1: ConnectionResolution) {
when(p1.status.statusCode){
ConnectionsStatusCodes.STATUS_OK -> Log.i(TAG, "ConnectionsStatusCodes STATUS_OK")
ConnectionsStatusCodes.STATUS_CONNECTION_REJECTED -> Log.i(TAG, "ConnectionsStatusCodes STATUS_CONNECTION_REJECTED")
ConnectionsStatusCodes.STATUS_ERROR -> Log.i(TAG, "ConnectionsStatusCodes STATUS_ERROR")
else -> Log.i(TAG, "ConnectionsStatusCodes STATUS_UNKNOWN")
}
}
override fun onDisconnected(p0: String) {
Log.i(TAG, "onDisconnected $p0")
}
}
private val endPoint = object : EndpointDiscoveryCallback() {
override fun onEndpointFound(p0: String, p1: DiscoveredEndpointInfo) {
Log.i(TAG, "onEndpointFound ID: $p0 Name: ${p1.endpointName} ")
connectionClient.requestConnection(p1.endpointName, p0, connPoint)
.addOnSuccessListener {
Log.i(TAG, "OnSuccessListener requestConnection")
}
.addOnFailureListener {
Log.i(TAG, "OnFailureListener requestConnection")
}
}
override fun onEndpointLost(p0: String) {
Log.i(TAG, "$p0 disconnected")
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
connectionClient = Nearby.getConnectionsClient(this.applicationContext)
//Toast.makeText(applicationContext, connectionClient.instanceId, Toast.LENGTH_SHORT).show()
setButtonOnClick()
}
override fun onStop() {
connectionClient.stopAllEndpoints()
connectionClient.stopAdvertising()
connectionClient.stopDiscovery()
super.onStop()
}
private fun setButtonOnClick(){
val create = findViewById<Button>(R.id.create_btn)
val join = findViewById<Button>(R.id.join_btn)
create.setOnClickListener{ _ -> CreateGroup()}
join.setOnClickListener{ _ -> JoinGroup()}
Log.i(TAG, "On Click Listener set")
}
private fun CreateGroup(){
Log.i(TAG, "Starting Advertising")
connectionClient
.startAdvertising(android.os.Build.MODEL,
packageName.toString(),
connPoint,
AdvertisingOptions.Builder().apply{
setStrategy(Strategy.P2P_CLUSTER)
}.build())
.addOnSuccessListener {
OnSuccessListener<Void> {
Log.i(TAG, "OnSuccessListener CreateGroup() was triggered")
}
}
.addOnFailureListener {
OnFailureListener {
Log.i(TAG, "OnFailureListener CreateGroup() was triggered")
}
}
}
private fun JoinGroup(){
Log.i(TAG, "Starting Discovering")
connectionClient.startDiscovery(packageName.toString(),
endPoint,
DiscoveryOptions.Builder().apply{
setStrategy(Strategy.P2P_CLUSTER)
}.build())
.addOnSuccessListener {
OnSuccessListener<Void> {
Log.i(TAG, "OnSuccessListener JoinGroup() was triggered")
}
}
.addOnFailureListener {
OnFailureListener {
Log.i(TAG, "OnSuccessListener JoinGroup() was triggered")
}
}
}
}
Android Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.testapplication">
<!-- Required for Nearby Connections -->
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- Optional: only required for FILE payloads -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Okay, after figuring out how to correctly setup the Listeners using Kotlin i found out that i got the exception of a missing permission, 01-20 21:11:14.269 1058-1058/com.example.testapplication I/16843649/Filter: 8034: MISSING_PERMISSION_ACCESS_COARSE_LOCATION, which i thought was strange since its in the manifest. However i went to the normal app settings and turned on the permissions manually, and it works now.

Sending text data from Android to IOS using NFC [duplicate]

This question already has answers here:
NDEF Message with HCE Android
(2 answers)
Closed 4 years ago.
I know that at the moment there is no API in IOS 11 to write data to NFC tags, but it's possible to read data from NFC tags and want to pass text from Android device to iPhone.
I assumed that it's possible to write NdefMessage and it will be received on IOS, but it just doesnt work for me. There is no Intent received when I start NFC scanning on IOS (using NfcActions application).
Source code of my main activity:
class MainActivity : AppCompatActivity() {
var nfc: NfcAdapter? = null
#SuppressLint("SetTextI18n")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
hintLabel.text = "Initializing..."
nfc = NfcAdapter.getDefaultAdapter(this)
if (nfc == null) hintLabel.text = "NFC is not available on this device"
else hintLabel.text = "NFC initialized"
}
override fun onResume() {
super.onResume()
nfc?.enableNFCInForeground(this, javaClass)
}
override fun onPause() {
super.onPause()
nfc?.disableForegroundDispatch(this)
}
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
val pathPrefix = "/testuser:nfctest"
val isSuccess = createNFCMessage(pathPrefix, "Hello World", intent)
if(isSuccess)
hintLabel.text = "Successfully wrote data"
else
hintLabel.text = "Couldnt write any data"
}
fun createNFCMessage(pathPrefix: String, payload: String, intent: Intent?) : Boolean {
val nfcRecord = NdefRecord(NdefRecord.TNF_EXTERNAL_TYPE, pathPrefix.toByteArray(), ByteArray(0), payload.toByteArray())
val nfcMessage = NdefMessage(arrayOf(nfcRecord))
intent?.let {
val tag = it.getParcelableExtra<Tag>(NfcAdapter.EXTRA_TAG)
return writeMessageToTag(nfcMessage, tag)
}
return false
}
fun <T>NfcAdapter.enableNFCInForeground(activity: Activity, classType: Class<T>) {
val pendingIntent = PendingIntent.getActivity(activity, 0,
Intent(activity,classType).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0)
val filters = arrayOf(IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED))
val techList = arrayOf(arrayOf(Ndef::class.java.name), arrayOf(NdefFormatable::class.java.name))
this.enableForegroundDispatch(activity, pendingIntent, filters, techList)
}
private fun writeMessageToTag(nfcMessage: NdefMessage, tag: Tag?): Boolean {
// This functions writes given NdefMessage to the tag, if it's possible
// and returns whether it was successful or not
}
And I also added following permissions and intent filter to main manifest
<uses-permission android:name="android.permission.NFC" />
<uses-feature
android:name="android.hardware.nfc"
android:required="false" />
<application ...>
<activity ...>
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:host="ext"
android:pathPrefix="/testuser:nfctest"
android:scheme="vnd.android.nfc"
android:mimeType="text/plain"/>
</intent-filter>
</activity>
</application>
What am I doing wrong and how to properly pass data from Android device to iPhone using NFC?
Apparently the usual peer-2-peer way to send NDEF messages from one phone to another only works between 2 android devices.
To send a message from Android to iOS you need to use host card emulation.
Basically the Android phone needs to emulate a Tag 4 Type (based on NDEF Forum specification), for the iPhone to read the content.
Hope that gets you on the right track ...
For anyone who stuck on this issue, I have read NFCForum-TS-Type-4-Tag which proposed by #Michael Roland. The whole idea is correct. All you need is to simulate the process SEND and RECEIVED commands to convert the byte array to a NDEF message. I created two repositories, one conclude the whole package about converting string to a NDEF message and the other one is a iOS Reader NDEF TAG to verify whether Android HCE is correct or not.
So Good luck!
Also see the response by Michael Roland to NDEF Message with HCE Android.

Categories

Resources