1 /* 2 * Copyright (C) 2018 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.settings.slices; 18 19 import android.content.Context; 20 import android.net.Uri; 21 22 import androidx.annotation.VisibleForTesting; 23 import androidx.lifecycle.LiveData; 24 import androidx.lifecycle.Observer; 25 import androidx.preference.PreferenceScreen; 26 import androidx.slice.Slice; 27 import androidx.slice.widget.SliceLiveData; 28 import androidx.slice.widget.SliceView; 29 30 import com.android.settings.core.BasePreferenceController; 31 import com.android.settingslib.core.lifecycle.LifecycleObserver; 32 import com.android.settingslib.core.lifecycle.events.OnStart; 33 import com.android.settingslib.core.lifecycle.events.OnStop; 34 35 /** 36 * Default {@link BasePreferenceController} for {@link SliceView}. It will take {@link Uri} for 37 * Slice and display what's inside this {@link Uri} 38 */ 39 public class SlicePreferenceController extends BasePreferenceController implements 40 LifecycleObserver, OnStart, OnStop, Observer<Slice> { 41 @VisibleForTesting 42 LiveData<Slice> mLiveData; 43 @VisibleForTesting 44 SlicePreference mSlicePreference; 45 private Uri mUri; 46 SlicePreferenceController(Context context, String preferenceKey)47 public SlicePreferenceController(Context context, String preferenceKey) { 48 super(context, preferenceKey); 49 } 50 51 @Override displayPreference(PreferenceScreen screen)52 public void displayPreference(PreferenceScreen screen) { 53 super.displayPreference(screen); 54 mSlicePreference = screen.findPreference(getPreferenceKey()); 55 } 56 57 @Override getAvailabilityStatus()58 public int getAvailabilityStatus() { 59 return mUri != null ? AVAILABLE : UNSUPPORTED_ON_DEVICE; 60 } 61 setSliceUri(Uri uri)62 public void setSliceUri(Uri uri) { 63 mUri = uri; 64 mLiveData = SliceLiveData.fromUri(mContext, mUri); 65 66 //TODO(b/120803703): figure out why we need to remove observer first 67 mLiveData.removeObserver(this); 68 } 69 70 @Override onStart()71 public void onStart() { 72 if (mLiveData != null) { 73 mLiveData.observeForever(this); 74 } 75 } 76 77 @Override onStop()78 public void onStop() { 79 if (mLiveData != null) { 80 mLiveData.removeObserver(this); 81 } 82 } 83 84 @Override onChanged(Slice slice)85 public void onChanged(Slice slice) { 86 mSlicePreference.onSliceUpdated(slice); 87 } 88 } 89