1 /* 2 * Copyright (C) 2019 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.tv.twopanelsettings.slices; 18 19 import android.app.slice.SliceManager; 20 import android.content.Context; 21 import android.net.Uri; 22 import android.util.ArrayMap; 23 24 import com.android.tv.twopanelsettings.slices.PreferenceSliceLiveData.SliceLiveDataImpl; 25 26 27 /** 28 * Ensure the SliceLiveData with same uri is created only once across the activity. 29 */ 30 public class ContextSingleton { 31 private static ContextSingleton sInstance; 32 private ArrayMap<Uri, SliceLiveDataImpl> mSliceMap; 33 private boolean mGivenFullSliceAccess; 34 35 /** 36 * Get the instance. 37 */ getInstance()38 public static ContextSingleton getInstance() { 39 if (sInstance == null) { 40 sInstance = new ContextSingleton(); 41 } 42 return sInstance; 43 } 44 ContextSingleton()45 private ContextSingleton() { 46 mSliceMap = new ArrayMap<>(); 47 mGivenFullSliceAccess = false; 48 } 49 50 /** 51 * Get the corresponding SliceLiveData based on the uri. 52 */ getSliceLiveData(Context context, Uri uri)53 public SliceLiveDataImpl getSliceLiveData(Context context, Uri uri) { 54 if (!mSliceMap.containsKey(uri)) { 55 mSliceMap.put(uri, PreferenceSliceLiveData.fromUri(context, uri)); 56 } 57 58 return mSliceMap.get(uri); 59 } 60 61 /** 62 * Grant full access to current package. 63 */ grantFullAccess(Context ctx, Uri uri)64 public void grantFullAccess(Context ctx, Uri uri) { 65 if (!mGivenFullSliceAccess) { 66 String currentPackageName = ctx.getApplicationContext().getPackageName(); 67 // Uri cannot be null here as SliceManagerService calls notifyChange(uri, null) in 68 // grantPermissionFromUser. 69 ctx.getSystemService(SliceManager.class).grantPermissionFromUser( 70 uri, currentPackageName, true); 71 mGivenFullSliceAccess = true; 72 } 73 } 74 75 /** 76 * Grant full access to specific package. 77 */ grantFullAccess(Context ctx, String uri, String packageName)78 public void grantFullAccess(Context ctx, String uri, String packageName) { 79 if (!mGivenFullSliceAccess) { 80 // Uri cannot be null here as SliceManagerService calls notifyChange(uri, null) in 81 // grantPermissionFromUser. 82 ctx.getSystemService(SliceManager.class).grantPermissionFromUser( 83 Uri.parse(uri), packageName, true); 84 mGivenFullSliceAccess = true; 85 } 86 } 87 } 88