android限制安装包来源,Android系统设置settings应用学习(一)--允许未知来源应用安装...

settings,是Android系统应用--设置的源代码,包名称为:com.android.settings

安全设置代码:SecuritySettings.java

/*

* Copyright (C) 2007 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;

import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;

import android.app.Activity;

import android.app.AlertDialog;

import android.app.admin.DevicePolicyManager;

import android.content.Context;

import android.content.DialogInterface;

import android.content.Intent;

import android.os.Bundle;

import android.os.Vibrator;

import android.preference.CheckBoxPreference;

import android.preference.ListPreference;

import android.preference.Preference;

import android.preference.Preference.OnPreferenceChangeListener;

import android.preference.PreferenceGroup;

import android.preference.PreferenceScreen;

import android.provider.Settings;

import android.provider.Telephony.SIMInfo;

import android.security.KeyStore;

import android.telephony.TelephonyManager;

import android.util.Log;

import com.android.internal.telephony.Phone;

import com.android.internal.widget.LockPatternUtils;

import com.android.settings.gemini.SimListEntrance;

import com.mediatek.xlog.Xlog;

import java.util.ArrayList;

import java.util.List;

import com.mediatek.featureoption.FeatureOption;

/**

* Gesture lock pattern settings.

*/

public class SecuritySettings extends SettingsPreferenceFragment

implements OnPreferenceChangeListener, DialogInterface.OnClickListener {

private static final String TAG = "SecuritySettings";

// Lock Settings

private static final String KEY_UNLOCK_SET_OR_CHANGE = "unlock_set_or_change";

private static final String KEY_BIOMETRIC_WEAK_IMPROVE_MATCHING =

"biometric_weak_improve_matching";

private static final String KEY_LOCK_ENABLED = "lockenabled";

private static final String KEY_VISIBLE_PATTERN = "visiblepattern";

private static final String KEY_TACTILE_FEEDBACK_ENABLED = "unlock_tactile_feedback";

private static final String KEY_SECURITY_CATEGORY = "security_category";

private static final String KEY_LOCK_AFTER_TIMEOUT = "lock_after_timeout";

private static final int SET_OR_CHANGE_LOCK_METHOD_REQUEST = 123;

private static final int CONFIRM_EXISTING_FOR_BIOMETRIC_IMPROVE_REQUEST = 124;

// Misc Settings

private static final String KEY_SIM_LOCK = "sim_lock";

private static final String KEY_SIM_LOCK_PREF = "sim_lock_pref";

private static final String KEY_SHOW_PASSWORD = "show_password";

private static final String KEY_RESET_CREDENTIALS = "reset_credentials";

private static final String KEY_TOGGLE_INSTALL_APPLICATIONS = "toggle_install_applications";

DevicePolicyManager mDPM;

private ChooseLockSettingsHelper mChooseLockSettingsHelper;

private LockPatternUtils mLockPatternUtils;

private ListPreference mLockAfter;

private CheckBoxPreference mVisiblePattern;

private CheckBoxPreference mTactileFeedback;

private CheckBoxPreference mShowPassword;

private Preference mResetCredentials;

private CheckBoxPreference mToggleAppInstallation;

private DialogInterface mWarnInstallApps;

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

mLockPatternUtils = new LockPatternUtils(getActivity());

mDPM = (DevicePolicyManager)getSystemService(Context.DEVICE_POLICY_SERVICE);

mChooseLockSettingsHelper = new ChooseLockSettingsHelper(getActivity());

}

private PreferenceScreen createPreferenceHierarchy() {

PreferenceScreen root = getPreferenceScreen();

if (root != null) {

root.removeAll();

}

addPreferencesFromResource(R.xml.security_settings);

root = getPreferenceScreen();

// Add options for lock/unlock screen

int resid = 0;

if (!mLockPatternUtils.isSecure()) {

if (mLockPatternUtils.isLockScreenDisabled()) {

resid = R.xml.security_settings_lockscreen;

} else {

resid = R.xml.security_settings_chooser;

}

} else if (mLockPatternUtils.usingBiometricWeak() &&

mLockPatternUtils.isBiometricWeakInstalled()) {

resid = R.xml.security_settings_biometric_weak;

} else {

switch (mLockPatternUtils.getKeyguardStoredPasswordQuality()) {

case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING:

resid = R.xml.security_settings_pattern;

break;

case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:

resid = R.xml.security_settings_pin;

break;

case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC:

case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC:

case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX:

resid = R.xml.security_settings_password;

break;

}

}

addPreferencesFromResource(resid);

// Add options for device encryption

Xlog.d(TAG,"FeatureOption.MTK_EMMC_SUPPORT="+FeatureOption.MTK_EMMC_SUPPORT);

if(FeatureOption.MTK_EMMC_SUPPORT) {

// Add options for device encryption

DevicePolicyManager dpm =

(DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);

switch (dpm.getStorageEncryptionStatus()) {

case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE:

// The device is currently encrypted.

addPreferencesFromResource(R.xml.security_settings_encrypted);

break;

case DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE:

// This device supports encryption but isn't encrypted.

addPreferencesFromResource(R.xml.security_settings_unencrypted);

break;

}

}

// lock after preference

mLockAfter = (ListPreference) root.findPreference(KEY_LOCK_AFTER_TIMEOUT);

if (mLockAfter != null) {

setupLockAfterPreference();

updateLockAfterPreferenceSummary();

}

// visible pattern

mVisiblePattern = (CheckBoxPreference) root.findPreference(KEY_VISIBLE_PATTERN);

// don't display visible pattern if biometric and backup is not pattern

if (resid == R.xml.security_settings_biometric_weak &&

mLockPatternUtils.getKeyguardStoredPasswordQuality() !=

DevicePolicyManager.PASSWORD_QUALITY_SOMETHING) {

PreferenceGroup securityCategory = (PreferenceGroup)

root.findPreference(KEY_SECURITY_CATEGORY);

if (securityCategory != null && mVisiblePattern != null) {

securityCategory.removePreference(root.findPreference(KEY_VISIBLE_PATTERN));

}

}

// tactile feedback. Should be common to all unlock preference screens.

mTactileFeedback = (CheckBoxPreference) root.findPreference(KEY_TACTILE_FEEDBACK_ENABLED);

if (!((Vibrator) getSystemService(Context.VIBRATOR_SERVICE)).hasVibrator()) {

PreferenceGroup securityCategory = (PreferenceGroup)

root.findPreference(KEY_SECURITY_CATEGORY);

if (securityCategory != null && mTactileFeedback != null) {

securityCategory.removePreference(mTactileFeedback);

}

}

// Append the rest of the settings

addPreferencesFromResource(R.xml.security_settings_misc);

// Do not display SIM lock for CDMA phone

TelephonyManager tm = TelephonyManager.getDefault();

if ((TelephonyManager.PHONE_TYPE_CDMA == tm.getCurrentPhoneType()) &&

(tm.getLteOnCdmaMode() != Phone.LTE_ON_CDMA_TRUE)) {

root.removePreference(root.findPreference(KEY_SIM_LOCK));

}else{

//Preference simLockPreferences = root.findPreference(KEY_SIM_LOCK);

Preference simLockPref = root.findPreference(KEY_SIM_LOCK_PREF);

List simList = SIMInfo.getInsertedSIMList(getActivity());

int nSimNum = simList.size();

if (nSimNum == 0) {

Xlog.d(TAG,"No sim found");

simLockPref.setEnabled(false);

}else if (nSimNum == 1) {

SIMInfo simInfo = simList.get(0);

Xlog.d(TAG,"Only one Sim inserted");

if (simInfo != null) {

Intent intent = new Intent();

intent.setClassName("com.android.settings", "com.android.settings.IccLockSettings");

int slot = SIMInfo.getSlotById(getActivity(), simInfo.mSimId);

intent.putExtra("slotid", simInfo.mSlot);

simLockPref.setIntent(intent);

}

} else if (nSimNum>1) {

Xlog.d(TAG,"two Sims inserted");

simLockPref.getExtras().putInt("type", SimListEntrance.PIN_SETTING_INDEX);

simLockPref.setFragment(SimListEntrance.class.getName());

}

}

// Show password

mShowPassword = (CheckBoxPreference) root.findPreference(KEY_SHOW_PASSWORD);

// Credential storage

mResetCredentials = root.findPreference(KEY_RESET_CREDENTIALS);

mToggleAppInstallation = (CheckBoxPreference) findPreference(

KEY_TOGGLE_INSTALL_APPLICATIONS);

mToggleAppInstallation.setChecked(isNonMarketAppsAllowed());

return root;

}

private boolean isNonMarketAppsAllowed() {

return Settings.Secure.getInt(getContentResolver(),

Settings.Secure.INSTALL_NON_MARKET_APPS, 0) > 0;

}

private void setNonMarketAppsAllowed(boolean enabled) {

// Change the system setting

Settings.Secure.putInt(getContentResolver(), Settings.Secure.INSTALL_NON_MARKET_APPS,

enabled ? 1 : 0);

}

private void warnAppInstallation() {

// TODO: DialogFragment?

mWarnInstallApps = new AlertDialog.Builder(getActivity()).setTitle(

getResources().getString(R.string.error_title))

.setIcon(com.android.internal.R.drawable.ic_dialog_alert)

.setMessage(getResources().getString(R.string.install_all_warning))

.setPositiveButton(android.R.string.yes, this)

.setNegativeButton(android.R.string.no, null)

.show();

}

public void onClick(DialogInterface dialog, int which) {

if (dialog == mWarnInstallApps && which == DialogInterface.BUTTON_POSITIVE) {

setNonMarketAppsAllowed(true);

mToggleAppInstallation.setChecked(true);

}

}

@Override

public void onDestroy() {

super.onDestroy();

if (mWarnInstallApps != null) {

mWarnInstallApps.dismiss();

}

}

private void setupLockAfterPreference() {

// Compatible with pre-Froyo

long currentTimeout = Settings.Secure.getLong(getContentResolver(),

Settings.Secure.LOCK_SCREEN_LOCK_AFTER_TIMEOUT, 5000);

mLockAfter.setValue(String.valueOf(currentTimeout));

mLockAfter.setOnPreferenceChangeListener(this);

final long adminTimeout = (mDPM != null ? mDPM.getMaximumTimeToLock(null) : 0);

final long displayTimeout = Math.max(0,

Settings.System.getInt(getContentResolver(), SCREEN_OFF_TIMEOUT, 0));

if (adminTimeout > 0) {

// This setting is a slave to display timeout when a device policy is enforced.

// As such, maxLockTimeout = adminTimeout - displayTimeout.

// If there isn't enough time, shows "immediately" setting.

disableUnusableTimeouts(Math.max(0, adminTimeout - displayTimeout));

}

}

private void updateLockAfterPreferenceSummary() {

// Update summary message with current value

long currentTimeout = Settings.Secure.getLong(getContentResolver(),

Settings.Secure.LOCK_SCREEN_LOCK_AFTER_TIMEOUT, 5000);

final CharSequence[] entries = mLockAfter.getEntries();

final CharSequence[] values = mLockAfter.getEntryValues();

int best = 0;

for (int i = 0; i < values.length; i++) {

long timeout = Long.valueOf(values[i].toString());

if (currentTimeout >= timeout) {

best = i;

}

}

mLockAfter.setSummary(getString(R.string.lock_after_timeout_summary, entries[best]));

}

