顯示具有 android -- Handler 標籤的文章。 顯示所有文章
顯示具有 android -- Handler 標籤的文章。 顯示所有文章

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
}

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"});
    }
}


Handler-- ProgressBar

Handler
參考: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" >

    <TextView
        android:id="@+id/textView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Handler" />

    <ProgressBar
        android:id="@+id/progressBar1"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:indeterminate="false"
        android:max="10"
        android:padding="4dip" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start Progress" 
        android:onClick="startProgress"/>

</LinearLayout>

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

main.java:


public class Cq_Handler_vogella01Activity extends Activity {
    /** Called when the activity is first created. */
private Handler mHandler;
private ProgressBar mProgressBar;
private Button mBtn;
private TextView tv;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mProgressBar = (ProgressBar) findViewById(R.id.progressBar1);
        mBtn = (Button) findViewById(R.id.button1);
        tv = (TextView) findViewById(R.id.textView);
        
        mHandler = new Handler();
        mBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
startProgress();
}
});
    }
    
    public void startProgress () {
    //Do something long
    Runnable runnable = new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i<= 10; i++) {
final int value = i;
try {
Thread.sleep(2000);
}catch (InterruptedException e) {
e.printStackTrace();
}
mHandler.post(new Runnable () {// 用來更新 View

@Override
public void run() {
// TODO Auto-generated method stub
mProgressBar.setProgress(value);
tv.setText("the value = " + value );
}
});
}
}
};
new Thread(runnable).start();
    }
}

2012年5月20日 星期日

Handler 03 + Timer



Handler and Timer

http://weizhulin.blog.51cto.com/1556324/323922



import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

public class Cq_Handler04Activity extends Activity {
    /** Called when the activity is first created. */

private int title = 0;
private Handler mHandler = new Handler() {

@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
//super.handleMessage(msg);
switch (msg.what) {
case 1:
updateTitle();
break;
}
}
};


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
     
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new MyTask(), 1, 1000);
    }
 
    private class MyTask extends TimerTask{

@Override
public void run() {
// TODO Auto-generated method stub
Message message = new Message();
message.what = 1;
mHandler.sendMessage(message);
}
   
    }
 
 
    public void updateTitle() {
    setTitle("Welcome to CQ's palace: " + title);
    title ++;
    }
}

Handler 01-- MainThread


MainHandler






package com.cq.practice.handler01;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;


public class Cq_Handler01Activity extends Activity {
    /** Called when the activity is first created. */

private Button mButton;
private ProgressDialog mProgressDialog;

private Handler handler = new Handler(){

@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
mProgressDialog.dismiss(); //close
}

};

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
     
        Resources res = this.getResources();
        mButton = (Button) findViewById(R.id.button1);
        mButton.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
processThread();
}
});
     
    }
 
 
 
    private void processThread() {
    mProgressDialog = ProgressDialog.show(this, "文件下載", "正在下載...");
   
    new Thread() {
   
   
    @Override
public void run() {
// TODO Auto-generated method stub
//super.run();
    prolongedActionMethod();
    handler.sendEmptyMessage(0);
}


    }.start();
    }
 
 
    private void prolongedActionMethod() {
    try {
    Thread.sleep(10000);
    }catch (Exception e){
    e.printStackTrace();
    }
    }
 
}

參考:
http://android.yaohuiji.com/archives/770

2012年3月18日 星期日

android -- Handler


按下按鈕後,會在新啟動的執行緒中向主執行緒發Handler訊息,主執行緒收到訊息後會根據訊息的內容修改TextView的顯示內容。



public class HandlerActivity extends Activity {
    /** Called when the activity is first created. */

public static final int UPDATE_DATA = 0;
public static final int UPDAT_COMPLETE = 1;
TextView tv;
Button btnStart;
//Handler物件
Handler myHandler = new Handler () {

@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
//super.handleMessage(msg);
switch (msg.what) {
case UPDATE_DATA:
tv.setText("Handler物件 " + msg.arg1 + "%...");
break;
case UPDATE_COMPLETE:
tv.setText("已完成來自執行緒的更新資料!");
break;
}
}

};

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
     
        tv = (TextView)findViewById(R.id.tv);
        btnStart = (Button)findViewById(R.id.btnStart);
     
        btnStart.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//啟動一個新執行緒
new Thread () {

@Override
public void run() {
// TODO Auto-generated method stub
//super.run();
for (int i = 0; i < 100; i++) {
try {
Thread.sleep(150);
} catch (Exception e) {
e.printStackTrace();
}
Message m = myHandler.obtainMessage();
m.what = UPDATE_DATA; //控制Handler的switch
m.arg1 = i + 1;
myHandler.sendMessage(m);//發出Message物件
}
myHandler.sendEmptyMessage(UPDATE_COMPLETE);//發更新完畢
}// end of run

}.start();
}
});
    }
}

******************************************************
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/btnStart"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="點按開始更新來自執行緒的資料"
    />
<TextView
android:id="@+id/tv"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="等待更新來自執行緒的資料..."
   />

</LinearLayout>


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

Optional: 以物件代替數字:

public class HandlerDemo extends Activity {
    /** Called when the activity is first created. */

public static final int UPDATE_DATA = 0;
public static final int UPDATE_COMPLETE = 1;
TextView tv;
Button btnStart;
//Handler物件
Handler myHandler = new Handler () {

@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
//super.handleMessage(msg);
switch (msg.what) {
case UPDATE_DATA:

tv.setText("Handler物件 : " + msg.obj);
break;
case UPDATE_COMPLETE:
tv.setText("已完成來自執行緒的更新資料!");
break;
}
}

};

String [] showWords= {"Blue Mountain", "Cappuccino", "Machiato", "Expresso", "Latte"};

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
     
        tv = (TextView)findViewById(R.id.tv);
        btnStart = (Button)findViewById(R.id.btnStart);
     
        btnStart.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//啟動一個新執行緒
new Thread () {

@Override
public void run() {
// TODO Auto-generated method stub
//super.run();
for (int i = 0; i < showWords.length; i++) {
try {
Thread.sleep(1500);
} catch (Exception e) {
e.printStackTrace();
}
Message m = myHandler.obtainMessage();
m.what = UPDATE_DATA;

m.obj = showWords[i].toString();
myHandler.sendMessage(m);//發出Message物件

//緩衝一下,以便看到最後一個字
try {
Thread.sleep(500);
} catch (Exception e) {
e.printStackTrace();
}
}
myHandler.sendEmptyMessage(UPDATE_COMPLETE);//發更新完畢
}// end of run

}.start();
}
});
    }
}