1 /* 2 * Copyright (C) 2020 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 android.os; 18 19 import android.annotation.NonNull; 20 21 import java.time.Duration; 22 23 /** 24 * Parcelable version of {@link Duration} that can be used in binder calls. 25 * 26 * @hide 27 */ 28 public final class ParcelDuration implements Parcelable { 29 30 private final long mSeconds; 31 private final int mNanos; 32 33 /** 34 * Construct a Duration object using the given millisecond value. 35 * 36 * @hide 37 */ ParcelDuration(long ms)38 public ParcelDuration(long ms) { 39 this(Duration.ofMillis(ms)); 40 } 41 42 /** 43 * Wrap a {@link Duration} instance. 44 * 45 * @param duration The {@link Duration} instance to wrap. 46 */ ParcelDuration(@onNull Duration duration)47 public ParcelDuration(@NonNull Duration duration) { 48 mSeconds = duration.getSeconds(); 49 mNanos = duration.getNano(); 50 } 51 ParcelDuration(@onNull Parcel parcel)52 private ParcelDuration(@NonNull Parcel parcel) { 53 mSeconds = parcel.readLong(); 54 mNanos = parcel.readInt(); 55 } 56 57 @Override describeContents()58 public int describeContents() { 59 return 0; 60 } 61 62 @Override writeToParcel(@onNull Parcel parcel, int parcelableFlags)63 public void writeToParcel(@NonNull Parcel parcel, int parcelableFlags) { 64 parcel.writeLong(mSeconds); 65 parcel.writeInt(mNanos); 66 } 67 68 /** 69 * Returns a {@link Duration} instance that's equivalent to this Duration's length. 70 * 71 * @return a {@link Duration} instance of identical length. 72 */ 73 @NonNull getDuration()74 public Duration getDuration() { 75 return Duration.ofSeconds(mSeconds, mNanos); 76 } 77 78 @Override 79 @NonNull toString()80 public String toString() { 81 return getDuration().toString(); 82 } 83 84 /** 85 * Creator for Duration. 86 */ 87 @NonNull 88 public static final Parcelable.Creator<ParcelDuration> CREATOR = 89 new Parcelable.Creator<ParcelDuration>() { 90 91 @Override 92 @NonNull 93 public ParcelDuration createFromParcel(@NonNull Parcel source) { 94 return new ParcelDuration(source); 95 } 96 97 @Override 98 @NonNull 99 public ParcelDuration[] newArray(int size) { 100 return new ParcelDuration[size]; 101 } 102 }; 103 } 104