Remove old default apps code and use roles instead.

Default apps are moved into PermissionController.

Bug: 124452117
Bug: 124457823
Test: presubmit & manual
Change-Id: I5f68e5b77cd6163d093590185314270706d75391
This commit is contained in:
Hai Zhang
2019-04-06 15:45:42 +08:00
parent 470ec69461
commit 22f8d48df0
39 changed files with 36 additions and 2917 deletions

View File

@@ -2819,30 +2819,6 @@
</intent-filter>
</activity>
<activity
android:name="Settings$AdvancedAppsActivity"
android:exported="true"
android:label="@string/app_default_dashboard_title"
android:parentActivityName="Settings">
<intent-filter android:priority="1">
<action android:name="android.settings.MANAGE_DEFAULT_APPS_SETTINGS" />
<action android:name="android.settings.HOME_SETTINGS" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<intent-filter>
<action android:name="com.android.settings.action.SETTINGS"/>
</intent-filter>
<meta-data android:name="com.android.settings.order" android:value="-120"/>
<meta-data android:name="com.android.settings.category"
android:value="com.android.settings.category.ia.apps"/>
<meta-data android:name="com.android.settings.FRAGMENT_CLASS"
android:value="com.android.settings.applications.DefaultAppSettings" />
<meta-data android:name="com.android.settings.summary"
android:resource="@string/summary_empty"/>
<meta-data android:name="com.android.settings.PRIMARY_PROFILE_CONTROLLED"
android:value="true" />
</activity>
<!-- Keep compatibility with old WebView-picker implementation -->
<activity-alias android:name=".WebViewImplementation"
android:targetActivity="Settings$WebViewAppPickerActivity"

View File

@@ -320,9 +320,6 @@
<!-- Whether wallpaper attribution should be shown or not. -->
<bool name="config_show_wallpaper_attribution">true</bool>
<!-- Whether default_home should be shown or not. -->
<bool name="config_show_default_home">true</bool>
<!-- Whether assist_and_voice_input should be shown or not. -->
<bool name="config_show_assist_and_voice_input">true</bool>

View File

@@ -7160,10 +7160,8 @@
<!-- Search keyword for "Flashlight" settings [CHAR_LIMIT=NONE]-->
<string name="keywords_flashlight">Flashlight, Light, Torch</string>
<string name="keywords_change_wifi_state">wifi, wi-fi, toggle, control</string>
<string name="keywords_more_default_sms_app">text message, texting, messages, messaging, default</string>
<string name="keywords_more_mobile_networks">cellular, mobile, cell carrier, wireless, data, 4g,3g, 2g, lte</string>
<string name="keywords_wifi_calling">wifi, wi-fi, call, calling</string>
<string name="keywords_home">launcher, default, apps</string>
<string name="keywords_display">screen, touchscreen</string>
<string name="keywords_display_brightness_level">dim screen, touchscreen, battery, bright</string>
<string name="keywords_display_night_display">dim screen, night, tint, night shift, brightness, screen color, colour, color</string>
@@ -7188,8 +7186,6 @@
<string name="keywords_users">restriction, restrict, restricted</string>
<string name="keywords_keyboard_and_ime">text correction, correct, sound, vibrate, auto, language, gesture, suggest, suggestion, theme, offensive, word, type, emoji, international</string>
<string name="keywords_reset_apps">reset, preferences, default</string>
<string name="keywords_emergency_app">emergency, ice, app, default</string>
<string name="keywords_default_phone_app">phone, dialer, default</string>
<string name="keywords_all_apps">apps, download, applications, system</string>
<string name="keywords_app_permissions">apps, permissions, security</string>
<string name="keywords_default_apps">apps, default</string>
@@ -7261,15 +7257,9 @@
<!-- List of synonyms for the Default Assist and Voice input setting, used to match in settings search [CHAR LIMIT=NONE] -->
<string name="keywords_assist_input">default, assistant</string>
<!-- List of synonyms for the Wallpaper picker setting, used to match in settings search [CHAR LIMIT=NONE] -->
<string name="keywords_default_browser">default, default browser</string>
<!-- List of synonyms for the default payment app setting, used to match in settings search [CHAR LIMIT=NONE] -->
<string name="keywords_default_payment_app">payment, default</string>
<!-- List of synonyms for the default links setting, used to match in settings search [CHAR LIMIT=NONE] -->
<string name="keywords_default_links">default</string>
<!-- List of synonyms for Ambient display setting (when the screen is off), used to match in settings search [CHAR LIMIT=NONE] -->
<string name="keywords_ambient_display">incoming notification</string>

View File

@@ -50,6 +50,14 @@
android:key="dashboard_tile_placeholder"
android:order="10"/>
<Preference
android:key="default_apps"
android:title="@string/app_default_dashboard_title"
android:order="11"
settings:controller="com.android.settings.applications.DefaultAppsPreferenceController">
<intent android:action="android.settings.MANAGE_DEFAULT_APPS_SETTINGS"/>
</Preference>
<Preference
android:key="manage_perms"
android:title="@string/app_permissions"

View File

@@ -1,106 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
Copyright (C) 2016 The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:settings="http://schemas.android.com/apk/res-auto"
android:key="app_default_settings_screen"
android:title="@string/app_default_dashboard_title"
settings:keywords="@string/keywords_app_default">
<com.android.settingslib.widget.apppreference.AppPreference
android:key="assist_and_voice_input"
android:title="@string/assist_and_voice_input_title"
android:fragment="com.android.settings.applications.assist.ManageAssist"
settings:searchable="false"/>
<com.android.settingslib.widget.apppreference.AppPreference
android:key="default_browser"
android:title="@string/default_browser_title"
android:fragment="com.android.settings.applications.defaultapps.DefaultBrowserPicker"
settings:keywords="@string/keywords_default_browser">
<extra android:name="for_work" android:value="false" />
</com.android.settingslib.widget.apppreference.AppPreference>
<com.android.settingslib.widget.apppreference.AppPreference
android:key="default_home"
android:title="@string/home_app"
android:fragment="com.android.settings.applications.defaultapps.DefaultHomePicker"
settings:keywords="@string/keywords_home" />
<com.android.settingslib.widget.apppreference.AppPreference
android:key="default_phone_app"
android:title="@string/default_phone_title"
android:fragment="com.android.settings.applications.defaultapps.DefaultPhonePicker"
settings:keywords="@string/keywords_default_phone_app" />
<com.android.settingslib.widget.apppreference.AppPreference
android:key="default_sms_app"
android:title="@string/sms_application_title"
android:fragment="com.android.settings.applications.defaultapps.DefaultSmsPicker"
settings:keywords="@string/keywords_more_default_sms_app" />
<com.android.settingslib.widget.apppreference.AppPreference
android:key="default_emergency_app"
android:title="@string/default_emergency_app"
settings:keywords="@string/keywords_emergency_app" />
<!--
<com.android.settingslib.widget.apppreference.AppPreference
android:key="default_notification_asst_app"
android:title="@string/default_notification_assistant"
android:fragment="com.android.settings.applications.defaultapps.DefaultNotificationAssistantPicker"
/>
-->
<com.android.settingslib.widget.apppreference.AppPreference
android:key="domain_urls"
android:title="@string/domain_urls_title"
android:fragment="com.android.settings.applications.managedomainurls.ManageDomainUrls"
settings:keywords="@string/keywords_default_links"/>
<!--
~ STOPSHIP(b/110557011): Remove once the new UI is ready.
-->
<Preference
android:key="roles"
android:title="@string/roles_title"
settings:controller="com.android.settings.applications.defaultapps.RolesPreferenceController" />
<com.android.settings.widget.WorkOnlyCategory
android:key="work_app_defaults"
android:title="@string/default_for_work">
<com.android.settingslib.widget.apppreference.AppPreference
android:key="work_default_browser"
android:title="@string/default_browser_title"
android:fragment="com.android.settings.applications.defaultapps.DefaultBrowserPicker"
settings:searchable="false">
<extra android:name="for_work" android:value="true" />
</com.android.settingslib.widget.apppreference.AppPreference>
<com.android.settingslib.widget.apppreference.AppPreference
android:key="work_default_phone_app"
android:title="@string/default_phone_title"
android:fragment="com.android.settings.applications.defaultapps.DefaultPhonePicker"
settings:searchable="false">
<extra android:name="for_work" android:value="true" />
</com.android.settingslib.widget.apppreference.AppPreference>
</com.android.settings.widget.WorkOnlyCategory>
</PreferenceScreen>

View File

@@ -1,20 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
Copyright (C) 2017 The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
android:title="@string/default_assist_title" />

View File

@@ -1,20 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
Copyright (C) 2017 The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
android:title="@string/default_browser_title" />

View File

@@ -1,20 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
Copyright (C) 2017 The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
android:title="@string/default_emergency_app" />

View File

@@ -1,20 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
Copyright (C) 2017 The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
android:title="@string/home_app" />

View File

@@ -1,20 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
Copyright (C) 2017 The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
android:title="@string/default_phone_title" />

View File

@@ -1,20 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
Copyright (C) 2017 The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
android:title="@string/sms_application_title" />

View File

