Skip to content

Commit a673cbb

Browse files
Prevent crash of telephoy listener method for Java Phone Call Detection
1 parent db8c5e6 commit a673cbb

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

Phone-Call-Detection-Java/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ This is the code responsible for listening for the call status:
1717

1818
```java
1919
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
20+
//Phone state permissions are required from Api 31. Add check of permission to avoid crash.
2021
telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
2122

2223
//...

Phone-Call-Detection-Java/app/src/main/java/com/tokbox/sample/phonecalldetection/MainActivity.java

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,8 +71,27 @@ private void startVideoPublish(Session session) {
7171
session.publish(publisher);
7272
}
7373

74+
private boolean hasPhoneStatePermission() {
75+
if (Build.VERSION.SDK_INT >= 31) {
76+
if (context.checkSelfPermission(Manifest.permission.READ_PHONE_STATE)
77+
!= PackageManager.PERMISSION_GRANTED) {
78+
log.e("Some features may not be available unless the phone permissions has been granted explicitly " +
79+
"in the App settings.");
80+
return false;
81+
}
82+
}
83+
return true;
84+
}
85+
7486
private void registerPhoneListener() {
7587
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
88+
89+
if (!hasPhoneStatePermission()) {
90+
log.d("No Phone State permissions. Register phoneStateListener cannot " +
91+
"be completed.");
92+
return;
93+
}
94+
7695
telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
7796
}
7897

0 commit comments

Comments
 (0)