Telephonymanager.EXTRA_INCOMING_NUMBER is deprecated in API level 29

前端 未结 2 526
醉酒成梦
醉酒成梦 2021-01-25 19:06

I am in situation where I need to identify incoming call phone number in Android but when using TelephonyManager.EXTRA_INCOMING_NUMBER android studio wa

2条回答
  •  孤独总比滥情好
    2021-01-25 20:02

    As @Saurabh said, the new way to screen calls is through the CallScreeningService. However, for the service to work on Android Q and up, the user needs to set your app as the default caller ID & spam app (which is done by using the new RoleManager class)

    1. Register your screening service:

       
           
               
           
       
      
    2. Create you service class:

       @RequiresApi(api = Build.VERSION_CODES.N)
       class ScreeningService : CallScreeningService() {
      
           override fun onScreenCall(details: Details) {
               //code here
           }
      
       }
      
    3. Request the screening role from the user in your main activity (or where ever you see as fit):

       @RequiresApi(Build.VERSION_CODES.Q)
       private fun requestScreeningRole(){
           val roleManager = getSystemService(Context.ROLE_SERVICE) as RoleManager
           val isHeld = roleManager.isRoleHeld(RoleManager.ROLE_CALL_SCREENING)
           if(!isHeld){
               //ask the user to set your app as the default screening app
               val intent = roleManager.createRequestRoleIntent(RoleManager.ROLE_CALL_SCREENING)
               startActivityForResult(intent, 123)
           } else {
               //you are already the default screening app!
           }
       }
      
    4. Catch the user's response:

       override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
               super.onActivityResult(requestCode, resultCode, data)
               when (requestCode) {
                   123 -> {
                       if (resultCode == Activity.RESULT_OK) {
                           //The user set you as the default screening app!
                       } else {
                           //the user didn't set you as the default screening app...
                       }
                   }
                   else -> {}
               }
           }
      

    Apologies for using a hard coded request code >.<

提交回复
热议问题