@@ -136,7 +136,6 @@ public class Settings extends SettingsActivity {
public static class ChangeWifiStateActivity extends SettingsActivity { /* empty */ }
public static class AppDrawOverlaySettingsActivity extends SettingsActivity { /* empty */ }
public static class AppWriteSettingsActivity extends SettingsActivity { /* empty */ }
public static class AdvancedAppsActivity extends SettingsActivity { /* empty */ }
public static class ManageExternalSourcesActivity extends SettingsActivity {/* empty */ }
public static class ManageAppExternalSourcesActivity extends SettingsActivity { /* empty */ }

View File

@@ -1,156 +0,0 @@
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.applications;
import android.app.Activity;
import android.app.settings.SettingsEnums;
import android.content.Context;
import android.icu.text.ListFormatter;
import android.provider.SearchIndexableResource;
import android.text.TextUtils;
import com.android.settings.R;
import com.android.settings.applications.assist.DefaultAssistPreferenceController;
import com.android.settings.applications.defaultapps.DefaultBrowserPreferenceController;
import com.android.settings.applications.defaultapps.DefaultEmergencyPreferenceController;
import com.android.settings.applications.defaultapps.DefaultHomePreferenceController;
import com.android.settings.applications.defaultapps.DefaultPhonePreferenceController;
import com.android.settings.applications.defaultapps.DefaultSmsPreferenceController;
import com.android.settings.applications.defaultapps.DefaultWorkBrowserPreferenceController;
import com.android.settings.applications.defaultapps.DefaultWorkPhonePreferenceController;
import com.android.settings.dashboard.DashboardFragment;
import com.android.settings.dashboard.SummaryLoader;
import com.android.settings.search.BaseSearchIndexProvider;
import com.android.settings.search.Indexable;
import com.android.settings.widget.PreferenceCategoryController;
import com.android.settingslib.core.AbstractPreferenceController;
import com.android.settingslib.search.SearchIndexable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@SearchIndexable
public class DefaultAppSettings extends DashboardFragment {
static final String TAG = "DefaultAppSettings";
private static final String KEY_DEFAULT_WORK_CATEGORY = "work_app_defaults";
private static final String KEY_ASSIST_VOICE_INPUT = "assist_and_voice_input";
@Override
protected String getLogTag() {
return TAG;
}
@Override
protected int getPreferenceScreenResId() {
return R.xml.app_default_settings;
}
@Override
protected List<AbstractPreferenceController> createPreferenceControllers(Context context) {
return buildPreferenceControllers(context);
}
@Override
public int getMetricsCategory() {
return SettingsEnums.APPLICATIONS_ADVANCED;
}
private static List<AbstractPreferenceController> buildPreferenceControllers(Context context) {
final List<AbstractPreferenceController> controllers = new ArrayList<>();
final List<AbstractPreferenceController> workControllers = new ArrayList<>();
workControllers.add(new DefaultWorkPhonePreferenceController(context));
workControllers.add(new DefaultWorkBrowserPreferenceController(context));
controllers.addAll(workControllers);
controllers.add(new PreferenceCategoryController(
context, KEY_DEFAULT_WORK_CATEGORY).setChildren(workControllers));
controllers.add(new DefaultAssistPreferenceController(context, KEY_ASSIST_VOICE_INPUT,
false /* showSetting */));
controllers.add(new DefaultBrowserPreferenceController(context));
controllers.add(new DefaultPhonePreferenceController(context));
controllers.add(new DefaultSmsPreferenceController(context));
controllers.add(new DefaultEmergencyPreferenceController(context));
controllers.add(new DefaultHomePreferenceController(context));
return controllers;
}
public static final Indexable.SearchIndexProvider SEARCH_INDEX_DATA_PROVIDER =
new BaseSearchIndexProvider() {
@Override
public List<SearchIndexableResource> getXmlResourcesToIndex(
Context context, boolean enabled) {
final SearchIndexableResource sir = new SearchIndexableResource(context);
sir.xmlResId = R.xml.app_default_settings;
return Arrays.asList(sir);
}
@Override
public List<AbstractPreferenceController> createPreferenceControllers(
Context context) {
return buildPreferenceControllers(context);
}
};
static class SummaryProvider implements SummaryLoader.SummaryProvider {
private final Context mContext;
private final SummaryLoader mSummaryLoader;
private final DefaultSmsPreferenceController mDefaultSmsPreferenceController;
private final DefaultBrowserPreferenceController mDefaultBrowserPreferenceController;
private final DefaultPhonePreferenceController mDefaultPhonePreferenceController;
public SummaryProvider(Context context, SummaryLoader summaryLoader) {
mContext = context;
mSummaryLoader = summaryLoader;
mDefaultSmsPreferenceController = new DefaultSmsPreferenceController(mContext);
mDefaultBrowserPreferenceController = new DefaultBrowserPreferenceController(mContext);
mDefaultPhonePreferenceController = new DefaultPhonePreferenceController(mContext);
}
@Override
public void setListening(boolean listening) {
if (!listening) {
return;
}
final List<CharSequence> summaries = new ArrayList<>();
if(!TextUtils.isEmpty(mDefaultBrowserPreferenceController.getDefaultAppLabel())) {
summaries.add(mDefaultBrowserPreferenceController.getDefaultAppLabel());
}
if(!TextUtils.isEmpty(mDefaultPhonePreferenceController.getDefaultAppLabel())) {
summaries.add(mDefaultPhonePreferenceController.getDefaultAppLabel());
}
if(!TextUtils.isEmpty(mDefaultSmsPreferenceController.getDefaultAppLabel())) {
summaries.add(mDefaultSmsPreferenceController.getDefaultAppLabel());
}
CharSequence summary = ListFormatter.getInstance().format(summaries);
if (!TextUtils.isEmpty(summary)) {
mSummaryLoader.setSummary(this, summary);
}
}
}
public static final SummaryLoader.SummaryProviderFactory SUMMARY_PROVIDER_FACTORY =
new SummaryLoader.SummaryProviderFactory() {
@Override
public SummaryLoader.SummaryProvider createSummaryProvider(Activity activity,
SummaryLoader summaryLoader) {
return new DefaultAppSettings.SummaryProvider(activity, summaryLoader);
}
};
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright (C) 2018 The Android Open Source Project
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -11,66 +11,38 @@
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* limitations under the License
*/
package com.android.settings.applications.defaultapps;
package com.android.settings.applications;
import android.app.role.RoleManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.icu.text.ListFormatter;
import android.provider.Settings;
import android.text.TextUtils;
import androidx.preference.Preference;
import com.android.settings.core.BasePreferenceController;
import com.android.settingslib.applications.AppUtils;
import java.util.ArrayList;
import java.util.List;
/**
* STOPSHIP(b/110557011): Remove once the new UI is ready.
*/
public class RolesPreferenceController extends BasePreferenceController {
public class DefaultAppsPreferenceController extends BasePreferenceController {
private final PackageManager mPackageManager;
private final RoleManager mRoleManager;
private final Intent mIntent;
public RolesPreferenceController(Context context, String preferenceKey) {
public DefaultAppsPreferenceController(Context context, String preferenceKey) {
super(context, preferenceKey);
mPackageManager = context.getPackageManager();
mRoleManager = context.getSystemService(RoleManager.class);
final String packageName = mPackageManager.getPermissionControllerPackageName();
if (packageName != null) {
mIntent = new Intent(Settings.ACTION_MANAGE_DEFAULT_APPS_SETTINGS)
.setPackage(packageName);
} else {
mIntent = null;
}
}
@Override
public int getAvailabilityStatus() {
return mIntent != null ? AVAILABLE_UNSEARCHABLE : UNSUPPORTED_ON_DEVICE;
}
@Override
public boolean handlePreferenceTreeClick(Preference preference) {
if (TextUtils.equals(preference.getKey(), mPreferenceKey)) {
if (mIntent != null) {
mContext.startActivity(mIntent);
}
return true;
}
return false;
return AVAILABLE;
}
@Override

View File

@@ -1,74 +0,0 @@
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.applications.defaultapps;
import android.app.settings.SettingsEnums;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import com.android.settings.R;
import com.android.settingslib.applications.DefaultAppInfo;
import java.util.ArrayList;
import java.util.List;
/**
* Fragment for choosing default browser.
*/
public class DefaultBrowserPicker extends DefaultAppPickerFragment {
@Override
protected int getPreferenceScreenResId() {
return R.xml.default_browser_settings;
}
@Override
public int getMetricsCategory() {
return SettingsEnums.DEFAULT_BROWSER_PICKER;
}
@Override
protected String getDefaultKey() {
return mPm.getDefaultBrowserPackageNameAsUser(mUserId);
}
@Override
protected boolean setDefaultKey(String packageName) {
return mPm.setDefaultBrowserPackageNameAsUser(packageName, mUserId);
}
@Override
protected List<DefaultAppInfo> getCandidates() {
final List<DefaultAppInfo> candidates = new ArrayList<>();
final Context context = getContext();
// Resolve that intent and check that the handleAllWebDataURI boolean is set
final List<ResolveInfo> list =
DefaultBrowserPreferenceController.getCandidates(mPm, mUserId);
for (ResolveInfo info : list) {
try {
candidates.add(new DefaultAppInfo(context, mPm, mUserId,
mPm.getApplicationInfoAsUser(info.activityInfo.packageName, 0, mUserId)));
} catch (PackageManager.NameNotFoundException e) {
// Skip unknown packages.
}
}
return candidates;
}
}

View File

@@ -1,198 +0,0 @@
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.applications.defaultapps;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.ComponentInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.text.TextUtils;
import android.util.ArraySet;
import android.util.IconDrawableFactory;
import android.util.Log;
import androidx.annotation.VisibleForTesting;
import androidx.preference.Preference;
import com.android.settingslib.applications.DefaultAppInfo;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
public class DefaultBrowserPreferenceController extends DefaultAppPreferenceController {
private static final String TAG = "BrowserPrefCtrl";
static final Intent BROWSE_PROBE = new Intent()
.setAction(Intent.ACTION_VIEW)
.addCategory(Intent.CATEGORY_BROWSABLE)
.setData(Uri.parse("http:"))
.addFlags(Intent.FLAG_IGNORE_EPHEMERAL);
public DefaultBrowserPreferenceController(Context context) {
super(context);
}
@Override
public boolean isAvailable() {
final List<ResolveInfo> candidates = getCandidates(mPackageManager, mUserId);
return candidates != null && !candidates.isEmpty();
}
@Override
public String getPreferenceKey() {
return "default_browser";
}
@Override
public void updateState(Preference preference) {
super.updateState(preference);
final CharSequence defaultAppLabel = getDefaultAppLabel();
if (!TextUtils.isEmpty(defaultAppLabel)) {
preference.setSummary(defaultAppLabel);
}
}
@Override
protected DefaultAppInfo getDefaultAppInfo() {
try {
final String packageName = mPackageManager.getDefaultBrowserPackageNameAsUser(mUserId);
Log.d(TAG, "Get default browser package: " + packageName);
return new DefaultAppInfo(mContext, mPackageManager, mUserId,
mPackageManager.getApplicationInfoAsUser(packageName, 0, mUserId));
} catch (PackageManager.NameNotFoundException e) {
return null;
}
}
@Override
public CharSequence getDefaultAppLabel() {
if (!isAvailable()) {
return null;
}
final DefaultAppInfo defaultApp = getDefaultAppInfo();
final CharSequence defaultAppLabel = defaultApp != null ? defaultApp.loadLabel() : null;
if (!TextUtils.isEmpty(defaultAppLabel)) {
return defaultAppLabel;
}
return getOnlyAppLabel();
}
@Override
public Drawable getDefaultAppIcon() {
if (!isAvailable()) {
return null;
}
final DefaultAppInfo defaultApp = getDefaultAppInfo();
if (defaultApp != null) {
return defaultApp.loadIcon();
}
return getOnlyAppIcon();
}
static List<ResolveInfo> getCandidates(PackageManager packageManager, int userId) {
final List<ResolveInfo> candidates = new ArrayList<>();
// Resolve that intent and check that the handleAllWebDataURI boolean is set
final List<ResolveInfo> list = packageManager.queryIntentActivitiesAsUser(
BROWSE_PROBE, PackageManager.MATCH_ALL, userId);
if (list != null) {
final Set<String> addedPackages = new ArraySet<>();
for (ResolveInfo info : list) {
if (!info.handleAllWebDataURI || info.activityInfo == null
|| !info.activityInfo.enabled
|| !info.activityInfo.applicationInfo.enabled) {
continue;
}
final String packageName = info.activityInfo.packageName;
if (addedPackages.contains(packageName)) {
continue;
}
candidates.add(info);
addedPackages.add(packageName);
}
}
return candidates;
}
private String getOnlyAppLabel() {
// Resolve that intent and check that the handleAllWebDataURI boolean is set
final List<ResolveInfo> list = getCandidates(mPackageManager, mUserId);
if (list != null && list.size() == 1) {
final ResolveInfo info = list.get(0);
final String label = info.loadLabel(mPackageManager).toString();
final ComponentInfo cn = info.getComponentInfo();
final String packageName = cn == null ? null : cn.packageName;
Log.d(TAG, "Getting label for the only browser app: " + packageName + label);
return label;
}
return null;
}
@VisibleForTesting
Drawable getOnlyAppIcon() {
final List<ResolveInfo> list = getCandidates(mPackageManager, mUserId);
if (list != null && list.size() == 1) {
final ResolveInfo info = list.get(0);
final ComponentInfo cn = info.getComponentInfo();
final String packageName = cn == null ? null : cn.packageName;
if (TextUtils.isEmpty(packageName)) {
return null;
}
final ApplicationInfo appInfo;
try {
appInfo = mPackageManager.getApplicationInfoAsUser(packageName, 0, mUserId);
} catch (PackageManager.NameNotFoundException e) {
Log.w(TAG, "Error getting app info for " + packageName);
return null;
}
Log.d(TAG, "Getting icon for the only browser app: " + packageName);
final IconDrawableFactory iconFactory = IconDrawableFactory.newInstance(mContext);
return iconFactory.getBadgedIcon(cn, appInfo, mUserId);
}
return null;
}
/**
* Whether or not the pkg contains browser capability
*/
public static boolean hasBrowserPreference(String pkg, Context context, int userId) {
final Intent intent = new Intent(BROWSE_PROBE);
intent.setPackage(pkg);
final List<ResolveInfo> resolveInfos = context.getPackageManager()
.queryIntentActivitiesAsUser(intent, 0 /* flags */, userId);
return resolveInfos != null && resolveInfos.size() != 0;
}
/**
* Whether or not the pkg is the default browser
*/
public boolean isBrowserDefault(String pkg, int userId) {
final String defaultPackage = mPackageManager.getDefaultBrowserPackageNameAsUser(userId);
if (defaultPackage != null) {
return defaultPackage.equals(pkg);
}
final List<ResolveInfo> list = getCandidates(mPackageManager, userId);
// There is only 1 app, it must be the default browser.
return list != null && list.size() == 1;
}
}

View File

@@ -1,115 +0,0 @@
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.applications.defaultapps;
import android.app.role.RoleManager;
import android.app.settings.SettingsEnums;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.AsyncTask;
import android.os.Process;
import android.text.TextUtils;
import android.util.Log;
import com.android.internal.util.CollectionUtils;
import com.android.settings.R;
import com.android.settings.Utils;
import com.android.settingslib.applications.DefaultAppInfo;
import com.android.settingslib.widget.CandidateInfo;
import java.util.ArrayList;
import java.util.List;
public class DefaultEmergencyPicker extends DefaultAppPickerFragment {
private static final String TAG = "DefaultEmergencyPicker";
@Override
public int getMetricsCategory() {
return SettingsEnums.DEFAULT_EMERGENCY_APP_PICKER;
}
@Override
protected int getPreferenceScreenResId() {
return R.xml.default_emergency_settings;
}
@Override
protected List<DefaultAppInfo> getCandidates() {
final List<DefaultAppInfo> candidates = new ArrayList<>();
final List<ResolveInfo> infos = mPm.queryIntentActivities(
DefaultEmergencyPreferenceController.QUERY_INTENT, 0);
PackageInfo bestMatch = null;
final Context context = getContext();
for (ResolveInfo info : infos) {
try {
final PackageInfo packageInfo =
mPm.getPackageInfo(info.activityInfo.packageName, 0);
final ApplicationInfo appInfo = packageInfo.applicationInfo;
candidates.add(new DefaultAppInfo(context, mPm, mUserId, appInfo));
// Get earliest installed system app.
if (isSystemApp(appInfo) && (bestMatch == null ||
bestMatch.firstInstallTime > packageInfo.firstInstallTime)) {
bestMatch = packageInfo;
}
} catch (PackageManager.NameNotFoundException e) {
// Skip unknown packages.
}
if (bestMatch != null) {
final String defaultKey = getDefaultKey();
if (TextUtils.isEmpty(defaultKey)) {
setDefaultKey(bestMatch.packageName);
}
}
}
return candidates;
}
@Override
protected String getConfirmationMessage(CandidateInfo info) {
return Utils.isPackageDirectBootAware(getContext(), info.getKey()) ? null
: getContext().getString(R.string.direct_boot_unaware_dialog_message);
}
@Override
protected String getDefaultKey() {
RoleManager roleManager = getContext().getSystemService(RoleManager.class);
return CollectionUtils.firstOrNull(roleManager.getRoleHolders(RoleManager.ROLE_EMERGENCY));
}
@Override
protected boolean setDefaultKey(String key) {
final String previousValue = getDefaultKey();
if (!TextUtils.isEmpty(key) && !TextUtils.equals(key, previousValue)) {
getContext().getSystemService(RoleManager.class).addRoleHolderAsUser(
RoleManager.ROLE_EMERGENCY, key, 0, Process.myUserHandle(),
AsyncTask.THREAD_POOL_EXECUTOR, successful -> {
if (!successful) {
Log.e(TAG, "Failed to set emergency default app.");
}
});
return true;
}
return false;
}
private boolean isSystemApp(ApplicationInfo info) {
return info != null && (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
}
}

View File

@@ -1,79 +0,0 @@
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.applications.defaultapps;
import android.app.role.RoleManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import com.android.internal.util.CollectionUtils;
import com.android.settingslib.applications.DefaultAppInfo;
import java.util.List;
public class DefaultEmergencyPreferenceController extends DefaultAppPreferenceController {
private static final boolean DEFAULT_EMERGENCY_APP_IS_CONFIGURABLE = false;
public static final Intent QUERY_INTENT = new Intent(
TelephonyManager.ACTION_EMERGENCY_ASSISTANCE);
public DefaultEmergencyPreferenceController(Context context) {
super(context);
}
@Override
public boolean isAvailable() {
return DEFAULT_EMERGENCY_APP_IS_CONFIGURABLE
&& isCapable()
&& mPackageManager.resolveActivity(QUERY_INTENT, 0) != null;
}
@Override
public String getPreferenceKey() {
return "default_emergency_app";
}
@Override
protected DefaultAppInfo getDefaultAppInfo() {
return null;
}
private boolean isCapable() {
return TelephonyManager.EMERGENCY_ASSISTANCE_ENABLED
&& mContext.getResources().getBoolean(
com.android.internal.R.bool.config_voice_capable);
}
public static boolean hasEmergencyPreference(String pkg, Context context) {
Intent i = new Intent(QUERY_INTENT);
i.setPackage(pkg);
final List<ResolveInfo> resolveInfos =
context.getPackageManager().queryIntentActivities(i, 0);
return resolveInfos != null && resolveInfos.size() != 0;
}
public static boolean isEmergencyDefault(String pkg, Context context) {
String defaultPackage = CollectionUtils.firstOrNull(
context.getSystemService(RoleManager.class)
.getRoleHolders(RoleManager.ROLE_EMERGENCY));
return defaultPackage != null && defaultPackage.equals(pkg);
}
}

View File

@@ -1,152 +0,0 @@
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.applications.defaultapps;
import android.app.settings.SettingsEnums;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.pm.UserInfo;
import android.os.Build;
import android.text.TextUtils;
import com.android.settings.R;
import com.android.settingslib.applications.DefaultAppInfo;
import java.util.ArrayList;
import java.util.List;
public class DefaultHomePicker extends DefaultAppPickerFragment {
private String mPackageName;
@Override
public void onAttach(Context context) {
super.onAttach(context);
mPackageName = context.getPackageName();
}
@Override
protected int getPreferenceScreenResId() {
return R.xml.default_home_settings;
}
@Override
public int getMetricsCategory() {
return SettingsEnums.DEFAULT_HOME_PICKER;
}
@Override
protected List<DefaultAppInfo> getCandidates() {
final boolean mustSupportManagedProfile = hasManagedProfile();
final List<DefaultAppInfo> candidates = new ArrayList<>();
final List<ResolveInfo> homeActivities = new ArrayList<>();
final Context context = getContext();
mPm.getHomeActivities(homeActivities);
for (ResolveInfo resolveInfo : homeActivities) {
final ActivityInfo info = resolveInfo.activityInfo;
final ComponentName activityName = new ComponentName(info.packageName, info.name);
if (info.packageName.equals(mPackageName)) {
continue;
}
final String summary;
boolean enabled = true;
if (mustSupportManagedProfile && !launcherHasManagedProfilesFeature(resolveInfo)) {
summary = getContext().getString(R.string.home_work_profile_not_supported);
enabled = false;
} else {
summary = null;
}
final DefaultAppInfo candidate =
new DefaultAppInfo(context, mPm, mUserId, activityName, summary, enabled);
candidates.add(candidate);
}
return candidates;
}
@Override
protected String getDefaultKey() {
final ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
final ComponentName currentDefaultHome = mPm.getHomeActivities(homeActivities);
if (currentDefaultHome != null) {
return currentDefaultHome.flattenToString();
}
return null;
}
@Override
protected boolean setDefaultKey(String key) {
if (!TextUtils.isEmpty(key)) {
final ComponentName component = ComponentName.unflattenFromString(key);
final List<ResolveInfo> homeActivities = new ArrayList<>();
mPm.getHomeActivities(homeActivities);
final List<ComponentName> allComponents = new ArrayList<>();
for (ResolveInfo info : homeActivities) {
final ActivityInfo appInfo = info.activityInfo;
ComponentName activityName = new ComponentName(appInfo.packageName, appInfo.name);
allComponents.add(activityName);
}
mPm.replacePreferredActivity(
DefaultHomePreferenceController.HOME_FILTER,
IntentFilter.MATCH_CATEGORY_EMPTY,
allComponents.toArray(new ComponentName[0]),
component);
// Launch the new Home app so the change is immediately visible even if
// the Home button is not pressed.
final Context context = getContext();
Intent i = new Intent(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_HOME);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
return true;
}
return false;
}
private boolean hasManagedProfile() {
final Context context = getContext();
List<UserInfo> profiles = mUserManager.getProfiles(context.getUserId());
for (UserInfo userInfo : profiles) {
if (userInfo.isManagedProfile()) {
return true;
}
}
return false;
}
private boolean launcherHasManagedProfilesFeature(ResolveInfo resolveInfo) {
try {
ApplicationInfo appInfo = mPm.getApplicationInfo(resolveInfo.activityInfo.packageName,
0 /* default flags */);
return versionNumberAtLeastL(appInfo.targetSdkVersion);
} catch (PackageManager.NameNotFoundException e) {
return false;
}
}
private boolean versionNumberAtLeastL(int versionNumber) {
return versionNumber >= Build.VERSION_CODES.LOLLIPOP;
}
}

View File

@@ -1,129 +0,0 @@
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.applications.defaultapps;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import com.android.settings.R;
import com.android.settingslib.applications.DefaultAppInfo;
import java.util.ArrayList;
import java.util.List;
public class DefaultHomePreferenceController extends DefaultAppPreferenceController {
static final IntentFilter HOME_FILTER;
private final String mPackageName;
static {
HOME_FILTER = new IntentFilter(Intent.ACTION_MAIN);
HOME_FILTER.addCategory(Intent.CATEGORY_HOME);
HOME_FILTER.addCategory(Intent.CATEGORY_DEFAULT);
}
public DefaultHomePreferenceController(Context context) {
super(context);
mPackageName = mContext.getPackageName();
}
@Override
public String getPreferenceKey() {
return "default_home";
}
@Override
public boolean isAvailable() {
return mContext.getResources().getBoolean(R.bool.config_show_default_home);
}
@Override
protected DefaultAppInfo getDefaultAppInfo() {
final ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
final ComponentName currentDefaultHome = mPackageManager.getHomeActivities(homeActivities);
if (currentDefaultHome != null) {
return new DefaultAppInfo(mContext, mPackageManager, mUserId, currentDefaultHome);
}
final ActivityInfo onlyAppInfo = getOnlyAppInfo(homeActivities);
if (onlyAppInfo != null) {
return new DefaultAppInfo(mContext, mPackageManager, mUserId,
onlyAppInfo.getComponentName());
}
return null;
}
private ActivityInfo getOnlyAppInfo(List<ResolveInfo> homeActivities) {
final List<ActivityInfo> appLabels = new ArrayList<>();
mPackageManager.getHomeActivities(homeActivities);
for (ResolveInfo candidate : homeActivities) {
final ActivityInfo info = candidate.activityInfo;
if (info.packageName.equals(mPackageName)) {
continue;
}
appLabels.add(info);
}
return appLabels.size() == 1
? appLabels.get(0)
: null;
}
@Override
protected Intent getSettingIntent(DefaultAppInfo info) {
if (info == null) {
return null;
}
final String packageName;
if (info.componentName != null) {
packageName = info.componentName.getPackageName();
} else if (info.packageItemInfo != null) {
packageName = info.packageItemInfo.packageName;
} else {
return null;
}
Intent intent = new Intent(Intent.ACTION_APPLICATION_PREFERENCES)
.setPackage(packageName)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
return intent.resolveActivity(mPackageManager) != null ? intent : null;
}
public static boolean hasHomePreference(String pkg, Context context) {
ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
PackageManager pm = context.getPackageManager();
pm.getHomeActivities(homeActivities);
for (int i = 0; i < homeActivities.size(); i++) {
if (homeActivities.get(i).activityInfo.packageName.equals(pkg)) {
return true;
}
}
return false;
}
public static boolean isHomeDefault(String pkg, PackageManager pm) {
final ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
ComponentName def = pm.getHomeActivities(homeActivities);
return def == null || def.getPackageName().equals(pkg);
}
}

View File

@@ -1,111 +0,0 @@
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.applications.defaultapps;
import android.app.settings.SettingsEnums;
import android.content.Context;
import android.content.pm.PackageManager;
import android.telecom.DefaultDialerManager;
import android.telecom.TelecomManager;
import android.text.TextUtils;
import com.android.settings.R;
import com.android.settingslib.applications.DefaultAppInfo;
import java.util.ArrayList;
import java.util.List;
public class DefaultPhonePicker extends DefaultAppPickerFragment {
private DefaultKeyUpdater mDefaultKeyUpdater;
@Override
public int getMetricsCategory() {
return SettingsEnums.DEFAULT_PHONE_PICKER;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
mDefaultKeyUpdater = new DefaultKeyUpdater(
(TelecomManager) context.getSystemService(Context.TELECOM_SERVICE));
}
@Override
protected int getPreferenceScreenResId() {
return R.xml.default_phone_settings;
}
@Override
protected List<DefaultAppInfo> getCandidates() {
final List<DefaultAppInfo> candidates = new ArrayList<>();
final List<String> dialerPackages =
DefaultDialerManager.getInstalledDialerApplications(getContext(), mUserId);
final Context context = getContext();
for (String packageName : dialerPackages) {
try {
candidates.add(new DefaultAppInfo(context, mPm, mUserId,
mPm.getApplicationInfoAsUser(packageName, 0, mUserId)));
} catch (PackageManager.NameNotFoundException e) {
// Skip unknown packages.
}
}
return candidates;
}
@Override
protected String getDefaultKey() {
return mDefaultKeyUpdater.getDefaultDialerApplication(getContext(), mUserId);
}
@Override
protected String getSystemDefaultKey() {
return mDefaultKeyUpdater.getSystemDialerPackage();
}
@Override
protected boolean setDefaultKey(String key) {
if (!TextUtils.isEmpty(key) && !TextUtils.equals(key, getDefaultKey())) {
mBatteryUtils.clearForceAppStandby(key);
return mDefaultKeyUpdater.setDefaultDialerApplication(getContext(), key, mUserId);
}
return false;
}
/**
* Wrapper class to handle default phone app update.
*/
static class DefaultKeyUpdater {
private final TelecomManager mTelecomManager;
public DefaultKeyUpdater(TelecomManager telecomManager) {
mTelecomManager = telecomManager;
}
public String getSystemDialerPackage() {
return mTelecomManager.getSystemDialerPackage();
}
public String getDefaultDialerApplication(Context context, int uid) {
return DefaultDialerManager.getDefaultDialerApplication(context, uid);
}
public boolean setDefaultDialerApplication(Context context, String key, int uid) {
return DefaultDialerManager.setDefaultDialerApplication(context, key, uid);
}
}
}

View File

@@ -1,85 +0,0 @@
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.applications.defaultapps;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.UserHandle;
import android.os.UserManager;
import android.telecom.DefaultDialerManager;
import android.telephony.TelephonyManager;
import com.android.settingslib.applications.DefaultAppInfo;
import java.util.List;
public class DefaultPhonePreferenceController extends DefaultAppPreferenceController {
public DefaultPhonePreferenceController(Context context) {
super(context);
}
@Override
public boolean isAvailable() {
final TelephonyManager tm =
(TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
if (!tm.isVoiceCapable()) {
return false;
}
final UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
final boolean hasUserRestriction =
um.hasUserRestriction(UserManager.DISALLOW_OUTGOING_CALLS);
if (hasUserRestriction) {
return false;
}
final List<String> candidates = getCandidates();
return candidates != null && !candidates.isEmpty();
}
@Override
public String getPreferenceKey() {
return "default_phone_app";
}
@Override
protected DefaultAppInfo getDefaultAppInfo() {
try {
return new DefaultAppInfo(mContext, mPackageManager, mUserId,
mPackageManager.getApplicationInfo(
DefaultDialerManager.getDefaultDialerApplication(mContext, mUserId), 0));
} catch (PackageManager.NameNotFoundException e) {
return null;
}
}
private List<String> getCandidates() {
return DefaultDialerManager.getInstalledDialerApplications(mContext, mUserId);
}
public static boolean hasPhonePreference(String pkg, Context context) {
List<String> dialerPackages =
DefaultDialerManager.getInstalledDialerApplications(context, UserHandle.myUserId());
return dialerPackages.contains(pkg);
}
public static boolean isPhoneDefault(String pkg, Context context) {
String def = DefaultDialerManager.getDefaultDialerApplication(context,
UserHandle.myUserId());
return def != null && def.equals(pkg);
}
}

View File

@@ -1,106 +0,0 @@
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.applications.defaultapps;
import android.app.settings.SettingsEnums;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.PackageManager;
import android.text.TextUtils;
import com.android.internal.telephony.SmsApplication;
import com.android.settings.R;
import com.android.settings.Utils;
import com.android.settingslib.applications.DefaultAppInfo;
import com.android.settingslib.widget.CandidateInfo;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class DefaultSmsPicker extends DefaultAppPickerFragment {
private DefaultKeyUpdater mDefaultKeyUpdater = new DefaultKeyUpdater();
@Override
public int getMetricsCategory() {
return SettingsEnums.DEFAULT_SMS_PICKER;
}
@Override
protected int getPreferenceScreenResId() {
return R.xml.default_sms_settings;
}
@Override
protected List<DefaultAppInfo> getCandidates() {
final Context context = getContext();
final Collection<SmsApplication.SmsApplicationData> smsApplications =
SmsApplication.getApplicationCollection(context);
final List<DefaultAppInfo> candidates = new ArrayList<>(smsApplications.size());
for (SmsApplication.SmsApplicationData smsApplicationData : smsApplications) {
try {
candidates.add(new DefaultAppInfo(context, mPm, mUserId,
mPm.getApplicationInfoAsUser(smsApplicationData.mPackageName, 0, mUserId)));
} catch (PackageManager.NameNotFoundException e) {
// Skip unknown packages.
}
}
return candidates;
}
@Override
protected String getDefaultKey() {
return mDefaultKeyUpdater.getDefaultApplication(getContext());
}
@Override
protected boolean setDefaultKey(String key) {
if (!TextUtils.isEmpty(key) && !TextUtils.equals(key, getDefaultKey())) {
mDefaultKeyUpdater.setDefaultApplication(getContext(), key);
mBatteryUtils.clearForceAppStandby(key);
return true;
}
return false;
}
@Override
protected String getConfirmationMessage(CandidateInfo info) {
return Utils.isPackageDirectBootAware(getContext(), info.getKey()) ? null
: getContext().getString(R.string.direct_boot_unaware_dialog_message);
}
/**
* Wrapper class to handle default phone app update.
*/
static class DefaultKeyUpdater {
public String getDefaultApplication(Context context) {
final ComponentName appName = SmsApplication.getDefaultSmsApplication(context, true);
if (appName != null) {
return appName.getPackageName();
}
return null;
}
public void setDefaultApplication(Context context, String key) {
SmsApplication.setDefaultApplication(key, context);
}
}
}

View File

@@ -1,71 +0,0 @@
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.applications.defaultapps;
import android.content.ComponentName;
import android.content.Context;
import android.telephony.TelephonyManager;
import com.android.internal.telephony.SmsApplication;
import com.android.settingslib.applications.DefaultAppInfo;
import java.util.Collection;
public class DefaultSmsPreferenceController extends DefaultAppPreferenceController {
public DefaultSmsPreferenceController(Context context) {
super(context);
}
@Override
public boolean isAvailable() {
boolean isRestrictedUser = mUserManager.getUserInfo(mUserId).isRestricted();
TelephonyManager tm =
(TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
return !isRestrictedUser && tm.isSmsCapable();
}
@Override
public String getPreferenceKey() {
return "default_sms_app";
}
@Override
protected DefaultAppInfo getDefaultAppInfo() {
final ComponentName app = SmsApplication.getDefaultSmsApplication(mContext, true);
if (app != null) {
return new DefaultAppInfo(mContext, mPackageManager, mUserId, app);
}
return null;
}
public static boolean hasSmsPreference(String pkg, Context context) {
Collection<SmsApplication.SmsApplicationData> smsApplications =
SmsApplication.getApplicationCollection(context);
for (SmsApplication.SmsApplicationData data : smsApplications) {
if (data.mPackageName.equals(pkg)) {
return true;
}
}
return false;
}
public static boolean isSmsDefault(String pkg, Context context) {
ComponentName appName = SmsApplication.getDefaultSmsApplication(context, true);
return appName != null && appName.getPackageName().equals(pkg);
}
}

View File

@@ -1,50 +0,0 @@
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.applications.defaultapps;
import android.content.Context;
import android.os.UserHandle;
import com.android.settings.Utils;
public class DefaultWorkBrowserPreferenceController extends DefaultBrowserPreferenceController {
public static final String KEY = "work_default_browser";
private final UserHandle mUserHandle;
public DefaultWorkBrowserPreferenceController(Context context) {
super(context);
mUserHandle = Utils.getManagedProfile(mUserManager);
if (mUserHandle != null) {
mUserId = mUserHandle.getIdentifier();
}
}
@Override
public String getPreferenceKey() {
return KEY;
}
@Override
public boolean isAvailable() {
if (mUserHandle == null) {
return false;
}
return super.isAvailable();
}
}

View File

@@ -1,49 +0,0 @@
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.applications.defaultapps;
import android.content.Context;
import android.os.UserHandle;
import com.android.settings.Utils;
public class DefaultWorkPhonePreferenceController extends DefaultPhonePreferenceController {
public static final String KEY = "work_default_phone_app";
private final UserHandle mUserHandle;
public DefaultWorkPhonePreferenceController(Context context) {
super(context);
mUserHandle = Utils.getManagedProfile(mUserManager);
if (mUserHandle != null) {
mUserId = mUserHandle.getIdentifier();
}
}
@Override
public boolean isAvailable() {
if (mUserHandle == null) {
return false;
}
return super.isAvailable();
}
@Override
public String getPreferenceKey() {
return KEY;
}
}

View File

@@ -92,7 +92,6 @@ import com.android.settings.applications.AppStateUsageBridge;
import com.android.settings.applications.AppStateUsageBridge.UsageState;
import com.android.settings.applications.AppStateWriteSettingsBridge;
import com.android.settings.applications.AppStorageSettings;
import com.android.settings.applications.DefaultAppSettings;
import com.android.settings.applications.InstalledAppCounter;
import com.android.settings.applications.UsageAccessDetails;
import com.android.settings.applications.appinfo.AppInfoDashboardFragment;
@@ -704,12 +703,9 @@ public class ManageApplications extends InstrumentedFragment
.setResultListener(this, ADVANCED_SETTINGS)
.launch();
} else {
new SubSettingLauncher(getContext())
.setDestination(DefaultAppSettings.class.getName())
.setTitleRes(R.string.configure_apps)
.setSourceMetricsCategory(getMetricsCategory())
.setResultListener(this, ADVANCED_SETTINGS)
.launch();
Intent intent = new Intent(
android.provider.Settings.ACTION_MANAGE_DEFAULT_APPS_SETTINGS);
startActivityForResult(intent, ADVANCED_SETTINGS);
}
return true;
default:

View File

@@ -34,7 +34,6 @@ import com.android.settings.accounts.AccountSyncSettings;
import com.android.settings.accounts.ChooseAccountFragment;
import com.android.settings.accounts.ManagedProfileSettings;
import com.android.settings.applications.AppAndNotificationDashboardFragment;
import com.android.settings.applications.DefaultAppSettings;
import com.android.settings.applications.ProcessStatsSummary;
import com.android.settings.applications.ProcessStatsUi;
import com.android.settings.applications.UsageAccessDetails;
@@ -247,7 +246,6 @@ public class SettingsGateway {
DrawOverlayDetails.class.getName(),
WriteSettingsDetails.class.getName(),
ExternalSourcesDetails.class.getName(),
DefaultAppSettings.class.getName(),
WallpaperTypeSettings.class.getName(),
VrListenerSettings.class.getName(),
PictureInPictureSettings.class.getName(),
@@ -308,7 +306,6 @@ public class SettingsGateway {
// Home page > Apps & Notifications
Settings.UserSettingsActivity.class.getName(),
Settings.ConfigureNotificationSettingsActivity.class.getName(),
Settings.AdvancedAppsActivity.class.getName(),
Settings.ManageApplicationsActivity.class.getName(),
Settings.PaymentSettingsActivity.class.getName(),
// Home page > Security & screen lock

View File

@@ -23,7 +23,6 @@ import com.android.settings.LegalSettings;
import com.android.settings.accounts.AccountDashboardFragment;
import com.android.settings.accounts.AccountDetailDashboardFragment;
import com.android.settings.applications.AppAndNotificationDashboardFragment;
import com.android.settings.applications.DefaultAppSettings;
import com.android.settings.connecteddevice.AdvancedConnectedDeviceDashboardFragment;
import com.android.settings.connecteddevice.ConnectedDeviceDashboardFragment;
import com.android.settings.development.DevelopmentSettingsDashboardFragment;
@@ -79,8 +78,6 @@ public class DashboardFragmentRegistry {
CategoryKey.CATEGORY_APPS);
PARENT_TO_CATEGORY_KEY_MAP.put(PowerUsageSummary.class.getName(),
CategoryKey.CATEGORY_BATTERY);
PARENT_TO_CATEGORY_KEY_MAP.put(DefaultAppSettings.class.getName(),
CategoryKey.CATEGORY_APPS_DEFAULT);
PARENT_TO_CATEGORY_KEY_MAP.put(DisplaySettings.class.getName(),
CategoryKey.CATEGORY_DISPLAY);
PARENT_TO_CATEGORY_KEY_MAP.put(SoundSettings.class.getName(),

View File

@@ -46,7 +46,6 @@
<bool name="config_show_show_password">false</bool>
<bool name="config_show_trust_agent_click_intent">false</bool>
<bool name="config_show_wallpaper_attribution">false</bool>
<bool name="config_show_default_home">false</bool>
<bool name="config_show_assist_and_voice_input">false</bool>
<bool name="config_show_phone_language">false</bool>
<bool name="config_show_virtual_keyboard_pref">false</bool>

View File

@@ -1,174 +0,0 @@
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.applications;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.UserManager;
import android.telephony.TelephonyManager;
import com.android.settings.R;
import com.android.settings.applications.defaultapps.DefaultBrowserPreferenceController;
import com.android.settings.applications.defaultapps.DefaultPhonePreferenceController;
import com.android.settings.applications.defaultapps.DefaultSmsPreferenceController;
import com.android.settings.dashboard.SummaryLoader;
import com.android.settings.testutils.XmlTestUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.util.ReflectionHelpers;
import java.util.List;
@RunWith(RobolectricTestRunner.class)
public class DefaultAppSettingsTest {
private Context mContext;
private DefaultAppSettings mFragment;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mContext = RuntimeEnvironment.application;
mFragment = new DefaultAppSettings();
mFragment.onAttach(mContext);
}
@Test
public void getPreferenceScreenResId_shouldUseAppDefaultSettingPrefLayout() {
assertThat(mFragment.getPreferenceScreenResId()).isEqualTo(R.xml.app_default_settings);
}
@Test
public void setListening_shouldUpdateSummary() {
final SummaryLoader summaryLoader = mock(SummaryLoader.class);
final DefaultAppSettings.SummaryProvider summaryProvider =
new DefaultAppSettings.SummaryProvider(mContext, summaryLoader);
final DefaultSmsPreferenceController defaultSms =
mock(DefaultSmsPreferenceController.class);
final DefaultBrowserPreferenceController defaultBrowser =
mock(DefaultBrowserPreferenceController.class);
final DefaultPhonePreferenceController defaultPhone =
mock(DefaultPhonePreferenceController.class);
ReflectionHelpers.setField(summaryProvider, "mDefaultSmsPreferenceController", defaultSms);
ReflectionHelpers.setField(
summaryProvider, "mDefaultBrowserPreferenceController", defaultBrowser);
ReflectionHelpers.setField(
summaryProvider, "mDefaultPhonePreferenceController", defaultPhone);
// all available
when(defaultSms.getDefaultAppLabel()).thenReturn("Sms1");
when(defaultBrowser.getDefaultAppLabel()).thenReturn("Browser1");
when(defaultPhone.getDefaultAppLabel()).thenReturn("Phone1");
summaryProvider.setListening(true);
verify(summaryLoader).setSummary(summaryProvider, "Browser1, Phone1, and Sms1");
// 2 available
when(defaultSms.getDefaultAppLabel()).thenReturn(null);
when(defaultBrowser.getDefaultAppLabel()).thenReturn("Browser1");
when(defaultPhone.getDefaultAppLabel()).thenReturn("Phone1");
summaryProvider.setListening(true);
verify(summaryLoader).setSummary(summaryProvider, "Browser1 and Phone1");
when(defaultSms.getDefaultAppLabel()).thenReturn("Sms1");
when(defaultBrowser.getDefaultAppLabel()).thenReturn(null);
when(defaultPhone.getDefaultAppLabel()).thenReturn("Phone1");
summaryProvider.setListening(true);
verify(summaryLoader).setSummary(summaryProvider, "Phone1 and Sms1");
when(defaultSms.getDefaultAppLabel()).thenReturn("Sms1");
when(defaultBrowser.getDefaultAppLabel()).thenReturn("Browser1");
when(defaultPhone.getDefaultAppLabel()).thenReturn(null);
summaryProvider.setListening(true);
verify(summaryLoader).setSummary(summaryProvider, "Browser1 and Sms1");
// 1 available
when(defaultSms.getDefaultAppLabel()).thenReturn(null);
when(defaultBrowser.getDefaultAppLabel()).thenReturn("Browser1");
when(defaultPhone.getDefaultAppLabel()).thenReturn(null);
summaryProvider.setListening(true);
verify(summaryLoader).setSummary(summaryProvider, "Browser1");
when(defaultSms.getDefaultAppLabel()).thenReturn("Sms1");
when(defaultBrowser.getDefaultAppLabel()).thenReturn(null);
when(defaultPhone.getDefaultAppLabel()).thenReturn(null);
summaryProvider.setListening(true);
verify(summaryLoader).setSummary(summaryProvider, "Sms1");
when(defaultSms.getDefaultAppLabel()).thenReturn(null);
when(defaultBrowser.getDefaultAppLabel()).thenReturn(null);
when(defaultPhone.getDefaultAppLabel()).thenReturn("Phone1");
summaryProvider.setListening(true);
verify(summaryLoader).setSummary(summaryProvider, "Phone1");
// None available
when(defaultSms.getDefaultAppLabel()).thenReturn(null);
when(defaultBrowser.getDefaultAppLabel()).thenReturn(null);
when(defaultPhone.getDefaultAppLabel()).thenReturn(null);
summaryProvider.setListening(true);
verify(summaryLoader, never()).setSummary(summaryProvider, eq(anyString()));
}
@Test
public void testNonIndexableKeys_existInXmlLayout() {
final Context context = spy(RuntimeEnvironment.application);
when(context.getApplicationContext()).thenReturn(context);
final UserManager userManager = mock(UserManager.class, RETURNS_DEEP_STUBS);
when(context.getSystemService(Context.USER_SERVICE))
.thenReturn(userManager);
when(userManager.getUserInfo(anyInt()).isRestricted()).thenReturn(true);
when(context.getSystemService(Context.TELEPHONY_SERVICE))
.thenReturn(mock(TelephonyManager.class));
when(context.getPackageManager())
.thenReturn(mock(PackageManager.class));
final List<String> niks = DefaultAppSettings.SEARCH_INDEX_DATA_PROVIDER
.getNonIndexableKeys(context);
final int xmlId = new DefaultAppSettings().getPreferenceScreenResId();
final List<String> keys = XmlTestUtils.getKeysFromPreferenceXml(context, xmlId);
assertThat(keys).containsAllIn(niks);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright (C) 2018 The Android Open Source Project
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -11,36 +11,25 @@
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* limitations under the License
*/
package com.android.settings.applications.defaultapps;
package com.android.settings.applications;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.app.role.RoleManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.provider.Settings;
import androidx.preference.Preference;
import com.android.settings.core.BasePreferenceController;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
@@ -48,13 +37,9 @@ import org.robolectric.RobolectricTestRunner;
import java.util.Collections;
@RunWith(RobolectricTestRunner.class)
public class RolesPreferenceControllerTest {
public class DefaultAppsPreferenceControllerTest {
private static final String PREFERENCE_KEY = "roles";
private static final String DIFFERENT_PREFERENCE_KEY = "different";
private static final String PERMISSION_CONTROLLER_PACKAGE_NAME =
"com.android.permissioncontroller";
private static final String PREFERENCE_KEY = "DefaultApps";
private static final String BROWSER_PACKAGE_NAME = "com.example.browser1";
private static final String DIALER_PACKAGE_NAME = "com.example.dialer1";
@@ -73,6 +58,8 @@ public class RolesPreferenceControllerTest {
@Mock
private ApplicationInfo mSmsApplicationInfo;
private DefaultAppsPreferenceController mPreferenceController;
@Before
public void setUp() throws PackageManager.NameNotFoundException {
MockitoAnnotations.initMocks(this);
@@ -89,80 +76,13 @@ public class RolesPreferenceControllerTest {
when(mSmsApplicationInfo.loadLabel(mPackageManager)).thenReturn("Sms1");
when(mPackageManager.getApplicationInfo(eq(SMS_PACKAGE_NAME), anyInt())).thenReturn(
mSmsApplicationInfo);
mPreferenceController = new DefaultAppsPreferenceController(mContext, PREFERENCE_KEY);
}
@Test
public void getAvailabilityStatus_noPermissionController_shouldReturnUnsupportedOnDevice() {
when(mPackageManager.getPermissionControllerPackageName()).thenReturn(null);
RolesPreferenceController preferenceController = new RolesPreferenceController(mContext,
PREFERENCE_KEY);
assertThat(preferenceController.getAvailabilityStatus())
.isEqualTo(BasePreferenceController.UNSUPPORTED_ON_DEVICE);
}
@Test
public void getAvailabilityStatus_hasPermissionController_shouldReturnAvailableUnsearchable() {
when(mPackageManager.getPermissionControllerPackageName())
.thenReturn(PERMISSION_CONTROLLER_PACKAGE_NAME);
RolesPreferenceController preferenceController = new RolesPreferenceController(mContext,
PREFERENCE_KEY);
assertThat(preferenceController.getAvailabilityStatus())
.isEqualTo(BasePreferenceController.AVAILABLE_UNSEARCHABLE);
}
@Test
public void handlePreferenceTreeClick_differentKey_shouldReturnFalse() {
when(mPackageManager.getPermissionControllerPackageName())
.thenReturn(PERMISSION_CONTROLLER_PACKAGE_NAME);
RolesPreferenceController preferenceController = new RolesPreferenceController(mContext,
PREFERENCE_KEY);
Preference preference = mock(Preference.class);
when(preference.getKey()).thenReturn(DIFFERENT_PREFERENCE_KEY);
assertThat(preferenceController.handlePreferenceTreeClick(preference)).isFalse();
}
@Test
public void handlePreferenceTreeClick_sameKey_shouldReturnTrue() {
when(mPackageManager.getPermissionControllerPackageName())
.thenReturn(PERMISSION_CONTROLLER_PACKAGE_NAME);
RolesPreferenceController preferenceController = new RolesPreferenceController(mContext,
PREFERENCE_KEY);
Preference preference = mock(Preference.class);
when(preference.getKey()).thenReturn(PREFERENCE_KEY);
assertThat(preferenceController.handlePreferenceTreeClick(preference)).isTrue();
}
@Test
public void handlePreferenceTreeClick_noPermissionController_shouldNotStartActivity() {
when(mPackageManager.getPermissionControllerPackageName()).thenReturn(null);
RolesPreferenceController preferenceController = new RolesPreferenceController(mContext,
PREFERENCE_KEY);
Preference preference = mock(Preference.class);
when(preference.getKey()).thenReturn(PREFERENCE_KEY);
preferenceController.handlePreferenceTreeClick(preference);
verify(mContext, never()).startActivity(any(Intent.class));
}
@Test
public void handlePreferenceTreeClick_hasPermissionController_shouldStartActivityWithIntent() {
when(mPackageManager.getPermissionControllerPackageName())
.thenReturn(PERMISSION_CONTROLLER_PACKAGE_NAME);
RolesPreferenceController preferenceController = new RolesPreferenceController(mContext,
PREFERENCE_KEY);
Preference preference = mock(Preference.class);
when(preference.getKey()).thenReturn(PREFERENCE_KEY);
preferenceController.handlePreferenceTreeClick(preference);
ArgumentCaptor<Intent> intent = ArgumentCaptor.forClass(Intent.class);
verify(mContext).startActivity(intent.capture());
assertThat(intent.getValue().getAction())
.isEqualTo(Settings.ACTION_MANAGE_DEFAULT_APPS_SETTINGS);
assertThat(intent.getValue().getPackage()).isEqualTo(PERMISSION_CONTROLLER_PACKAGE_NAME);
public void isAvailable_shouldReturnTrue() {
assertThat(mPreferenceController.isAvailable()).isTrue();
}
@Test
@@ -173,10 +93,8 @@ public class RolesPreferenceControllerTest {
Collections.singletonList(DIALER_PACKAGE_NAME));
when(mRoleManager.getRoleHolders(RoleManager.ROLE_SMS)).thenReturn(
Collections.singletonList(SMS_PACKAGE_NAME));
RolesPreferenceController preferenceController = new RolesPreferenceController(mContext,
PREFERENCE_KEY);
assertThat(preferenceController.getSummary()).isEqualTo("Browser1, Phone1, and Sms1");
assertThat(mPreferenceController.getSummary()).isEqualTo("Browser1, Phone1, and Sms1");
}
@Test
@@ -186,10 +104,8 @@ public class RolesPreferenceControllerTest {
when(mRoleManager.getRoleHolders(RoleManager.ROLE_DIALER)).thenReturn(
Collections.singletonList(DIALER_PACKAGE_NAME));
when(mRoleManager.getRoleHolders(RoleManager.ROLE_SMS)).thenReturn(Collections.emptyList());
RolesPreferenceController preferenceController = new RolesPreferenceController(mContext,
PREFERENCE_KEY);
assertThat(preferenceController.getSummary()).isEqualTo("Browser1 and Phone1");
assertThat(mPreferenceController.getSummary()).isEqualTo("Browser1 and Phone1");
}
@Test
@@ -200,10 +116,8 @@ public class RolesPreferenceControllerTest {
Collections.emptyList());
when(mRoleManager.getRoleHolders(RoleManager.ROLE_SMS)).thenReturn(
Collections.singletonList(SMS_PACKAGE_NAME));
RolesPreferenceController preferenceController = new RolesPreferenceController(mContext,
PREFERENCE_KEY);
assertThat(preferenceController.getSummary()).isEqualTo("Browser1 and Sms1");
assertThat(mPreferenceController.getSummary()).isEqualTo("Browser1 and Sms1");
}
@Test
@@ -214,10 +128,8 @@ public class RolesPreferenceControllerTest {
Collections.singletonList(DIALER_PACKAGE_NAME));
when(mRoleManager.getRoleHolders(RoleManager.ROLE_SMS)).thenReturn(
Collections.singletonList(SMS_PACKAGE_NAME));
RolesPreferenceController preferenceController = new RolesPreferenceController(mContext,
PREFERENCE_KEY);
assertThat(preferenceController.getSummary()).isEqualTo("Phone1 and Sms1");
assertThat(mPreferenceController.getSummary()).isEqualTo("Phone1 and Sms1");
}
@Test
@@ -227,10 +139,8 @@ public class RolesPreferenceControllerTest {
when(mRoleManager.getRoleHolders(RoleManager.ROLE_DIALER)).thenReturn(
Collections.emptyList());
when(mRoleManager.getRoleHolders(RoleManager.ROLE_SMS)).thenReturn(Collections.emptyList());
RolesPreferenceController preferenceController = new RolesPreferenceController(mContext,
PREFERENCE_KEY);
assertThat(preferenceController.getSummary()).isEqualTo("Browser1");
assertThat(mPreferenceController.getSummary()).isEqualTo("Browser1");
}
@Test
@@ -240,10 +150,8 @@ public class RolesPreferenceControllerTest {
when(mRoleManager.getRoleHolders(RoleManager.ROLE_DIALER)).thenReturn(
Collections.singletonList(DIALER_PACKAGE_NAME));
when(mRoleManager.getRoleHolders(RoleManager.ROLE_SMS)).thenReturn(Collections.emptyList());
RolesPreferenceController preferenceController = new RolesPreferenceController(mContext,
PREFERENCE_KEY);
assertThat(preferenceController.getSummary()).isEqualTo("Phone1");
assertThat(mPreferenceController.getSummary()).isEqualTo("Phone1");
}
@Test
@@ -254,10 +162,8 @@ public class RolesPreferenceControllerTest {
Collections.emptyList());
when(mRoleManager.getRoleHolders(RoleManager.ROLE_SMS)).thenReturn(
Collections.singletonList(SMS_PACKAGE_NAME));
RolesPreferenceController preferenceController = new RolesPreferenceController(mContext,
PREFERENCE_KEY);
assertThat(preferenceController.getSummary()).isEqualTo("Sms1");
assertThat(mPreferenceController.getSummary()).isEqualTo("Sms1");
}
@Test
@@ -267,9 +173,7 @@ public class RolesPreferenceControllerTest {
when(mRoleManager.getRoleHolders(RoleManager.ROLE_DIALER)).thenReturn(
Collections.emptyList());
when(mRoleManager.getRoleHolders(RoleManager.ROLE_SMS)).thenReturn(Collections.emptyList());
RolesPreferenceController preferenceController = new RolesPreferenceController(mContext,
PREFERENCE_KEY);
assertThat(preferenceController.getSummary()).isNull();
assertThat(mPreferenceController.getSummary()).isNull();
}
}

View File

@@ -1,77 +0,0 @@
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.applications.defaultapps;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.UserManager;
import com.android.settings.testutils.FakeFeatureFactory;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.util.ReflectionHelpers;
@RunWith(RobolectricTestRunner.class)
public class DefaultBrowserPickerTest {
private static final String TEST_APP_KEY = "";
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private Activity mActivity;
@Mock
private UserManager mUserManager;
@Mock
private PackageManager mPackageManager;
private DefaultBrowserPicker mPicker;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
FakeFeatureFactory.setupForTest();
when(mActivity.getSystemService(Context.USER_SERVICE)).thenReturn(mUserManager);
mPicker = new DefaultBrowserPicker();
mPicker.onAttach(mActivity);
ReflectionHelpers.setField(mPicker, "mPm", mPackageManager);
}
@Test
public void setDefaultAppKey_shouldUpdateDefaultBrowser() {
mPicker.setDefaultKey(TEST_APP_KEY);
verify(mPackageManager).setDefaultBrowserPackageNameAsUser(eq(TEST_APP_KEY), anyInt());
}
@Test
public void getDefaultAppKey_shouldReturnDefaultBrowser() {
mPicker.getDefaultKey();
verify(mPackageManager).getDefaultBrowserPackageNameAsUser(anyInt());
}
}

View File

@@ -1,231 +0,0 @@
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.applications.defaultapps;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.os.UserManager;
import androidx.preference.Preference;
import com.android.settings.R;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.util.ReflectionHelpers;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@RunWith(RobolectricTestRunner.class)
public class DefaultBrowserPreferenceControllerTest {
@Mock
private Context mContext;
@Mock
private UserManager mUserManager;
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private PackageManager mPackageManager;
private DefaultBrowserPreferenceController mController;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
when(mContext.getSystemService(Context.USER_SERVICE)).thenReturn(mUserManager);
mController = new DefaultBrowserPreferenceController(mContext);
ReflectionHelpers.setField(mController, "mPackageManager", mPackageManager);
}
@Test
public void isAvailable_noBrowser_shouldReturnFalse() {
when(mPackageManager.queryIntentActivitiesAsUser(any(Intent.class), anyInt(), anyInt()))
.thenReturn(null);
assertThat(mController.isAvailable()).isFalse();
}
@Test
public void isAvailable_hasBrowser_shouldReturnTrue() {
when(mPackageManager.queryIntentActivitiesAsUser(any(Intent.class), anyInt(), anyInt()))
.thenReturn(Collections.singletonList(createResolveInfo("com.test.pkg")));
assertThat(mController.isAvailable()).isTrue();
}
@Test
public void getSoleAppLabel_hasNoApp_shouldNotReturnLabel() {
when(mPackageManager.queryIntentActivitiesAsUser(any(Intent.class), anyInt(), anyInt()))
.thenReturn(null);
final Preference pref = mock(Preference.class);
mController.updateState(pref);
verify(pref).setSummary(R.string.app_list_preference_none);
}
@Test
public void getDefaultAppLabel_hasAppWithMultipleResolvedInfo_shouldReturnLabel()
throws NameNotFoundException {
DefaultBrowserPreferenceController spyController = spy(mController);
doReturn(null).when(spyController).getDefaultAppIcon();
final List<ResolveInfo> resolveInfos = new ArrayList<>();
final CharSequence PACKAGE_NAME = "com.test.package";
// This ResolveInfo will return a non-null label from loadLabel.
final ResolveInfo info1 = createResolveInfo(PACKAGE_NAME.toString());
info1.nonLocalizedLabel = PACKAGE_NAME;
resolveInfos.add(info1);
// This ResolveInfo will return a null label from loadLabel.
final ResolveInfo info2 = createResolveInfo(PACKAGE_NAME.toString());
resolveInfos.add(info2);
when(mPackageManager.getDefaultBrowserPackageNameAsUser(anyInt())).thenReturn(null);
when(mPackageManager.queryIntentActivitiesAsUser(any(Intent.class), anyInt(), anyInt()))
.thenReturn(resolveInfos);
when(mPackageManager.getApplicationInfoAsUser(
eq(PACKAGE_NAME.toString()), anyInt(), anyInt()))
.thenReturn(createApplicationInfo(PACKAGE_NAME.toString()));
assertThat(spyController.getDefaultAppLabel()).isEqualTo(PACKAGE_NAME);
}
@Test
public void getDefaultApp_shouldGetDefaultBrowserPackage() {
mController.getDefaultAppInfo();
verify(mPackageManager).getDefaultBrowserPackageNameAsUser(anyInt());
}
@Test
public void getDefaultApp_shouldGetApplicationInfoAsUser() throws NameNotFoundException {
final String PACKAGE_NAME = "com.test.package";
when(mPackageManager.getDefaultBrowserPackageNameAsUser(anyInt())).thenReturn(PACKAGE_NAME);
mController.getDefaultAppInfo();
verify(mPackageManager).getApplicationInfoAsUser(eq(PACKAGE_NAME), anyInt(), anyInt());
}
@Test
public void isBrowserDefault_onlyApp_shouldReturnTrue() {
when(mPackageManager.getDefaultBrowserPackageNameAsUser(anyInt())).thenReturn(null);
final List<ResolveInfo> resolveInfos = new ArrayList<>();
final String PACKAGE_ONE = "pkg";
resolveInfos.add(createResolveInfo(PACKAGE_ONE));
when(mPackageManager.queryIntentActivitiesAsUser(any(Intent.class), anyInt(), anyInt()))
.thenReturn(resolveInfos);
assertThat(mController.isBrowserDefault("pkg", 0)).isTrue();
}
@Test
public void getCandidates_shouldNotIncludeDuplicatePackageName() throws NameNotFoundException {
final List<ResolveInfo> resolveInfos = new ArrayList<>();
final String PACKAGE_ONE = "com.first.package";
final String PACKAGE_TWO = "com.second.package";
resolveInfos.add(createResolveInfo(PACKAGE_ONE));
resolveInfos.add(createResolveInfo(PACKAGE_TWO));
resolveInfos.add(createResolveInfo(PACKAGE_ONE));
resolveInfos.add(createResolveInfo(PACKAGE_TWO));
when(mPackageManager.queryIntentActivitiesAsUser(any(Intent.class), anyInt(), anyInt()))
.thenReturn(resolveInfos);
when(mPackageManager.getApplicationInfoAsUser(eq(PACKAGE_ONE), anyInt(), anyInt()))
.thenReturn(createApplicationInfo(PACKAGE_ONE));
when(mPackageManager.getApplicationInfoAsUser(eq(PACKAGE_TWO), anyInt(), anyInt()))
.thenReturn(createApplicationInfo(PACKAGE_TWO));
final List<ResolveInfo> defaultBrowserInfo =
DefaultBrowserPreferenceController.getCandidates(mPackageManager, 0 /* userId */);
assertThat(defaultBrowserInfo.size()).isEqualTo(2);
}
@Test
public void getCandidates_shouldQueryActivityWithMatchAll() {
DefaultBrowserPreferenceController.getCandidates(mPackageManager, 0 /* userId */);
verify(mPackageManager).queryIntentActivitiesAsUser(
any(Intent.class), eq(PackageManager.MATCH_ALL), eq(0) /* userId */);
}
@Test
public void getOnlyAppIcon_shouldGetApplicationInfoAsUser() throws NameNotFoundException {
final List<ResolveInfo> resolveInfos = new ArrayList<>();
final String PACKAGE_NAME = "com.test.package";
resolveInfos.add(createResolveInfo(PACKAGE_NAME));
when(mPackageManager.queryIntentActivitiesAsUser(any(Intent.class), anyInt(), anyInt()))
.thenReturn(resolveInfos);
when(mContext.getPackageManager()).thenReturn(mPackageManager);
when(mContext.getSystemService(UserManager.class)).thenReturn(mUserManager);
when(mContext.getResources()).thenReturn(mock(Resources.class));
mController.getOnlyAppIcon();
verify(mPackageManager).getApplicationInfoAsUser(
eq(PACKAGE_NAME), eq(0) /* flags */, eq(0) /* userId */);
}
@Test
public void hasBrowserPreference_shouldQueryIntentActivitiesAsUser() {
when(mContext.getPackageManager()).thenReturn(mPackageManager);
DefaultBrowserPreferenceController
.hasBrowserPreference("com.test.package", mContext, 0 /* userId */);
verify(mPackageManager).queryIntentActivitiesAsUser(
any(Intent.class), eq(0) /* flags */, eq(0) /* userId */);
}
private ResolveInfo createResolveInfo(String packageName) {
final ResolveInfo info = new ResolveInfo();
info.handleAllWebDataURI = true;
info.activityInfo = new ActivityInfo();
info.activityInfo.packageName = packageName;
info.activityInfo.applicationInfo = createApplicationInfo(packageName);
return info;
}
private ApplicationInfo createApplicationInfo(String packageName) {
final ApplicationInfo info = new ApplicationInfo();
info.packageName = packageName;
return info;
}
}

View File

@@ -1,97 +0,0 @@
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.applications.defaultapps;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.app.Activity;
import android.app.role.RoleManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.UserHandle;
import android.os.UserManager;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.shadows.ShadowApplication;
import org.robolectric.util.ReflectionHelpers;
import java.util.Arrays;
import java.util.concurrent.Executor;
import java.util.function.Consumer;
@RunWith(RobolectricTestRunner.class)
public class DefaultEmergencyPickerTest {
private static final String TAG = DefaultEmergencyPickerTest.class.getSimpleName();
private static final String TEST_APP_KEY = "test_app";
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private Activity mActivity;
@Mock
private UserManager mUserManager;
@Mock
private PackageManager mPackageManager;
@Mock
private RoleManager mRoleManager;
private DefaultEmergencyPicker mPicker;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
ShadowApplication shadowApplication = ShadowApplication.getInstance();
shadowApplication.setSystemService(Context.ROLE_SERVICE, mRoleManager);
when(mActivity.getSystemService(Context.USER_SERVICE)).thenReturn(mUserManager);
mPicker = spy(new DefaultEmergencyPicker());
mPicker.onAttach(mActivity);
ReflectionHelpers.setField(mPicker, "mPm", mPackageManager);
when(mPicker.getContext()).thenReturn(RuntimeEnvironment.application);
}
@Test
public void setDefaultAppKey_shouldUpdateDefault() {
mPicker.setDefaultKey(TEST_APP_KEY);
verify(mRoleManager).addRoleHolderAsUser(
eq(RoleManager.ROLE_EMERGENCY),
eq(TEST_APP_KEY),
eq(0),
any(UserHandle.class),
any(Executor.class),
any(Consumer.class));
}
@Test
public void getDefaultAppKey_shouldReturnDefault() {
when(mRoleManager.getRoleHolders(RoleManager.ROLE_EMERGENCY))
.thenReturn(Arrays.asList(TEST_APP_KEY));
assertThat(mPicker.getDefaultKey()).isEqualTo(TEST_APP_KEY);
}
}

View File

@@ -1,168 +0,0 @@
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.applications.defaultapps;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.app.Activity;
import android.app.AppOpsManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.content.pm.UserInfo;
import android.os.Build;
import android.os.UserManager;
import com.android.settings.testutils.FakeFeatureFactory;
import com.android.settingslib.applications.DefaultAppInfo;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.util.ReflectionHelpers;
import java.util.ArrayList;
import java.util.List;
@RunWith(RobolectricTestRunner.class)
public class DefaultHomePickerTest {
private static final String TEST_APP_KEY = "com.android.settings/DefaultEmergencyPickerTest";
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private Activity mActivity;
@Mock
private UserManager mUserManager;
@Mock
private AppOpsManager mAppOpsManager;
@Mock
private PackageManager mPackageManager;
private Context mContext;
private DefaultHomePicker mPicker;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
FakeFeatureFactory.setupForTest();
when(mActivity.getSystemService(Context.USER_SERVICE)).thenReturn(mUserManager);
when(mActivity.getSystemService(Context.APP_OPS_SERVICE)).thenReturn(mAppOpsManager);
when(mActivity.getApplicationContext()).thenReturn(RuntimeEnvironment.application);
mPicker = spy(new DefaultHomePicker());
mPicker.onAttach((Context) mActivity);
ReflectionHelpers.setField(mPicker, "mPm", mPackageManager);
mContext = spy(RuntimeEnvironment.application);
doReturn(mContext).when(mPicker).getContext();
}
@Test
public void setDefaultAppKey_shouldUpdateDefault() {
assertThat(mPicker.setDefaultKey(TEST_APP_KEY)).isTrue();
verify(mPackageManager).replacePreferredActivity(any(IntentFilter.class),
anyInt(), any(ComponentName[].class), any(ComponentName.class));
verify(mContext).startActivity(any());
}
@Test
public void getDefaultAppKey_shouldReturnDefault() {
final ComponentName cn = mock(ComponentName.class);
when(mPackageManager.getHomeActivities(anyList())).thenReturn(cn);
mPicker.getDefaultKey();
verify(cn).flattenToString();
}
@Test
public void getCandidates_allLaunchersAvailableIfNoManagedProfile() {
addLaunchers();
List<DefaultAppInfo> candidates = mPicker.getCandidates();
assertThat(candidates.size()).isEqualTo(2);
assertThat(candidates.get(0).summary).isNull();
assertThat(candidates.get(0).enabled).isTrue();
assertThat(candidates.get(1).summary).isNull();
assertThat(candidates.get(1).enabled).isTrue();
}
@Test
public void getCandidates_onlyLollipopPlusLaunchersAvailableIfManagedProfile() {
List<UserInfo> profiles = new ArrayList<>();
profiles.add(new UserInfo(/*id=*/ 10, "TestUserName", UserInfo.FLAG_MANAGED_PROFILE));
when(mUserManager.getProfiles(anyInt())).thenReturn(profiles);
addLaunchers();
List<DefaultAppInfo> candidates = mPicker.getCandidates();
assertThat(candidates.size()).isEqualTo(2);
DefaultAppInfo lollipopPlusLauncher = candidates.get(0);
assertThat(lollipopPlusLauncher.summary).isNull();
assertThat(lollipopPlusLauncher.enabled).isTrue();
DefaultAppInfo preLollipopLauncher = candidates.get(1);
assertThat(preLollipopLauncher.summary).isNotNull();
assertThat(preLollipopLauncher.enabled).isFalse();
}
private ResolveInfo createLauncher(
String packageName, String className, int targetSdk) throws NameNotFoundException {
ResolveInfo launcher = new ResolveInfo();
launcher.activityInfo = new ActivityInfo();
launcher.activityInfo.packageName = packageName;
launcher.activityInfo.name = className;
ApplicationInfo launcherAppInfo = new ApplicationInfo();
launcherAppInfo.targetSdkVersion = targetSdk;
when(mPackageManager.getApplicationInfo(eq(launcher.activityInfo.packageName), anyInt()))
.thenReturn(launcherAppInfo);
return launcher;
}
private void addLaunchers() {
doAnswer(invocation -> {
// The result of this method is stored in the first parameter...
List<ResolveInfo> parameter = (List<ResolveInfo>) invocation.getArguments()[0];
parameter.add(createLauncher(
"package.1", "LollipopPlusLauncher", Build.VERSION_CODES.LOLLIPOP));
parameter.add(createLauncher(
"package.2", "PreLollipopLauncher", Build.VERSION_CODES.KITKAT));
return null;
})
.when(mPackageManager).getHomeActivities(anyList());
}
}

View File

@@ -1,170 +0,0 @@
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.applications.defaultapps;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.UserManager;
import androidx.preference.Preference;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
import org.robolectric.util.ReflectionHelpers;
@RunWith(RobolectricTestRunner.class)
public class DefaultHomePreferenceControllerTest {
private static final String TEST_PACKAGE = "test.pkg";
private static final String TEST_CLASS = "class";
@Mock
private UserManager mUserManager;
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private PackageManager mPackageManager;
private Context mContext;
private DefaultHomePreferenceController mController;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mContext = spy(RuntimeEnvironment.application);
when(mContext.getSystemService(Context.USER_SERVICE)).thenReturn(mUserManager);
mController = spy(new DefaultHomePreferenceController(mContext));
ReflectionHelpers.setField(mController, "mPackageManager", mPackageManager);
}
@Test
public void testDefaultHome_byDefault_shouldBeShown() {
assertThat(mController.isAvailable()).isTrue();
}
@Test
@Config(qualifiers = "mcc999")
public void testDefaultHome_ifDisabled_shouldNotBeShown() {
assertThat(mController.isAvailable()).isFalse();
}
@Test
public void getDefaultApp_shouldGetDefaultBrowserPackage() {
assertThat(mController.getDefaultAppInfo()).isNotNull();
verify(mPackageManager).getHomeActivities(anyList());
}
@Test
public void getDefaultApp_noDefaultHome_shouldReturnNull() {
when(mPackageManager.getHomeActivities(anyList())).thenReturn(null);
assertThat(mController.getDefaultAppInfo()).isNull();
}
@Test
public void updateState_noDefaultApp_shouldAskPackageManagerForOnlyApp() {
when(mPackageManager.getHomeActivities(anyList())).thenReturn(null);
mController.updateState(mock(Preference.class));
verify(mPackageManager, atLeastOnce()).getHomeActivities(anyList());
}
@Test
public void testIsHomeDefault_noDefaultSet_shouldReturnTrue() {
when(mPackageManager.getHomeActivities(anyList())).thenReturn(null);
assertThat(DefaultHomePreferenceController.isHomeDefault(TEST_PACKAGE, mPackageManager))
.isTrue();
}
@Test
public void testIsHomeDefault_defaultSetToPkg_shouldReturnTrue() {
final String pkgName = TEST_PACKAGE;
final ComponentName defaultHome = new ComponentName(pkgName, TEST_CLASS);
when(mPackageManager.getHomeActivities(anyList())).thenReturn(defaultHome);
assertThat(DefaultHomePreferenceController.isHomeDefault(pkgName, mPackageManager))
.isTrue();
}
@Test
public void testIsHomeDefault_defaultSetToOtherPkg_shouldReturnFalse() {
final String pkgName = TEST_PACKAGE;
final ComponentName defaultHome = new ComponentName("not" + pkgName, TEST_CLASS);
when(mPackageManager.getHomeActivities(anyList())).thenReturn(defaultHome);
assertThat(DefaultHomePreferenceController.isHomeDefault(pkgName, mPackageManager))
.isFalse();
}
@Test
public void testGetSettingIntent_homeHasNoSetting_shouldNotReturnSettingIntent() {
when(mPackageManager.getHomeActivities(anyList()))
.thenReturn(new ComponentName(TEST_PACKAGE, TEST_CLASS));
when(mPackageManager.resolveActivity(any(Intent.class), anyInt()))
.thenReturn(null);
assertThat(mController.getSettingIntent(mController.getDefaultAppInfo())).isNull();
}
@Test
public void testGetSettingIntent_homeHasOneSetting_shouldReturnSettingIntent() {
when(mPackageManager.getHomeActivities(anyList()))
.thenReturn(new ComponentName(TEST_PACKAGE, TEST_CLASS));
final ResolveInfo info = mock(ResolveInfo.class);
info.activityInfo = mock(ActivityInfo.class);
info.activityInfo.name = TEST_CLASS;
info.activityInfo.applicationInfo = mock(ApplicationInfo.class);
info.activityInfo.applicationInfo.packageName = TEST_PACKAGE;
when(mPackageManager.resolveActivity(any(Intent.class), anyInt()))
.thenReturn(info);
Intent intent = mController.getSettingIntent(mController.getDefaultAppInfo());
assertThat(intent).isNotNull();
assertThat(intent.getPackage()).isEqualTo(TEST_PACKAGE);
}
@Test
public void testGetSettingIntent_noDefauldHome_shouldReturnNull() {
when(mPackageManager.getHomeActivities(anyList())).thenReturn(null);
assertThat(mController.getSettingIntent(mController.getDefaultAppInfo())).isNull();
}
}

View File

@@ -1,104 +0,0 @@
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.applications.defaultapps;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.UserManager;
import com.android.settings.fuelgauge.BatteryUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.util.ReflectionHelpers;
@RunWith(RobolectricTestRunner.class)
public class DefaultPhonePickerTest {
private static final String TEST_APP_KEY = "com.android.settings/PickerTest";
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private Activity mActivity;
@Mock
private UserManager mUserManager;
@Mock
private DefaultPhonePicker.DefaultKeyUpdater mDefaultKeyUpdater;
@Mock
private PackageManager mPackageManager;
@Mock
private BatteryUtils mBatteryUtils;
private DefaultPhonePicker mPicker;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
when(mActivity.getSystemService(Context.USER_SERVICE)).thenReturn(mUserManager);
when(mActivity.getSystemService(Context.TELECOM_SERVICE)).thenReturn(null);
mPicker = spy(new DefaultPhonePicker());
mPicker.onAttach(mActivity);
ReflectionHelpers.setField(mPicker, "mPm", mPackageManager);
ReflectionHelpers.setField(mPicker, "mDefaultKeyUpdater", mDefaultKeyUpdater);
ReflectionHelpers.setField(mPicker, "mBatteryUtils", mBatteryUtils);
doReturn(RuntimeEnvironment.application).when(mPicker).getContext();
}
@Test
public void getSystemDefaultPackage_shouldAskDefaultKeyUpdater() {
mPicker.getSystemDefaultKey();
verify(mDefaultKeyUpdater).getSystemDialerPackage();
}
@Test
public void setDefaultAppKey_shouldUpdateDefault() {
mPicker.setDefaultKey(TEST_APP_KEY);
verify(mDefaultKeyUpdater)
.setDefaultDialerApplication(any(Context.class), eq(TEST_APP_KEY), anyInt());
}
@Test
public void getDefaultAppKey_shouldReturnDefault() {
mPicker.getDefaultKey();
verify(mDefaultKeyUpdater).getDefaultDialerApplication(any(Context.class), anyInt());
}
@Test
public void setDefaultKey_shouldUnrestrictApp() {
mPicker.setDefaultKey(TEST_APP_KEY);
verify(mBatteryUtils).clearForceAppStandby(TEST_APP_KEY);
}
}

View File

@@ -1,94 +0,0 @@
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.applications.defaultapps;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.UserManager;
import com.android.settings.fuelgauge.BatteryUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.util.ReflectionHelpers;
@RunWith(RobolectricTestRunner.class)
public class DefaultSmsPickerTest {
private static final String TEST_APP_KEY = "com.android.settings/PickerTest";
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private Activity mActivity;
@Mock
private UserManager mUserManager;
@Mock
private DefaultSmsPicker.DefaultKeyUpdater mDefaultKeyUpdater;
@Mock
private PackageManager mPackageManager;
@Mock
private BatteryUtils mBatteryUtils;
private DefaultSmsPicker mPicker;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
when(mActivity.getSystemService(Context.USER_SERVICE)).thenReturn(mUserManager);
mPicker = spy(new DefaultSmsPicker());
mPicker.onAttach(mActivity);
ReflectionHelpers.setField(mPicker, "mPm", mPackageManager);
ReflectionHelpers.setField(mPicker, "mDefaultKeyUpdater", mDefaultKeyUpdater);
ReflectionHelpers.setField(mPicker, "mBatteryUtils", mBatteryUtils);
doReturn(RuntimeEnvironment.application).when(mPicker).getContext();
}
@Test
public void setDefaultAppKey_shouldUpdateDefault() {
mPicker.setDefaultKey(TEST_APP_KEY);
verify(mDefaultKeyUpdater).setDefaultApplication(any(Context.class), eq(TEST_APP_KEY));
}
@Test
public void getDefaultAppKey_shouldReturnDefault() {
mPicker.getDefaultKey();
verify(mDefaultKeyUpdater).getDefaultApplication(any(Context.class));
}
@Test
public void setDefaultKey_shouldUnrestrictApp() {
mPicker.setDefaultKey(TEST_APP_KEY);
verify(mBatteryUtils).clearForceAppStandby(TEST_APP_KEY);
}
}