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.android.server.apphibernation; 18 19 20 import android.annotation.NonNull; 21 import android.annotation.Nullable; 22 import android.util.Slog; 23 import android.util.proto.ProtoInputStream; 24 import android.util.proto.ProtoOutputStream; 25 26 import java.io.IOException; 27 import java.util.ArrayList; 28 import java.util.List; 29 30 /** 31 * Reads and writes protos for {@link UserLevelState} hiberation states. 32 */ 33 final class UserLevelHibernationProto implements ProtoReadWriter<List<UserLevelState>> { 34 private static final String TAG = "UserLevelHibernationProtoReadWriter"; 35 36 @Override writeToProto(@onNull ProtoOutputStream stream, @NonNull List<UserLevelState> data)37 public void writeToProto(@NonNull ProtoOutputStream stream, 38 @NonNull List<UserLevelState> data) { 39 for (int i = 0, size = data.size(); i < size; i++) { 40 long token = stream.start(UserLevelHibernationStatesProto.HIBERNATION_STATE); 41 UserLevelState state = data.get(i); 42 stream.write(UserLevelHibernationStateProto.PACKAGE_NAME, state.packageName); 43 stream.write(UserLevelHibernationStateProto.HIBERNATED, state.hibernated); 44 stream.end(token); 45 } 46 } 47 48 @Override readFromProto(@onNull ProtoInputStream stream)49 public @Nullable List<UserLevelState> readFromProto(@NonNull ProtoInputStream stream) 50 throws IOException { 51 List<UserLevelState> list = new ArrayList<>(); 52 while (stream.nextField() != ProtoInputStream.NO_MORE_FIELDS) { 53 if (stream.getFieldNumber() 54 != (int) UserLevelHibernationStatesProto.HIBERNATION_STATE) { 55 continue; 56 } 57 UserLevelState state = new UserLevelState(); 58 long token = stream.start(UserLevelHibernationStatesProto.HIBERNATION_STATE); 59 while (stream.nextField() != ProtoInputStream.NO_MORE_FIELDS) { 60 switch (stream.getFieldNumber()) { 61 case (int) UserLevelHibernationStateProto.PACKAGE_NAME: 62 state.packageName = 63 stream.readString(UserLevelHibernationStateProto.PACKAGE_NAME); 64 break; 65 case (int) UserLevelHibernationStateProto.HIBERNATED: 66 state.hibernated = 67 stream.readBoolean(UserLevelHibernationStateProto.HIBERNATED); 68 break; 69 default: 70 Slog.w(TAG, "Undefined field in proto: " + stream.getFieldNumber()); 71 } 72 } 73 stream.end(token); 74 list.add(state); 75 } 76 return list; 77 } 78 } 79