Thu. Nov 14th, 2024

To get the IMEI programmatically when a button is clicked and display it in a TextView, follow these steps. Remember that accessing the IMEI is restricted on Android 10 (API level 29) and above, so you’ll need a fallback approach.

Here is a complete example:

XML Layout (activity_main.xml)

Define a Button and a TextView:

<?xml version="1.0" encoding="utf-8"?>
<!-- res/layout/activity_main.xml -->
<layout>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">

<Button
android:id="@+id/myButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me" />

<TextView
android:id="@+id/myTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textSize="18sp"
android:paddingTop="20dp" />

</LinearLayout>
</layout>

MainActivity.kt

package com.androindian.imeiex

// MainActivity.kt
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.telephony.TelephonyManager
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import com.androindian.imeiex.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {


var binding: ActivityMainBinding?=null

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding= DataBindingUtil.setContentView(this,R.layout.activity_main)



binding?.myButton?.setOnClickListener {
// Check permission and get IMEI
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
displayIMEI()
} else {
// Request permission if not granted
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_PHONE_STATE), 1)
}
}
}

private fun displayIMEI() {
val telephonyManager = getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
val imei: String? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
// Fallback for Android 10 and above (use ANDROID_ID)
Settings.Secure.getString(contentResolver, Settings.Secure.ANDROID_ID)
} else {
// Get IMEI for Android 9 and below
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
telephonyManager.imei
} else {
TODO("VERSION.SDK_INT < O")
}
}

binding?.myTextView?.text = imei ?: "Unable to retrieve IMEI"
}

override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == 1 && grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
displayIMEI()
} else {
binding?.myTextView?.text = "Permission denied"
}
}
}

build.gradle

plugins {
alias(libs.plugins.android.application)
alias(libs.plugins.jetbrains.kotlin.android)
}

android {
namespace = "com.androindian.imeiex"
compileSdk = 35

defaultConfig {
applicationId = "com.androindian.imeiex"
minSdk = 24
targetSdk = 34
versionCode = 1
versionName = "1.0"

testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = "1.8"
}
dataBinding{
enable=true
}
}

dependencies {

implementation(libs.androidx.core.ktx)
implementation(libs.androidx.appcompat)
implementation(libs.material)
implementation(libs.androidx.activity)
implementation(libs.androidx.constraintlayout)
testImplementation(libs.junit)
androidTestImplementation(libs.androidx.junit)
androidTestImplementation(libs.androidx.espresso.core)
}

xplanation

  1. Button Click: When the “Get IMEI” button is clicked, it checks if READ_PHONE_STATE permission is granted.
  2. Permission Request: If the permission is not granted, it requests it from the user.
  3. Get IMEI:
    • For Android 10+ANDROID_ID is used as a fallback since IMEI is restricted.
    • For Android 9 and belowtelephonyManager.imei retrieves the actual IMEI.
  4. Display IMEI: The retrieved IMEI or a fallback identifier is displayed in imeiTextView.

This setup will display the IMEI or device ID in the TextView when the button is clicked. Make sure to test on a device that can provide a proper IMEI if required.

By Rajashekar

I’m (Rajashekar) a core Android developer with complimenting skills as a web developer from India. I cherish taking up complex problems and turning them into beautiful interfaces. My love for decrypting the logic and structure of coding keeps me pushing towards writing elegant and proficient code, whether it is Android, PHP, Flutter or any other platforms. You would find me involved in cuisines, reading, travelling during my leisure hours.

Leave a Reply

Your email address will not be published. Required fields are marked *