2012年5月21日 星期一

Handler -- v3. thread

Handler 下載網路的圖,如遇上restart,thread 還是能保存下來。


Manifest.xm:


<uses-permission android:name="android.permission.INTERNET"/>

**************************
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" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="下載" />

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="重整" />

    </LinearLayout>

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" />

</LinearLayout>



*********************************

public class Cq_Handler_vogella03Activity extends Activity {
    /** Called when the activity is first created. */
private static ProgressDialog dialog;
private static ImageView mImageView;
private static Bitmap downloadBitmap;
private static Handler handler;
private Thread downloadThread;
private Button downloadBtn;
private Button resetBtn;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        //Create a handler to update the UI
        handler = new Handler();
        mImageView = (ImageView) findViewById(R.id.imageView1);
        
        //Did we already download the image?
        if (downloadBitmap != null) {
        mImageView.setImageBitmap(downloadBitmap);
        }
        
        //Check if the thread is already running
        downloadThread = (Thread) getLastNonConfigurationInstance();
        if (downloadThread != null && downloadThread.isAlive()) {
        dialog = ProgressDialog.show(this, "下載狀況", "下載中...");
        }
        
        //Setup buttons
        downloadBtn = (Button) findViewById(R.id.button1);
        resetBtn = (Button) findViewById(R.id.button2);
        
        downloadBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
downloadPicture(v);
}
});
        
        resetBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
resetPicture(v);
}
});
    }
    
    
    
    public void downloadPicture (View view) {
    
    dialog = ProgressDialog.show(this, "下載狀況", "下載中...");
    downloadThread = new MyThread();
    downloadThread.start();
    
    }
    
    public void resetPicture(View view) {
    if (downloadBitmap != null) {
    downloadBitmap = null;
    }
    mImageView.setImageResource(R.drawable.ic_launcher);
    }


    //SAVE the thread
@Override
public Object onRetainNonConfigurationInstance() {
// TODO Auto-generated method stub
//return super.onRetainNonConfigurationInstance();
return downloadThread;
}


    // Dismiss dialog if activity is destroyed
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
dialog = null;
}
super.onDestroy();
}
    
    // Utility method to download image from the internet
static private Bitmap downloadBitmap (String url) throws IOException {
HttpUriRequest request = new HttpGet(url.toString());
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
byte [] bytes = EntityUtils.toByteArray(entity);
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
return bitmap;
}else {
throw new IOException("Download failed, HTTP response code " + statusCode + " - "
+ statusLine.getReasonPhrase());
}
}
   
static public class MyThread extends Thread {

@Override
public void run() {
// TODO Auto-generated method stub
//super.run();
try {
//Simulate a slow network
try {
new Thread().sleep(5000);
}catch (InterruptedException e) {
e.printStackTrace();
}
downloadBitmap = downloadBitmap("http://www.vogella.com/img/lars/LarsVogelArticle7.png");
handler.post(new MyRunnable());
}catch (IOException e) {
e.printStackTrace();
}finally {
}
}
}// end of MyThread
    
static public class MyRunnable implements Runnable {

@Override
public void run() {
// TODO Auto-generated method stub
mImageView.setImageBitmap(downloadBitmap);
dialog.dismiss();
}
     }// end of MyRunnable
}

沒有留言:

張貼留言