1 /*
2  * Copyright (C) 2014 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.settings;
18 
19 import android.content.Context;
20 import android.content.Intent;
21 import android.content.pm.ApplicationInfo;
22 import android.content.pm.PackageManager;
23 import android.content.pm.ResolveInfo;
24 
25 import androidx.preference.Preference;
26 import androidx.preference.PreferenceGroup;
27 
28 import java.util.List;
29 
30 /**
31  * Utilities for saving and loading shared prefs.
32  */
33 public final class PreferenceUtils {
34 
35     public static final int FLAG_SET_TITLE = 1;
36 
resolveSystemActivityOrRemove(Context context, PreferenceGroup parent, Preference preference, int flags)37     public static void resolveSystemActivityOrRemove(Context context, PreferenceGroup parent,
38             Preference preference, int flags) {
39         if (preference == null) {
40             return;
41         }
42 
43         Intent intent = preference.getIntent();
44         if (intent != null) {
45             // Find the activity that is in the system image
46             PackageManager pm = context.getPackageManager();
47             List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
48             for (final ResolveInfo resolveInfo : list) {
49                 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
50                         != 0) {
51 
52                     // Replace the intent with this specific activity
53                     preference.setIntent(new Intent().setClassName(
54                             resolveInfo.activityInfo.packageName,
55                             resolveInfo.activityInfo.name));
56 
57                     if ((flags & FLAG_SET_TITLE) != 0) {
58                         // Set the preference title to the activity's label
59                         preference.setTitle(resolveInfo.loadLabel(pm));
60                     }
61 
62                     return;
63                 }
64             }
65         }
66 
67         // Did not find a matching activity, so remove the preference
68         parent.removePreference(preference);
69     }
70 }
71