private void disableUnusableTimeouts(long maxTimeout) {

final CharSequence[] entries = mLockAfter.getEntries();

final CharSequence[] values = mLockAfter.getEntryValues();

ArrayList revisedEntries = new ArrayList();

ArrayList revisedValues = new ArrayList();

for (int i = 0; i < values.length; i++) {

long timeout = Long.valueOf(values[i].toString());

if (timeout <= maxTimeout) {

revisedEntries.add(entries[i]);

revisedValues.add(values[i]);

}

}

if (revisedEntries.size() != entries.length || revisedValues.size() != values.length) {

mLockAfter.setEntries(

revisedEntries.toArray(new CharSequence[revisedEntries.size()]));

mLockAfter.setEntryValues(

revisedValues.toArray(new CharSequence[revisedValues.size()]));

final int userPreference = Integer.valueOf(mLockAfter.getValue());

if (userPreference <= maxTimeout) {

mLockAfter.setValue(String.valueOf(userPreference));

} else {

// There will be no highlighted selection since nothing in the list matches

// maxTimeout. The user can still select anything less than maxTimeout.

// TODO: maybe append maxTimeout to the list and mark selected.

}

}

mLockAfter.setEnabled(revisedEntries.size() > 0);

}

@Override

public void onResume() {

super.onResume();

// Make sure we reload the preference hierarchy since some of these settings

// depend on others...

createPreferenceHierarchy();

final LockPatternUtils lockPatternUtils = mChooseLockSettingsHelper.utils();

if (mVisiblePattern != null) {

mVisiblePattern.setChecked(lockPatternUtils.isVisiblePatternEnabled());

}

if (mTactileFeedback != null) {

mTactileFeedback.setChecked(lockPatternUtils.isTactileFeedbackEnabled());

}

mShowPassword.setChecked(Settings.System.getInt(getContentResolver(),

Settings.System.TEXT_SHOW_PASSWORD, 1) != 0);

KeyStore.State state = KeyStore.getInstance().state();

mResetCredentials.setEnabled(state != KeyStore.State.UNINITIALIZED);

}

@Override

public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {

final String key = preference.getKey();

final LockPatternUtils lockPatternUtils = mChooseLockSettingsHelper.utils();

if (KEY_UNLOCK_SET_OR_CHANGE.equals(key)) {

startFragment(this, "com.android.settings.ChooseLockGeneric$ChooseLockGenericFragment",

SET_OR_CHANGE_LOCK_METHOD_REQUEST, null);

} else if (KEY_BIOMETRIC_WEAK_IMPROVE_MATCHING.equals(key)) {

ChooseLockSettingsHelper helper =

new ChooseLockSettingsHelper(this.getActivity(), this);

if (!helper.launchConfirmationActivity(

CONFIRM_EXISTING_FOR_BIOMETRIC_IMPROVE_REQUEST, null, null)) {

startBiometricWeakImprove(); // no password set, so no need to confirm

}

} else if (KEY_LOCK_ENABLED.equals(key)) {

lockPatternUtils.setLockPatternEnabled(isToggled(preference));

} else if (KEY_VISIBLE_PATTERN.equals(key)) {

lockPatternUtils.setVisiblePatternEnabled(isToggled(preference));

} else if (KEY_TACTILE_FEEDBACK_ENABLED.equals(key)) {

lockPatternUtils.setTactileFeedbackEnabled(isToggled(preference));

} else if (preference == mShowPassword) {

Settings.System.putInt(getContentResolver(), Settings.System.TEXT_SHOW_PASSWORD,

mShowPassword.isChecked() ? 1 : 0);

} else if (preference == mToggleAppInstallation) {

if (mToggleAppInstallation.isChecked()) {

mToggleAppInstallation.setChecked(false);

warnAppInstallation();

} else {

setNonMarketAppsAllowed(false);

}

} else {

// If we didn't handle it, let preferences handle it.

return super.onPreferenceTreeClick(preferenceScreen, preference);

}

return true;

}

private boolean isToggled(Preference pref) {

return ((CheckBoxPreference) pref).isChecked();

}

/**

* see confirmPatternThenDisableAndClear

*/

@Override

