我正在为 Android 构建一个简单的 IRC 客户端。
我使用 AsyncTask 连接到 Freenode/IRC-server。
我可以很容易地得到来自 irc-server 的所有响应,
然后我可以根据响应显示对话。
public class IrcTask extends AsyncTask<Void, String, Void> {
public IrcTask(Activity activity, ProgressDialog pdialog, ScrollView sv_channel_output, List<String> join_users, BufferedWriter writer, BufferedReader reader, TextView outputView, String channel, String nick, String login) {
this.activity = new WeakReference<Activity>(activity);//ChannelActivity
this.nick = nick;
this.login = login;
}
@Override
protected Void doInBackground(Void... Sparams) {
// Connect directly to the IRC server.
try {
// Log on to the server.
this.writer.get().write("NICK " + nick + "\r\n");
this.writer.get().write("USER " + login + " 8 * : Freenode for Android App IRC Bot\r\n");
this.writer.get().flush();
// Join to the channel.
this.writer.get().write("JOIN " + channel + "\r\n");
this.writer.get().flush();
// Read lines from the server until it tells us we have connected.
String line = null;
while ((line = this.reader.get().readLine( )) != null) {
publishProgress(line);
if (line.contains("PING ")) {
// We must respond to PINGs to avoid being disconnected.
this.writer.get().write("PONG " + line.substring(5) + "\r\n");
this.writer.get().flush( );
}
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
在我的 ChannelActvity 上,我有一个 EditView 可以将文本/数据发送到服务器。
我的问题是从服务器读取时将一些写入数据传递给 AsyncTask。
(启动 doInBackground->while.. 后,它会运行,以便将数据发送回我的 ChannelActicity)
我尝试使用“SharedPreferences”将写入数据传递给 IrcServer。
但它不起作用......
像这样...
// Read lines from the server until it tells us we have connected.
String line = null;
while ((line = this.reader.get().readLine( )) != null) {
//gets/sets IRC-detils from 'MainActivity'
pref = this.activity.get().getSharedPreferences("writeToIrcTack", 0);
if(pref.getString("data", "").length() >0)
{
Log.d("doInBackground->IF-it-gets-data", "pref.getString=="+pref.getString("data", ""));
this.writer.get().write("NOTICE "+channel+" " + pref.getString("data", "") + "\r\n");
this.writer.get().flush( );
}
publishProgress(line);