我已经TCP
使用套接字为 android 制作了一个客户端。但是,我拥有的程序不允许我动态输入服务器地址。我也不能使用意图来传输字符串,MainActivity
因为我TcpClient.java
没有扩展到Activity
. 我应该实现什么逻辑,以便我可以动态设置服务器地址并连接到我希望的任何服务器..
MainActivity.java
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_settings:
Intent i = new Intent(this, Preferences.class);
startActivityForResult(i, RESULT_SETTINGS);
break;
}
return true;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_SETTINGS:
saveData();
break;
}
}
public class connectTask extends AsyncTask<String,String,TcpClient> {
@Override
protected TcpClient doInBackground(String... message) {
//we create a TCPClient object and
mTcpClient = new TcpClient(new TcpClient.OnMessageReceived() {
@Override
//here the messageReceived method is implemented
public void messageReceived(String message) {
//this method calls the onProgressUpdate
publishProgress(message);
}
});
mTcpClient.run(serverip, serverport);
return null;
}
}
//call it at Activity startup onStart() for example
public void loadData(){
int mode = Activity.MODE_PRIVATE;
SharedPreferences mySharedPreferences;
mySharedPreferences = getSharedPreferences(MYPREFS, mode);
serverip = mySharedPreferences.getString("IP", serverip);
serverport = mySharedPreferences.getInt("Port", serverport);
}
// Call it whenever you modify the values
public void saveData()
{
int mode = Activity.MODE_PRIVATE;
SharedPreferences mySharedPreferences;
mySharedPreferences = getSharedPreferences(MYPREFS, mode);
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putString("IP", serverip);
editor.putInt("Port", serverport);
editor.commit();
Toast.makeText(getBaseContext(),
"Server Settings Saved" + serverip + serverport ,
Toast.LENGTH_LONG).show();
}
}
这不是保存数据。它在 Toast 上显示 null0。此外,这些是为上述代码声明的变量
public static final String MYPREFS = "192.168.1.3";
public String serverip;
public int serverport;
首选项.java
package com.example.homauto;
导入android.os.Bundle;导入android.preference.PreferenceActivity;
公共类首选项扩展 PreferenceActivity{
@SuppressWarnings("deprecation")
@Override
protected void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
我是编程新手.. 这是我参考的网站.. Android TCP 连接教程