下面是主要活动:
class MainActivity : AppCompatActivity() {
private val REQUEST_CODE_ENABLE_BT: Int = 1
//bluetooth adapter
private lateinit var bAdapter: BluetoothAdapter
private val bluetoothStatusTv: TextView = findViewById(R.id.bluetoothStatusTv)
private val bluetoothIv: ImageView = findViewById(R.id.bluetoothIm)
private val turnOnBtn: Button = findViewById(R.id.turnOnBtn)
private val turnOffBtn: Button = findViewById(R.id.turnOffBtn)
private val pairedBtn: Button = findViewById(R.id.pairedBtn)
private val pairedTv: TextView = findViewById(R.id.pairedDevices)
@SuppressLint("MissingPermission")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//init bluetooth adapter
val bluetoothManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
bAdapter = bluetoothManager.adapter
// check if bluetooth is available or not
if (bAdapter == null) {
bluetoothStatusTv.text = getString(R.string.bluetooth_is_not_available)
} else {
bluetoothStatusTv.text = getString(R.string.bluetooth_is_available)
}
//set image according to bluetooth
if (bAdapter.isEnabled) {
bluetoothIv.setImageResource(R.drawable.ic_bluetooth_on)
} else {
bluetoothIv.setImageResource(R.drawable.ic_bluetooth_off)
}
//turn on bluetooth
turnOnBtn.setOnClickListener {
if (bAdapter.isEnabled) {
//already enabled
Toast.makeText(this, "ALready on", Toast.LENGTH_LONG).show()
} else {
//turn on bluetooth
val intent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
onActivityResult(REQUEST_CODE_ENABLE_BT, result)
}.launch(intent)
// startActivityForResult( intent, REQUEST_CODE_ENABLE_BT )
}
}
//turn off bluetooth
turnOffBtn.setOnClickListener {
if (!bAdapter.isEnabled) {
//already disabled
Toast.makeText(this, "ALready off", Toast.LENGTH_LONG).show()
} else {
//turn off bluetooth
bluetoothIv.setImageResource(R.drawable.ic_bluetooth_off)
Toast.makeText(this, "Bluetooth disabled", Toast.LENGTH_LONG).show()
}
}
//get list of paired devices
pairedBtn.setOnClickListener {
if (bAdapter.isEnabled) {
pairedTv.text = getString(R.string.paired_devices)
//get list of paired devices
val devices = bAdapter.bondedDevices
for (device in devices) {
val deviceName = device.name
pairedTv.append("\nDevice: $deviceName , $device")
}
} else {
Toast.makeText(this, "Bluetooth is off.", Toast.LENGTH_LONG).show()
}
}
}
private fun onActivityResult(
requestCode: Int,
result: androidx.activity.result.ActivityResult
) {
when (requestCode) {
REQUEST_CODE_ENABLE_BT ->
if (requestCode == Activity.RESULT_OK) {
bluetoothIv.setImageResource(R.drawable.ic_bluetooth_on)
Toast.makeText(this, "Bluetooth is on.", Toast.LENGTH_LONG).show()
} else {
Toast.makeText(this, "Could not on bluetooth.", Toast.LENGTH_LONG).show()
}
}
}
}
应用程序一直崩溃。
应用程序甚至无法打开并崩溃。一开始我使用了startActivityforResult(),但它崩溃了,我想这可能是由于该方法被弃用。但更改后它仍然崩溃,我已经在多个设备上尝试过。
我已在AndroidManifest.xml中包含权限
<!--Permissions -->
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
这是日志
--------- beginning of main
--------- beginning of kernel
--------- beginning of system
2023-06-18 16:42:07.086 276-280 vold vold E Failed to find mounted volume for /dev/null/Android/obb/com.example.rawis/
2023-06-18 16:42:07.144 679-750 StorageManagerService system_process E Failed to fixup app dir for com.example.rawis
android.os.ServiceSpecificException: (code -22)
at android.os.Parcel.createExceptionOrNull(Parcel.java:3025)
at android.os.Parcel.createException(Parcel.java:2995)
at android.os.Parcel.readException(Parcel.java:2978)
at android.os.Parcel.readException(Parcel.java:2920)
at android.os.IVold$Stub$Proxy.fixupAppDir(IVold.java:1804)
at com.android.server.StorageManagerService$StorageManagerInternalImpl.prepareAppDataAfterInstall(StorageManagerService.java:4893)
at com.android.server.pm.AppDataHelper.lambda$prepareAppDataPostCommitLIF$0(AppDataHelper.java:138)
at com.android.server.pm.AppDataHelper.$r8$lambda$3RlktWim_2VfqH429iqZylE48dA(Unknown Source:0)
at com.android.server.pm.AppDataHelper$$ExternalSyntheticLambda0.run(Unknown Source:8)
at java.util.concurrent.CompletableFuture$UniRun.tryFire(CompletableFuture.java:759)
at java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:482)
at java.util.concurrent.CompletableFuture.complete(CompletableFuture.java:2049)
at com.android.server.pm.Installer$Batch.execute(Installer.java:397)
at com.android.server.pm.AppDataHelper.executeBatchLI(AppDataHelper.java:148)
at com.android.server.pm.AppDataHelper.prepareAppDataPostCommitLIF(AppDataHelper.java:143)
at com.android.server.pm.InstallPackageHelper.executePostCommitSteps(InstallPackageHelper.java:2235)
at com.android.server.pm.InstallPackageHelper.installPackagesLI(InstallPackageHelper.java:1007)
at com.android.server.pm.InstallPackageHelper.installPackagesTracedLI(InstallPackageHelper.java:885)
at com.android.server.pm.InstallPackageHelper.processInstallRequests(InstallPackageHelper.java:825)
at com.android.server.pm.InstallParams.lambda$processInstallRequestsAsync$0(InstallParams.java:266)
at com.android.server.pm.InstallParams.$r8$lambda$jbPYK1dOf5qsZh9SAizHgadlSi0(Unknown Source:0)
at com.android.server.pm.InstallParams$$ExternalSyntheticLambda0.run(Unknown Source:6)
at android.os.Handler.handleCallback(Handler.java:942)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.os.HandlerThread.run(HandlerThread.java:67)
at com.android.server.ServiceThread.run(ServiceThread.java:44)
---------------------------- PROCESS STARTED (2543) for package com.example.rawis ----------------------------
2023-06-18 16:42:13.096 2543-2543 Compatibil...geReporter com.example.rawis D Compat change id reported: 171979766; UID 10172; state: ENABLED
2023-06-18 16:42:13.157 2543-2543 ziparchive com.example.rawis W Unable to open '/data/app/~~u_uY-Rj62MLJY7ZrG6YGaQ==/com.example.rawis-9qluLLJK7syZRtQV8aRI9A==/base.dm': No such file or directory
2023-06-18 16:42:13.157 2543-2543 ziparchive com.example.rawis W Unable to open '/data/app/~~u_uY-Rj62MLJY7ZrG6YGaQ==/com.example.rawis-9qluLLJK7syZRtQV8aRI9A==/base.dm': No such file or directory
2023-06-18 16:42:13.561 2543-2543 nativeloader com.example.rawis D Configuring classloader-namespace for other apk /data/app/~~u_uY-Rj62MLJY7ZrG6YGaQ==/com.example.rawis-9qluLLJK7syZRtQV8aRI9A==/base.apk. target_sdk_version=33, uses_libraries=, library_path=/data/app/~~u_uY-Rj62MLJY7ZrG6YGaQ==/com.example.rawis-9qluLLJK7syZRtQV8aRI9A==/lib/x86_64, permitted_path=/data:/mnt/expand:/data/user/0/com.example.rawis
2023-06-18 16:42:13.596 2543-2543 GraphicsEnvironment com.example.rawis V ANGLE Developer option for 'com.example.rawis' set to: 'default'
2023-06-18 16:42:13.597 2543-2543 GraphicsEnvironment com.example.rawis V ANGLE GameManagerService for com.example.rawis: false
2023-06-18 16:42:13.598 2543-2543 GraphicsEnvironment com.example.rawis V Neither updatable production driver nor prerelease driver is supported.
2023-06-18 16:42:13.614 2543-2543 NetworkSecurityConfig com.example.rawis D No Network Security Config specified, using platform default
2023-06-18 16:42:13.617 2543-2543 NetworkSecurityConfig com.example.rawis D No Network Security Config specified, using platform default
2023-06-18 16:42:13.773 2543-2752 libEGL com.example.rawis D loaded /vendor/lib64/egl/libEGL_emulation.so
2023-06-18 16:42:13.779 2543-2752 libEGL com.example.rawis D loaded /vendor/lib64/egl/libGLESv1_CM_emulation.so
2023-06-18 16:42:13.791 2543-2752 libEGL com.example.rawis D loaded /vendor/lib64/egl/libGLESv2_emulation.so
2023-06-18 16:42:13.906 2543-2543 AndroidRuntime com.example.rawis D Shutting down VM
--------- beginning of crash
2023-06-18 16:42:13.921 2543-2543 AndroidRuntime com.example.rawis E FATAL EXCEPTION: main
Process: com.example.rawis, PID: 2543
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.rawis/com.example.rawis.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3551)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3782)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:101)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2307)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7872)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:202)
at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:174)
at android.content.Context.obtainStyledAttributes(Context.java:861)
at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:848)
at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:815)
at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:640)
at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:259)
at com.example.rawis.MainActivity.<init>(MainActivity.kt:27)
at java.lang.Class.newInstance(Native Method)
at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95)
at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:45)
at android.app.Instrumentation.newActivity(Instrumentation.java:1339)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3538)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3782)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:101)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2307)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7872)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936)
2023-06-18 16:42:14.736 2543-2543 Process com.example.rawis I Sending signal. PID: 2543 SIG: 9
---------------------------- PROCESS ENDED (2543) for package com.example.rawis ----------------------------
2023-06-18 16:42:28.988 679-747 VerityUtils system_process E Failed to measure fs-verity, errno 1: /data/app/~~u_uY-Rj62MLJY7ZrG6YGaQ==/com.example.rawis-9qluLLJK7syZRtQV8aRI9A==/base.apk
2023-06-18 16:42:32.011 679-747 VerityUtils system_process E Failed to measure fs-verity, errno 1: /data/app/~~u_uY-Rj62MLJY7ZrG6YGaQ==/com.example.rawis-9qluLLJK7syZRtQV8aRI9A==/base.apk
2条答案
按热度按时间slsn1g291#
有几点可以改进,但应用程序崩溃主要是因为视图在您定义的位置初始化。您应该在setContentView之后的onCreate方法中使用findViewById。
您还应该检查logcat窗口中的错误日志,以找到问题所在。https://developer.android.com/studio/debug/logcat
xxhby3vn2#
错误的原因是你试图在视图被创建之前获取它们的引用。您以以下方式声明了属性:
这意味着它在
MainActivity
类构造函数中调用,这还为时过早。视图通常通过setContentView
方法调用在onCreate
中创建。因此,您可以使用以下选项之一:首先-稍后获得参考。
第二,使用属性而不存储值。这样,每次调用都会触发
findViewById
,所以如果您多次调用它,它会变慢。