1 /* 2 * Copyright (C) 2021 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 17 package com.google.uwb.support.base; 18 19 import android.os.Build.VERSION_CODES; 20 import android.os.Parcel; 21 import android.os.PersistableBundle; 22 23 import androidx.annotation.Nullable; 24 import androidx.annotation.RequiresApi; 25 26 import java.util.Arrays; 27 28 /** Provides common parameter operations. */ 29 @RequiresApi(VERSION_CODES.LOLLIPOP) 30 public abstract class Params { 31 private static final String KEY_BUNDLE_VERSION = "bundle_version"; 32 protected static final int BUNDLE_VERSION_UNKNOWN = -1; 33 34 protected static final String KEY_PROTOCOL_NAME = "protocol_name"; 35 protected static final String PROTOCOL_NAME_UNKNOWN = "unknown"; 36 toBundle()37 public PersistableBundle toBundle() { 38 PersistableBundle bundle = new PersistableBundle(); 39 bundle.putInt(KEY_BUNDLE_VERSION, getBundleVersion()); 40 bundle.putString(KEY_PROTOCOL_NAME, getProtocolName()); 41 return bundle; 42 } 43 toBytes()44 private byte[] toBytes() { 45 Parcel parcel = Parcel.obtain(); 46 toBundle().writeToParcel(parcel, 0); 47 byte[] bytes = parcel.marshall(); 48 parcel.recycle(); 49 return bytes; 50 } 51 getProtocolName()52 public abstract String getProtocolName(); 53 getBundleVersion()54 protected abstract int getBundleVersion(); 55 getBundleVersion(PersistableBundle bundle)56 public static int getBundleVersion(PersistableBundle bundle) { 57 return bundle.getInt(KEY_BUNDLE_VERSION, BUNDLE_VERSION_UNKNOWN); 58 } 59 isProtocol(PersistableBundle bundle, String protocol)60 public static boolean isProtocol(PersistableBundle bundle, String protocol) { 61 return bundle.getString(KEY_PROTOCOL_NAME, PROTOCOL_NAME_UNKNOWN).equals(protocol); 62 } 63 64 @Override hashCode()65 public int hashCode() { 66 return Arrays.hashCode(toBytes()); 67 } 68 69 @Override equals(@ullable Object obj)70 public boolean equals(@Nullable Object obj) { 71 return obj instanceof Params && Arrays.equals(this.toBytes(), ((Params) obj).toBytes()); 72 } 73 } 74