public void onActivityResult(int requestCode, int resultCode, Intent data) {

super.onActivityResult(requestCode, resultCode, data);

if (requestCode == CONFIRM_EXISTING_FOR_BIOMETRIC_IMPROVE_REQUEST &&

resultCode == Activity.RESULT_OK) {

startBiometricWeakImprove();

return;

}

createPreferenceHierarchy();

}

public boolean onPreferenceChange(Preference preference, Object value) {

if (preference == mLockAfter) {

int timeout = Integer.parseInt((String) value);

try {

Settings.Secure.putInt(getContentResolver(),

Settings.Secure.LOCK_SCREEN_LOCK_AFTER_TIMEOUT, timeout);

} catch (NumberFormatException e) {

Log.e("SecuritySettings", "could not persist lockAfter timeout setting", e);

}

updateLockAfterPreferenceSummary();

}

return true;

}

public void startBiometricWeakImprove(){

Intent intent = new Intent();

intent.setClassName("com.android.facelock", "com.android.facelock.AddToSetup");

startActivity(intent);

}

}

其中有关未知来源应用安装的有:

mToggleAppInstallation = (CheckBoxPreference) findPreference(

KEY_TOGGLE_INSTALL_APPLICATIONS);

mToggleAppInstallation.setChecked(isNonMarketAppsAllowed());

private boolean isNonMarketAppsAllowed() {

return Settings.Secure.getInt(getContentResolver(),

Settings.Secure.INSTALL_NON_MARKET_APPS, 0) > 0;

}

private void setNonMarketAppsAllowed(boolean enabled) {

// Change the system setting

Settings.Secure.putInt(getContentResolver(), Settings.Secure.INSTALL_NON_MARKET_APPS,

enabled ? 1 : 0);

}

public void onClick(DialogInterface dialog, int which) {

if (dialog == mWarnInstallApps && which == DialogInterface.BUTTON_POSITIVE) {

setNonMarketAppsAllowed(true);

mToggleAppInstallation.setChecked(true);

}

}

源代码Settings$Secure.class中有关允许未知来源应用安装

/**

* Whether the package installer should allow installation of apps downloaded from

* sources other than the Android Market (vending machine).

*

* 1 = allow installing from other sources

* 0 = only allow installing from the Android Market

*/

public static final String INSTALL_NON_MARKET_APPS = "install_non_market_apps";

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android系统中的PackageManager(包管理器)是一个系统级别的服务,它是一个应用程序包的管理器,可以用来安装、卸载、查询应用程序包信息等操作。PackageManager API是Android系统中非常重要的一个API,它可以让开发者获取应用程序包的信息,比如版本号、权限等等。 常用的PackageManager命令有: 1. 查询已安装应用的信息 ``` pm list packages // 列出所有已安装应用的包名 pm list packages -s // 列出所有已安装系统应用的包名 pm list packages -3 // 列出所有已安装的第三方应用的包名 pm list packages -f // 列出所有已安装应用的APK路径 pm list packages -d // 只列出已禁用的应用 pm list packages -e // 只列出系统已启用的应用 ``` 2. 安装应用 ``` pm install /path/to/app.apk // 安装应用 pm install -r /path/to/app.apk // 重新安装应用,保留应用数据 pm install -t /path/to/app.apk // 允许安装覆盖其他应用 pm install -i <installer_package_name> /path/to/app.apk // 指定应用安装包安装来源 ``` 3. 卸载应用 ``` pm uninstall com.package.name // 卸载应用 pm uninstall -k com.package.name // 卸载应用,保留应用数据和缓存 ``` 4. 查询应用信息 ``` pm dump com.package.name // 输出应用信息 pm path com.package.name // 输出应用APK路径 pm list features // 列出系统支持的特性 pm list instrumentation // 列出所有已安装的Instrumentation ``` 5. 其他命令 ``` pm enable com.package.name // 启用应用 pm disable com.package.name // 禁用应用 pm clear com.package.name // 清除应用数据和缓存 ``` 以上是一些常用的PackageManager命令,使用时需要注意权限问题,部分命令需要root权限才能执行。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值