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