native android not connecting to socket.io - android

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.

Related

How to fix android run time error in Stripe Terminal discover device code build using kotlin

I am trying to integrate stripe terminal code with my android app build using kotlin, unfortunately I am getting the following run time error which I could not able to fix
java.lang.IllegalStateException: initTerminal must be called before attempting to get the instance
The code I have added is used below
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_pay_screen)
onDiscoverReaders()
}
fun onDiscoverReaders() {
val config = DiscoveryConfiguration(
timeout = 0,
discoveryMethod = DiscoveryMethod.LOCAL_MOBILE,
isSimulated = false,
location = "xxxxxxxxxxxxxxx"
)
// Save this cancelable to an instance variable
discoveryCancelable = Terminal.getInstance().discoverReaders(config,
discoveryListener = object : DiscoveryListener {
override fun onUpdateDiscoveredReaders(readers: List<Reader>) {
}
}
, object : Callback {
override fun onSuccess() {
println("Finished discovering readers")
}
override fun onFailure(e: TerminalException) {
e.printStackTrace()
}
})
}
I have added this to one of my activity and my intention is to check if my phone is supporting stripe tap on mobile
I guess the issue could be calling onDiscoverReaders() from a wrong place, someone please help me to fix this issue
Thanks in advance
In stripe docs you can check
// Create your listener object. Override any methods that you want to be notified about
val listener = object : TerminalListener {
}
// Choose the level of messages that should be logged to your console
val logLevel = LogLevel.VERBOSE
// Create your token provider.
val tokenProvider = TokenProvider()
// Pass in the current application context, your desired logging level, your token provider, and the listener you created
if (!Terminal.isInitialized()) {
Terminal.initTerminal(applicationContext, logLevel, tokenProvider, listener)
}
// Since the Terminal is a singleton, you can call getInstance whenever you need it
Terminal.getInstance()
might be you missed to initialise terminal before getting Instance so try add above code before onDiscoverReaders()
The error speaks for itself - first you need to initialize the api terminal, and then call the terminal instance.
Based on the documentation, we follow the following steps to get started with the api terminal:
Initialize the terminal application in the application class of the
application
class App : Application() {
override fun onCreate() {
super.onCreate()
TerminalApplicationDelegate.onCreate(this)
}
}
We request the necessary permissions for correct work with the
terminal search (bluetooth, geolocation), if everything is provided,
we call the init terminal with parameters like that:
Terminal.initTerminal(
context = context,
logLevel = LogLevel.VERBOSE,
tokenProvider = TokenProvider(),
listener = object : TerminalListener {
override fun onUnexpectedReaderDisconnect(reader: Reader) {
Log.d("log", "onUnexpectedReaderDisconnect")
}
override fun onConnectionStatusChange(status: ConnectionStatus) {
super.onConnectionStatusChange(status)
Log.d("log", "onConnectionStatusChange")
}
override fun onPaymentStatusChange(status: PaymentStatus) {
super.onPaymentStatusChange(status)
Log.d("log", "onPaymentStatusChange")
}
}
)
After this initialization, you can call the terminal instance and
work with it.

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.

How to implement the checking of internet Android using RxJava/Rx Android Kotlin?

The answer for checking internet was posted back in 2014 in this post: https://stackoverflow.com/a/27312494/12359431
However, in one of the answer, there is this piece of code
fun hasInternetConnection(): Single<Boolean> {
return Single.fromCallable {
try {
// Connect to Google DNS to check for connection
val timeoutMs = 1500
val socket = Socket()
val socketAddress = InetSocketAddress("8.8.8.8", 53)
socket.connect(socketAddress, timeoutMs)
socket.close()
true
} catch (e: IOException) {
false
}
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
}
I have tried it by implementing the code above to my code at the bottom. However, it just crashes and I could not get any finding of the error as to why the app crash.
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
/* Initialise Azure Service Adapter */
AzureServiceAdapter.Initialize(this)
hasInternetConnection().subscribe{hasInternet->
/*Call database and check phone number*/
Log.i("Logger", "Connected")}
/* Authentication */
authUser()
}
}
This is my implementations
implementation 'io.reactivex.rxjava3:rxandroid:3.0.0'
implementation 'io.reactivex.rxjava3:rxjava:3.0.0'
Is there anything I'm lacking or I shouldn't add to my MainActivity File? Or a clue as to why my kotlin app crash ?
That's because you cant call this on main Thread.
Check if you added Internet permission in Manifest.
hasInternetConnection()
.subscribeOn(Schedulars.io())
.observeOn(AndroidSchedulars.mainThread()).subscribe{hasInternet->
/*Call database and check phone number*/
Log.i("Logger", "Connected")}

Auto Read OTP from SMS

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).

Sockets not understood

What I am trying to make is a local chat app (i.e, over local network, i.e. without internet only i.e. hotspot wifi based on android).I studied about sockets and tried to implement using https://github.com/socketio/socket.io-client-java I tried to make use of mainly socket.emit and socket.on. Both of my devices are connected on local network so can I do this
class MainActivity : AppCompatActivity()
{
var TAG = "TCPClient"; //For debugging, always a good idea to have defined
var serverIp = "192.168.0.102";
var startTime = 0L;
var serverPort = 5000;
lateinit var socket:Socket
var onMessageReceived=object:Emitter.Listener
{
override fun call(vararg args: Any?)
{
runOnUiThread {
editText2.setText(args[0].toString())
Toast.makeText(this#MainActivity,"called",Toast.LENGTH_SHORT).show()
}
}
}
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var SOCKET_URL="http://192.168.0.102"
socket= IO.socket(SOCKET_URL)
button.setOnClickListener {
socket.emit("messageSent",editText.text.toString())
Toast.makeText(this#MainActivity,"button",Toast.LENGTH_SHORT).show()
}
socket.on("messageSent",onMessageReceived)
socket.connect()
}
override fun onDestroy()
{
socket.disconnect()
super.onDestroy()
}
}
What I was trying whatever is the text written in editext1(in one phone with ip 192.68.0.102) is displayed in edittex2 (of both devices (one with ip 192.168.0.102 and the other devices on local network(192.168.0.100) since I ran the same app on both devices)) when button is pressed.What I am doing wrong? I would have made this app by hosting rest service on one of the devices and accessing it from all the connected devices in the network but the main problem I was facing is that if I do so I would have to request the rest api again and again in a loop in a thread to check for a new message.
Don't all the connected devices listen when we use socket.on?

Categories

Resources