1/* 2 * Copyright 2018 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package androidx.media; 18 19import android.media.AudioAttributes; 20import android.util.Log; 21 22import androidx.annotation.NonNull; 23import androidx.annotation.RequiresApi; 24 25import java.lang.reflect.InvocationTargetException; 26import java.lang.reflect.Method; 27 28@RequiresApi(21) 29class AudioAttributesCompatApi21 { 30 private static final String TAG = "AudioAttributesCompat"; 31 32 // used to introspect AudioAttributes @hidden API 33 // I'm sorry, CheckStyle, but this is much more readable 34 private static Method sAudioAttributesToLegacyStreamType; 35 36 public static int toLegacyStreamType(Wrapper aaWrap) { 37 final AudioAttributes aaObject = aaWrap.unwrap(); 38 try { 39 if (sAudioAttributesToLegacyStreamType == null) { 40 sAudioAttributesToLegacyStreamType = AudioAttributes.class.getMethod( 41 "toLegacyStreamType", AudioAttributes.class); 42 } 43 Object result = sAudioAttributesToLegacyStreamType.invoke( 44 null, aaObject); 45 return (Integer) result; 46 } catch (NoSuchMethodException | InvocationTargetException 47 | IllegalAccessException | ClassCastException e) { 48 Log.w(TAG, "getLegacyStreamType() failed on API21+", e); 49 return -1; // AudioSystem.STREAM_DEFAULT 50 } 51 } 52 53 static final class Wrapper { 54 private AudioAttributes mWrapped; 55 private Wrapper(AudioAttributes obj) { 56 mWrapped = obj; 57 } 58 public static Wrapper wrap(@NonNull AudioAttributes obj) { 59 if (obj == null) { 60 throw new IllegalArgumentException("AudioAttributesApi21.Wrapper cannot wrap null"); 61 } 62 return new Wrapper(obj); 63 } 64 public AudioAttributes unwrap() { 65 return mWrapped; 66 } 67 } 68 69 private AudioAttributesCompatApi21() { 70 } 71} 72