2011-06-30 54 views
0

四處串基本上我有一個獨立的類,它不使用活動或服務。 該類中的一個函數啓動一個新的Authenticator。在保護功能的Android

我在strings.xml檔案一個字符串,我想訪問 尋找最好的方法

示例代碼

class MyConnection(){ 

String username; 
String pwd; 
String strurl; 
    public MyConnection(String usernameIN, String pwdIN, String urlIN){ 
     this.username = usernameIN; 
     this.pwd = pwdIN; 
     this.strurl = urlIN 
    } 
public void 
URL url = null; 

try { 
    url = new URL(this.strURL); 
    URLConnection urlConn = null; 
    Authenticator.setDefault(new Authenticator()){ 

     protected PasswordAuthentication getPasswordAuthentication()(
       // I want my vars from strings.xml here 
       return new PasswordAuthentication(strUsername, strPwd.toCharArray()); 
     } 
    }); 
    urlCOnn = url.openConnection(); 
    //Rest of the code, including CATCH 
} 

我通過了瓦爾地走入類,但怎麼做我訪問他們當我設置PasswordAuthentication。或者我可以直接從strings.xml訪問它們?

回答

0

你如何創建MyConnection類的實例?

它應該是通過一個活動或服務,對不對?

然後,當您創建,傳遞當前活動

public class MyConnection { 

    private Activity activity; 

    public MyConnection(Activity a) { 
     this.activity = a; 
    } 

    //.... 

    private void method() { 
     activity.getResources().getString(R.string....); 
    } 
} 

編輯:我沒有看到你已經有了一個構造函數。然後添加一個參數到現有的參數。

0

您可以將final修飾符添加到您的MyConnection()構造函數的參數中,這樣您可以在調用PasswordAuthentication()時將它們用作參數。希望這可以幫助。

0

您需要將Context實例傳遞給您的類或單個方法。 Context實例可以是ActivityServiceContext的子類別的任何其他實例。您可以使用它訪問系統資源:

class MyConnection 
{ 
    private final Context context; 

    public MyConnection(Context context) 
    { 
     this.context = context; 
    } 

    . 
    . 
    . 
    public void someMethod() 
    { 
     String str = context.getResources().getString (R.string.myString); 
    } 
}