我的 android 应用程序不断崩溃,尽管在清单中授予了相关权限,但似乎是权限问题
My android app keeps crashing from which seems to be a permission problem despite granting the relevant permission in the Manifest
下面是出现问题的 MainActivity 代码。
class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener,
AdapterView.OnItemSelectedListener {
private var user: FirebaseUser? = null
var activity: MainActivity? = null
private var mUserRef: DatabaseReference? = null
private lateinit var dialog: AlertDialog
lateinit var bottomSheet: BottomSheetLayout
lateinit var cView: View
lateinit var tView: View
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val toolbar: Toolbar = findViewById(R. id.toolbar)
setSupportActionBar(toolbar)
activity = this@MainActivity
user = Firebase.auth.currentUser
dialog = SpotsDialog.Builder().setContext(this).build()
dialog.show()
val network = Network(this)
val imei = network.imei
val imsi = network.imsi
Log.e("deviceInfo", "$imei $imsi")
if (user != null) {
Log.d("UserData", user!!.metadata!!.lastSignInTimestamp.toString())
// User is signed in
user.let {
val db = Firebase.firestore
mUserRef = FirebaseDatabase.getInstance().reference.child("users")
.child(user!!.uid)
val docRef = db.collection("users").document(user!!.uid)
docRef.get()
.addOnSuccessListener { document ->
if (document != null) {
Log.d("MainActivity", "DocumentSnapshot data: ${document.data}")
name.text ="Name: "+ document.data!!["displayName"].toString()
mobile.text = "Phone number: "+ document.data!!["phoneNumber"].toString()
email.text = "Email: "+ document.data!!["email"].toString()
Glide.with(this)
.load(document.data!!["image"].toString())
.into(profile_image)
dialog.dismiss()
when {
document.data!!["clientTypeId"].toString() == "1" -> {
svc.text = "Svc No.: ${document.data!!["militarySvc"].toString()}"
}
document.data!!["clientTypeId"].toString() == "2" -> {
svc.text = "Job ID: ${document.data!!["jobId"].toString()}"
}
document.data!!["clientTypeId"].toString() == "3" -> {
svc.text = "Employee No.: ${document.data!!["employeeNumber"].toString()}"
}
}
} else {
Log.d("MainActivity", "No such document")
}
}
.addOnFailureListener { exception ->
Log.d("MainActivity", "get failed with ", exception)
}
val uid = user!!.uid
}
} else {
startActivity(Intent(this, LoginActivity::class.java))
finish()
}
val toggle = ActionBarDrawerToggle(
this, drawer_layout,
toolbar,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close
)
drawer_layout.addDrawerListener(toggle)
toggle.syncState()
bottomSheet = findViewById<View>(R.id.bottomsheet) as BottomSheetLayout
nav_view.setNavigationItemSelectedListener(this)
requestLoan.setOnClickListener {
startActivity(Intent(this,RequestLoanActivity::class.java))
}
insurance.setOnClickListener {
bottomSheet.showWithSheetView(
LayoutInflater.from(this@MainActivity)
.inflate(R.layout.insurance_sheet, bottomSheet, false)
)
val nextPage = bottomSheet.findViewById<Button>(R.id.next)
nextPage.setOnClickListener {
startActivity(Intent(this, AddInsuranceActivity::class.java))
}
}
buyTokens.setOnClickListener {
val dialog = MaterialDialog(this).customView(R.layout.kplc_token, scrollable = true)
dialog.cornerRadius(16f)
val customView = dialog.getCustomView()
tView = customView
buytoken(customView)
dialog.show()
}
repayLoan.setOnClickListener {
startActivity(Intent(this, RepayLoanActivity::class.java))
}
kopaless.setOnClickListener {
startActivity(Intent(this, KopalessActivity::class.java))
}
buyAirtime.setOnClickListener {
val dialog = MaterialDialog(this).customView(R.layout.airtime_sheet, scrollable = true)
dialog.cornerRadius(16f)
val customView = dialog.getCustomView()
cView = customView
buyairtim(customView)
dialog.show()
}
}
}
由于在
未授予读取 Phone 州权限,我遇到了致命异常
val network = Network(this)
即使在清单中列出了必要的权限之后。请告诉我如何解决这个问题。
04-25 08:26:55.346 E/AndroidRuntime(15754): FATAL EXCEPTION: main
04-25 08:26:55.346 E/AndroidRuntime(15754): FATAL EXCEPTION: main
04-25 08:26:55.346 E/AndroidRuntime(15754): Process: com.lkmicrocredit.app, PID: 15754
04-25 08:26:55.346 E/AndroidRuntime(15754): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.lkmicrocredit.app/com.lkmicrocredit.app.ui.activity.home.MainActivity}: java.lang.RuntimeException: Read Phone State permission not granted!
04-25 08:26:55.346 E/AndroidRuntime(15754): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3792)
04-25 08:26:55.346 E/AndroidRuntime(15754): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3968)
04-25 08:26:55.346 E/AndroidRuntime(15754): at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
04-25 08:26:55.346 E/AndroidRuntime(15754): at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
04-25 08:26:55.346 E/AndroidRuntime(15754): at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
04-25 08:26:55.346 E/AndroidRuntime(15754): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2307)
04-25 08:26:55.346 E/AndroidRuntime(15754): at android.os.Handler.dispatchMessage(Handler.java:106)
04-25 08:26:55.346 E/AndroidRuntime(15754): at android.os.Looper.loop(Looper.java:246)
04-25 08:26:55.346 E/AndroidRuntime(15754): at android.app.ActivityThread.main(ActivityThread.java:8512)
04-25 08:26:55.346 E/AndroidRuntime(15754): at java.lang.reflect.Method.invoke(Native Method)
04-25 08:26:55.346 E/AndroidRuntime(15754): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
04-25 08:26:55.346 E/AndroidRuntime(15754): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)
04-25 08:26:55.346 E/AndroidRuntime(15754): Caused by: java.lang.RuntimeException: Read Phone State permission not granted!
04-25 08:26:55.346 E/AndroidRuntime(15754): at com.an.deviceinfo.device.DeviceInfo.getIMEI(DeviceInfo.java:614)
04-25 08:26:55.346 E/AndroidRuntime(15754): at com.an.deviceinfo.device.model.Network.<init>(Network.java:26)
04-25 08:26:55.346 E/AndroidRuntime(15754): at com.lkmicrocredit.app.ui.activity.home.MainActivity.onCreate(MainActivity.kt:79)
和清单...
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.lkmicrocredit.app">
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"
tools:remove="android:maxSdkVersion"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
</manifest>
像这样的东西应该可以工作:
val requestPermissionLauncher = registerForActivityResult(RequestPermission()) { isGranted: Boolean ->
if (isGranted) {
// Permission granted. App continues with permission
} else {
// Explain why the permission is needed to the user
}
}
when {
ContextCompat.checkSelfPermission(CONTEXT, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED -> {
// Use the permission!
}
shouldShowRequestPermissionRationale(...) -> {
showInContextUI(...)
}
else -> {
requestPermissionLauncher.launch(Manifest.permission.READ_PHONE_STATE)
}
}
这也行。
private val requestPermission =
registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted ->
// Do something if permission granted
if (isGranted) {
Log.i("DEBUG", "permission granted")
} else {
Log.i("DEBUG", "permission denied")
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
requestPermission.launch(Manifest.permission.READ_PHONE_STATE)
}
下面是出现问题的 MainActivity 代码。
class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener,
AdapterView.OnItemSelectedListener {
private var user: FirebaseUser? = null
var activity: MainActivity? = null
private var mUserRef: DatabaseReference? = null
private lateinit var dialog: AlertDialog
lateinit var bottomSheet: BottomSheetLayout
lateinit var cView: View
lateinit var tView: View
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val toolbar: Toolbar = findViewById(R. id.toolbar)
setSupportActionBar(toolbar)
activity = this@MainActivity
user = Firebase.auth.currentUser
dialog = SpotsDialog.Builder().setContext(this).build()
dialog.show()
val network = Network(this)
val imei = network.imei
val imsi = network.imsi
Log.e("deviceInfo", "$imei $imsi")
if (user != null) {
Log.d("UserData", user!!.metadata!!.lastSignInTimestamp.toString())
// User is signed in
user.let {
val db = Firebase.firestore
mUserRef = FirebaseDatabase.getInstance().reference.child("users")
.child(user!!.uid)
val docRef = db.collection("users").document(user!!.uid)
docRef.get()
.addOnSuccessListener { document ->
if (document != null) {
Log.d("MainActivity", "DocumentSnapshot data: ${document.data}")
name.text ="Name: "+ document.data!!["displayName"].toString()
mobile.text = "Phone number: "+ document.data!!["phoneNumber"].toString()
email.text = "Email: "+ document.data!!["email"].toString()
Glide.with(this)
.load(document.data!!["image"].toString())
.into(profile_image)
dialog.dismiss()
when {
document.data!!["clientTypeId"].toString() == "1" -> {
svc.text = "Svc No.: ${document.data!!["militarySvc"].toString()}"
}
document.data!!["clientTypeId"].toString() == "2" -> {
svc.text = "Job ID: ${document.data!!["jobId"].toString()}"
}
document.data!!["clientTypeId"].toString() == "3" -> {
svc.text = "Employee No.: ${document.data!!["employeeNumber"].toString()}"
}
}
} else {
Log.d("MainActivity", "No such document")
}
}
.addOnFailureListener { exception ->
Log.d("MainActivity", "get failed with ", exception)
}
val uid = user!!.uid
}
} else {
startActivity(Intent(this, LoginActivity::class.java))
finish()
}
val toggle = ActionBarDrawerToggle(
this, drawer_layout,
toolbar,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close
)
drawer_layout.addDrawerListener(toggle)
toggle.syncState()
bottomSheet = findViewById<View>(R.id.bottomsheet) as BottomSheetLayout
nav_view.setNavigationItemSelectedListener(this)
requestLoan.setOnClickListener {
startActivity(Intent(this,RequestLoanActivity::class.java))
}
insurance.setOnClickListener {
bottomSheet.showWithSheetView(
LayoutInflater.from(this@MainActivity)
.inflate(R.layout.insurance_sheet, bottomSheet, false)
)
val nextPage = bottomSheet.findViewById<Button>(R.id.next)
nextPage.setOnClickListener {
startActivity(Intent(this, AddInsuranceActivity::class.java))
}
}
buyTokens.setOnClickListener {
val dialog = MaterialDialog(this).customView(R.layout.kplc_token, scrollable = true)
dialog.cornerRadius(16f)
val customView = dialog.getCustomView()
tView = customView
buytoken(customView)
dialog.show()
}
repayLoan.setOnClickListener {
startActivity(Intent(this, RepayLoanActivity::class.java))
}
kopaless.setOnClickListener {
startActivity(Intent(this, KopalessActivity::class.java))
}
buyAirtime.setOnClickListener {
val dialog = MaterialDialog(this).customView(R.layout.airtime_sheet, scrollable = true)
dialog.cornerRadius(16f)
val customView = dialog.getCustomView()
cView = customView
buyairtim(customView)
dialog.show()
}
}
}
由于在
未授予读取 Phone 州权限,我遇到了致命异常val network = Network(this)
即使在清单中列出了必要的权限之后。请告诉我如何解决这个问题。
04-25 08:26:55.346 E/AndroidRuntime(15754): FATAL EXCEPTION: main
04-25 08:26:55.346 E/AndroidRuntime(15754): FATAL EXCEPTION: main
04-25 08:26:55.346 E/AndroidRuntime(15754): Process: com.lkmicrocredit.app, PID: 15754
04-25 08:26:55.346 E/AndroidRuntime(15754): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.lkmicrocredit.app/com.lkmicrocredit.app.ui.activity.home.MainActivity}: java.lang.RuntimeException: Read Phone State permission not granted!
04-25 08:26:55.346 E/AndroidRuntime(15754): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3792)
04-25 08:26:55.346 E/AndroidRuntime(15754): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3968)
04-25 08:26:55.346 E/AndroidRuntime(15754): at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
04-25 08:26:55.346 E/AndroidRuntime(15754): at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
04-25 08:26:55.346 E/AndroidRuntime(15754): at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
04-25 08:26:55.346 E/AndroidRuntime(15754): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2307)
04-25 08:26:55.346 E/AndroidRuntime(15754): at android.os.Handler.dispatchMessage(Handler.java:106)
04-25 08:26:55.346 E/AndroidRuntime(15754): at android.os.Looper.loop(Looper.java:246)
04-25 08:26:55.346 E/AndroidRuntime(15754): at android.app.ActivityThread.main(ActivityThread.java:8512)
04-25 08:26:55.346 E/AndroidRuntime(15754): at java.lang.reflect.Method.invoke(Native Method)
04-25 08:26:55.346 E/AndroidRuntime(15754): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
04-25 08:26:55.346 E/AndroidRuntime(15754): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)
04-25 08:26:55.346 E/AndroidRuntime(15754): Caused by: java.lang.RuntimeException: Read Phone State permission not granted!
04-25 08:26:55.346 E/AndroidRuntime(15754): at com.an.deviceinfo.device.DeviceInfo.getIMEI(DeviceInfo.java:614)
04-25 08:26:55.346 E/AndroidRuntime(15754): at com.an.deviceinfo.device.model.Network.<init>(Network.java:26)
04-25 08:26:55.346 E/AndroidRuntime(15754): at com.lkmicrocredit.app.ui.activity.home.MainActivity.onCreate(MainActivity.kt:79)
和清单...
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.lkmicrocredit.app">
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"
tools:remove="android:maxSdkVersion"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
</manifest>
像这样的东西应该可以工作:
val requestPermissionLauncher = registerForActivityResult(RequestPermission()) { isGranted: Boolean ->
if (isGranted) {
// Permission granted. App continues with permission
} else {
// Explain why the permission is needed to the user
}
}
when {
ContextCompat.checkSelfPermission(CONTEXT, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED -> {
// Use the permission!
}
shouldShowRequestPermissionRationale(...) -> {
showInContextUI(...)
}
else -> {
requestPermissionLauncher.launch(Manifest.permission.READ_PHONE_STATE)
}
}
这也行。
private val requestPermission =
registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted ->
// Do something if permission granted
if (isGranted) {
Log.i("DEBUG", "permission granted")
} else {
Log.i("DEBUG", "permission denied")
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
requestPermission.launch(Manifest.permission.READ_PHONE_STATE)
}