How to change vibrate mode to ringer prgrammatically through audio manager

后端 未结 4 989
一生所求
一生所求 2021-01-05 06:27

I am making application where phone mode will changes from silent mode to ringer mode if the user sends an sms with some specific keyword. The application mainly works when

4条回答
  •  一生所求
    2021-01-05 07:31

    To make it work for android devices for and above Marshmallow(API 23)

    1. In AndroidManifest.xml define the ACCESS_NOTIFICATION_POLICY permission

      
      
    2. In your onResume/onCreate function ask for permission if not granted

      @Override
      protected void onResume() {
          super.onResume();
          NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
          //Check if the phone is running Marshmallow or above
          if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.M) {
              //If the permission is not granted, launch an inbuilt activity to grant permission
              if (!nm.isNotificationPolicyAccessGranted()) {
                  startActivity(new Intent(Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS));
              }
          }
      }
      
    3. Finally to change Ringer mode call this method

      public void setRingerMode(Context context,int mode){
              /*
              * mode variable value can be:
              * AudioManager.RINGER_MODE_SILENT
              * AudioManager.RINGER_MODE_NORMAL
              * AudioManager.RINGER_MODE_VIBRATE
              */
              NotificationManager nm = (NotificationManager)context.getSystemService(NOTIFICATION_SERVICE);
              AudioManager audioManager = (AudioManager)context.getSystemService(AUDIO_SERVICE);
              if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M && nm.isNotificationPolicyAccessGranted())
                  audioManager.setRingerMode(mode);
          }
      

提交回复
热议问题