按照《Android编程权威指南第四版》中的教程,有如下代码:
suspectButton.apply {
val pickContactIntent = Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI)
setOnClickListener {
startActivityForResult(pickContactIntent, REQUEST_CONTACT)
}
val packageManager: PackageManager = requireActivity().packageManager
val resolvedActivity: ResolveInfo? = packageManager.resolveActivity(pickContactIntent, PackageManager.MATCH_DEFAULT_ONLY)
if(resolvedActivity == null) {
isEnabled = false
}
}
目前,如果去掉对resolvedActivity
的检查,会正常弹出联系人APP,且可以正常获取选择的联系人名字。
但是检查代码返回的一直是null。
编译环境:
- compileSdk 32
- minSdk 21
- targetSdk 32
- 依赖:
implementation 'androidx.core:core-ktx:1.7.0'
implementation 'androidx.appcompat:appcompat:1.4.1'
implementation 'com.google.android.material:material:1.6.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
implementation 'androidx.lifecycle:lifecycle-extensions:2.1.0'
implementation 'androidx.recyclerview:recyclerview:1.2.1'
implementation 'androidx.room:room-runtime:2.4.2'
kapt 'androidx.room:room-compiler:2.4.2'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
运行环境:
- 模拟器API28,正常运行且检查代码没有返回null。
- Android11真机(realmex7),检查代码返回null导致按钮被禁用。
在bnr上找到答案了: