我当前的代码就像这样...问题就是我无法在Toast中显示消息....
任何人都可以帮助我,因为我需要在这里使用哪种方法或上下文?
我已成功连接到服务器,但响应在控制台上,但无法在toast消息中显示。
public class MyActivity extends ActionBarActivity {
private Socket client;
Context c;
String userInput;
TextView txtV;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
txtV = (TextView)findViewById(R.id.txtView);
MyConnection sendMessageTask = new MyConnection();
sendMessageTask.execute();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my, menu);
return true;
}
private class MyConnection extends AsyncTask<Void, Void, Void> {
String userInput;
Context c1;
@Override
protected Void doInBackground(Void... params) {
try {
client = new Socket("10.10.0.122", 1978); // connect to the server
BufferedReader stdIn = new BufferedReader(new InputStreamReader(client.getInputStream()));
while (true)
{
userInput = stdIn.readLine();
System.out.println(userInput);
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Toast.makeText(c,userInput,Toast.LENGTH_LONG).show();
}
}
}
答案 0 :(得分:0)
请勿在同一套接字上混合多个Writers
和OutputStreams
或Readers
和InputStreams
。它不会工作。
PrintWriter
已缓冲。如果你写了一些东西,然后期待一个回复,你需要在写完后冲洗它。