2012年5月21日 星期一

Handler -- Async Task

Handler: Async Task
使用 Async Task (非同步任務)的方式下載網頁的內容。當背景下載完成時,才載入TextView 裡顯現出來。

參考:http://www.vogella.com/articles/AndroidPerformance/article.html






res/layout/main.xml:


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Load Webpage" />
     <ScrollView
        android:id="@+id/scrollView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:fadingEdge="vertical"
        android:paddingTop="10dip"
        android:scrollbars="vertical" >

     <TextView
            android:id="@+id/textView01"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:paddingTop="10dip"
            android:text="Taipei Times (台北時報)"
            android:textColor="#00FF00"
           />
    </ScrollView>

      
</LinearLayout>

****************************************
main.java:

/**
 *  Async Task  using Android HttpClient
 * */
public class HandlerAsyncTaskActivity extends Activity {
    /** Called when the activity is first created. */
private TextView tv;
private Button btn;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tv = (TextView) findViewById(R.id.textView01);
      
        btn = (Button) findViewById(R.id.button1);
        btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
readWebpage(tv);
}
});
    }
    
    
    private class DownloadWebPageTask extends AsyncTask<String, Void, String>{

@Override
protected String doInBackground(String... urls) {
// TODO Auto-generated method stub
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
}catch (Exception e) {
e.printStackTrace();
}
}
return response;
}

@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
//super.onPostExecute(result);
tv.setText(result);
}
    
    }
    
    public void readWebpage (View view) {
    DownloadWebPageTask task = new DownloadWebPageTask();
    task.execute(new String[] {"http://www.taipeitimes.com"});
    }
}


沒有留言:

張貼留言