You simply need to create an async task that communicates in the background and then updates the UI thread as needed. Here is the background thread to get information from a socket and update a text view with the number of bytes it receivers
public class InternetTask extends AsyncTask<Void, Integer, Void> {
private WeakReference<TextView> mUpdateView;
public LoginTask(TextView view) {
this.mUpdateView = new WeakReference<TextView>(view);
}
@Override
protected Void doInBackground() {
try {
Socket socket = new Socket("127.0.0.1", 80);
InputStream is = socket.getInputStream();
byte[] buffer = new byte[25];
int read = is.read(buffer);
while(read != -1){
publishProgress(read);
read = is.read(buffer);
}
is.close();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onProgressUpdate(Integer... values) {
if(mUpdateView.get() != null && values.length > 0){
mUpdateView.get().setText(values[0].toString());
}
}
}
And here is how you would kick that thread off
public class TestTab extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.someLayout);
TextView textView = (TextView)findViewById(R.id.someid);
InternetTask task = new InternetTask(textView);
task.execute();
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…