如何在Android中获取设备信息?
在当今世界,有时我们希望访问用户的设备信息以扩展我们的业务,例如电子商务公司可能希望访问用户的手机品牌以提供(更具体地说,针对用户提供高/低价格的项目)推荐。我们可以在 Android 中使用 Build Package 找到设备(硬件和软件)信息。
分步实施
要获取设备信息,请按照以下步骤操作。我们将使用Kotlin语言来实现它。
想要一个更快节奏和更具竞争力的环境来学习 Android 的基础知识吗?
单击此处前往由我们的专家精心策划的指南,旨在让您立即做好行业准备!
第 1 步:创建一个新项目
要在 Android Studio 中创建新项目,请参阅如何在 Android Studio 中创建/启动新项目。请注意,选择Kotlin作为编程语言。
步骤 2:使用 activity_main.xml 文件
导航到app > res > layout > activity_main.xml并将以下代码添加到该文件中。下面是activity_main.xml文件的代码。
XML
Kotlin
import android.annotation.SuppressLint
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val tvDisplay: TextView = findViewById(R.id.tv_displayInfo)
tvDisplay.text = getSystemDetail()
}
@SuppressLint("HardwareIds")
private fun getSystemDetail(): String {
return "Brand: ${Build.BRAND} \n" +
"DeviceID: ${
Settings.Secure.getString(
contentResolver,
Settings.Secure.ANDROID_ID
)
} \n" +
"Model: ${Build.MODEL} \n" +
"ID: ${Build.ID} \n" +
"SDK: ${Build.VERSION.SDK_INT} \n" +
"Manufacture: ${Build.MANUFACTURER} \n" +
"Brand: ${Build.BRAND} \n" +
"User: ${Build.USER} \n" +
"Type: ${Build.TYPE} \n" +
"Base: ${Build.VERSION_CODES.BASE} \n" +
"Incremental: ${Build.VERSION.INCREMENTAL} \n" +
"Board: ${Build.BOARD} \n" +
"Host: ${Build.HOST} \n" +
"FingerPrint: ${Build.FINGERPRINT} \n" +
"Version Code: ${Build.VERSION.RELEASE}"
}
}
第 3 步:使用MainActivity。 Java文件
转到MainActivity.kt文件并参考以下代码。下面是MainActivity.kt文件的代码。代码中添加了注释以更详细地理解代码。
科特林
import android.annotation.SuppressLint
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val tvDisplay: TextView = findViewById(R.id.tv_displayInfo)
tvDisplay.text = getSystemDetail()
}
@SuppressLint("HardwareIds")
private fun getSystemDetail(): String {
return "Brand: ${Build.BRAND} \n" +
"DeviceID: ${
Settings.Secure.getString(
contentResolver,
Settings.Secure.ANDROID_ID
)
} \n" +
"Model: ${Build.MODEL} \n" +
"ID: ${Build.ID} \n" +
"SDK: ${Build.VERSION.SDK_INT} \n" +
"Manufacture: ${Build.MANUFACTURER} \n" +
"Brand: ${Build.BRAND} \n" +
"User: ${Build.USER} \n" +
"Type: ${Build.TYPE} \n" +
"Base: ${Build.VERSION_CODES.BASE} \n" +
"Incremental: ${Build.VERSION.INCREMENTAL} \n" +
"Board: ${Build.BOARD} \n" +
"Host: ${Build.HOST} \n" +
"FingerPrint: ${Build.FINGERPRINT} \n" +
"Version Code: ${Build.VERSION.RELEASE}"
}
}
输出: