我正在使用此代码获取特定应用程序所需的权限列表。我想为每个请求的权限创建一个Preference。我怎样才能做到这一点?代码是:
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();
}
答案 0 :(得分:1)
马里奥我想知道你打算用App的权限名称创建偏好,但是你有一个解决方案。
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();