2016-04-13 33 views
0

我想製作一個android應用程序,當應用程序的用戶點擊一個按鈕時,它應該轉到RaspBerry PI的IP地址。這個Pi位於網絡本身並具有靜態IP,但應由用戶指定一次。Android重構URL onClick按鈕

我有一個TextField,用戶可以在其中放置Pi的IP地址。這應該存儲在SharedPreferences中。以下是此部分的代碼:

public void save(View view) { 
    editor.putString("homeIP", textHomeIP.getText().toString()); 
    editor.commit(); 

    editor.putString("PiIP", textPiIP.getText().toString()); 
    editor.commit(); 

    piIP = textPiIP.getText().toString(); 
    homeIP = textHomeIP.getText().toString(); 

    makeURL(); 

    Toast.makeText(getApplication(), "Saved", Toast.LENGTH_SHORT); 

    finish(); 
} 

此方法在單擊保存按鈕時運行。該類擴展了MainActivity,並在設置按鈕被單擊時使用設置xml打開。出於某種原因,MainActivity不能更改URL。以下是更改URL的方法

protected void makeURL() 
{ 
    if(mSocket != null) 
    { 
     mSocket.disconnect(); 
    } 

    try 
    { 
     url = new URL("http://" + piIP); 
     Log.d("URL", url.toString()); 
    } 
    catch (java.net.MalformedURLException e) {} 

    try 
    { 
     mSocket = IO.socket(url.toString(), opts); 
    } 
    catch (java.net.URISyntaxException e) 
    { 
     Log.d("ERROR", "Cant initialize socket: " + e.toString()); 
    } 

    mSocket.connect(); 
    mSocket.on("detection-start", detectionStart); 
    mSocket.on("detection-end", detectionEnd); 
} 

套接字確實實際連接,但由於某種原因URL保持不變。我在onCreate中運行此方法並在此之前啓動piIP。

這裏的onCreate方法:

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    ipActivity = new IPActivity(); 
    ipActivity.execute(); 

    setContentView(R.layout.content_main); 
    notificationSettings(); 

    //connectionChanger = new ConnectionChangeReceiver(); 

    sharedPref = this.getPreferences(Context.MODE_PRIVATE); 
    //sharedPref = PreferenceManager.getDefaultSharedPreferences(this); 

    editor = sharedPref.edit(); 

    homeIP = sharedPref.getString("homeIP", "localhost"); 
    piIP = sharedPref.getString("PiIP", "localhost"); 

    Log.d("Pi IP", piIP); 

    makeURL(); 
} 

,最後這裏的openBrowser()方法

public void openBrowser(View view) 
{ 
    makeURL(); 
    Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url.toString())); 
    startActivity(browserIntent); 
} 

有人能告訴我爲什麼當保存設置的URL沒有改變?

+0

你能詳細說明一下:「套接字確實連接,但URL由於某種原因保持不變」? – Pooya

+0

用戶套接字連接到用戶的給定IP地址,並可以從服務器接收事件。但是,該URL仍然鏈接到本地​​主機 –

+0

你看到logcat中的任何錯誤?我看到你把Log.d放在makeURL中 – Pooya

回答

0

事實證明,我使用getPreferences而不是getSharedPreferences。它解決了創建URL的問題。我自己創建了子類,讓de IP地址通過getSharedPreferences加載。