gpt4 book ai didi

java - 动态创建首选项

转载 作者:行者123 更新时间:2023-11-30 03:14:31 25 4
gpt4 key购买 nike

我正在使用此代码获取特定应用程序所需的权限列表。我想为请求的每个权限创建一个首选项。我怎样才能做到这一点?代码是:

try {
PackageInfo packageInfo = getPackageManager().getPackageInfo(myPackageName, PackageManager.GET_PERMISSIONS);

String[] requestedPermissions = packageInfo.requestedPermissions;
if ( requestedPermissions != null ) {
for (int i = 0; i < requestedPermissions.length; i++) {
permission.setSummary(requestedPermissions[i] + "\n");
}

}
}
catch ( PackageManager.NameNotFoundException e ) {
e.printStackTrace();
}

最佳答案

Mario 我想知道您要为什么创建带有应用权限名称的首选项,但在这里您有一个解决方案。

try { 
PackageInfo packageInfo = getPackageManager().getPackageInfo(myPackageName, PackageManager.GET_PERMISSIONS);

String[] requestedPermissions = packageInfo.requestedPermissions;
if ( requestedPermissions != null ) {
for (int i = 0; i < requestedPermissions.length; i++) {
//permission.setSummary(requestedPermissions[i] + "\n");
//method to create a preference with the name of your permission.
setPreference(this, requestedPermissions[i]);
}

}
}
catch ( PackageManager.NameNotFoundException e ) {
e.printStackTrace();
}

创建首选项的方法。

public static void setPreference(Context context, String preferenceName)
{
SharedPreferences settings = context.getSharedPreferences(preferenceName, 0);
SharedPreferences.Editor editor = settings.edit();
//Add a key to this preference and his value.
editor.putString(preferenceName+"_value", "Value stored in preference called: " + preferenceName);
editor.commit();
}

创建一个方法来读取存储在您的首选项中的值

public static String getPreference(Context context,  String preferenceName){
SharedPreferences settings = context.getSharedPreferences(preferenceName, 0);
return settings.getString(preferenceName+"_value", "");
}

然后你可以读取存储在你的首选项中的值,例如,读取存储在名为

的首选项中的值

"android.permission.INTERNET"

:

   Log.i("Preferences", getPreference(this,"android.permission.INTERNET"));

在 Toast 中显示数据的示例:

Toast.makeText(this, "the value stored in \"android.permission.INTERNET\" preference is: " + getPreference(this,"android.permission.INTERNET"), Toast.LENGTH_LONG).show();

关于java - 动态创建首选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20359610/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com