2013-12-03 125 views
1

我使用此代碼獲取特定應用程序所需的權限列表。我想爲每個請求的權限創建一個首選項。我怎樣才能做到這一點?代碼是:動態創建首選項

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

添加每個權限的偏好?你究竟是什麼意思?您想做什麼 ? – gahfy

+0

例如,如果應用程序需要三個許可證,我想每個許可證都有三個首選項。 –

+0

但是究竟是什麼? – gahfy

回答

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")); 

例如Displayin數據:

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