2016-04-13 37 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加载。