(转载)android多线程及定时器处理方式

来源:互联网 发布:网络教育有哪些学校 编辑:程序博客网 时间:2024/06/06 05:43

转自雨松博客:

http://blog.csdn.net/xys289187120/article/details/6706952

记录一下:

//Thread与Handler执行多线程

package cn.m15.xys;import java.io.InputStream;import android.app.Activity;import android.content.Context;import android.graphics.Bitmap;import android.graphics.BitmapFactory;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;import android.widget.TextView;public class SingleActivity extends Activity {    /**读取进度**/    public final static int LOAD_PROGRESS = 0;         /**标志读取进度结束**/    public final static int LOAD_COMPLETE = 1;             /** 开始加载100张图片按钮 **/    Button mButton = null;    /** 显示内容 **/    TextView mTextView = null;    /** 加载图片前的时间 **/    Long mLoadStatr = 0L;    /** 加载图片后的时间 **/    Long mLoadEnd = 0L;    Context mContext = null;    //接收传递过来的信息    Handler handler = new Handler() {@Overridepublic void handleMessage(Message msg) {    switch (msg.what) {    case LOAD_PROGRESS:mTextView.setText("当前读取到第" + msg.arg1 + "张图片");break;    case LOAD_COMPLETE:mTextView.setText("读取结束一共耗时" + msg.arg1 + "毫秒");break;    }    super.handleMessage(msg);}    };    @Override    protected void onCreate(Bundle savedInstanceState) {setContentView(R.layout.single);mContext = this;/** 拿到button 与 TextView 对象 **/mButton = (Button) findViewById(R.id.button0);mTextView = (TextView) findViewById(R.id.textView0);mTextView.setText("点击按钮开始更新时间");mButton.setOnClickListener(new OnClickListener() {    @Override    public void onClick(View arg0) {//开始读取图片LoadImage();    }});super.onCreate(savedInstanceState);    }    public void LoadImage() {new Thread() {    @Override    public void run() {//得到加载图片开始的时间mLoadStatr = System.currentTimeMillis();for (int i = 0; i < 100; i++) {    // 这里循环加载图片100遍    ReadBitMap(mContext, R.drawable.bg);    // 每读取完一张图片将进度甩给handler    Message msg = new Message();    msg.what = LOAD_PROGRESS;    msg.arg1 = i + 1;    handler.sendMessage(msg);}//得到加载图片结束的时间mLoadEnd = System.currentTimeMillis();//100张图片加载完成Message msg = new Message();msg.what = LOAD_COMPLETE;msg.arg1 = (int) (mLoadEnd - mLoadStatr);handler.sendMessage(msg);    }}.start();    }    /**     * 读取本地资源的图片     *      * @param context     * @param resId     * @return     */    public Bitmap ReadBitMap(Context context, int resId) {BitmapFactory.Options opt = new BitmapFactory.Options();opt.inPreferredConfig = Bitmap.Config.RGB_565;opt.inPurgeable = true;opt.inInputShareable = true;// 获取资源图片InputStream is = context.getResources().openRawResource(resId);return BitmapFactory.decodeStream(is, null, opt);    }}

定时器方法:

//TimerTask与Handler延迟多线程

package cn.m15.xys;import java.util.Timer;import java.util.TimerTask;import android.app.Activity;import android.content.Context;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;import android.widget.TextView;public class TimerTaskActivity extends Activity {    /**执行Timer进度**/    public final static int LOAD_PROGRESS = 0;         /**关闭Timer进度**/    public final static int CLOSE_PROGRESS = 1;         /** 开始TimerTask按钮 **/    Button mButton0 = null;        /** 关闭TimerTask按钮 **/    Button mButton1 = null;        /** 显示内容 **/    TextView mTextView = null;    Context mContext = null;    /**Timer对象**/    Timer mTimer = null;        /**TimerTask对象**/    TimerTask mTimerTask = null;       /**记录TimerID**/    int mTimerID = 0;            /**接收传递过来的信息**/    Handler handler = new Handler() {@Overridepublic void handleMessage(Message msg) {    switch (msg.what) {    case LOAD_PROGRESS:mTextView.setText("当前TimerID为" + msg.arg1 );break;    case CLOSE_PROGRESS:mTextView.setText("当前Timer已经关闭请重新开启" );break;        }    super.handleMessage(msg);}    };    @Override    protected void onCreate(Bundle savedInstanceState) {setContentView(R.layout.timer);mContext = this;/** 拿到button 与 TextView 对象 **/mButton0 = (Button) findViewById(R.id.button0);mButton1 = (Button) findViewById(R.id.button1);mTextView = (TextView) findViewById(R.id.textView0);mTextView.setText("点击按钮开始更新时间");//开始mButton0.setOnClickListener(new OnClickListener() {    @Override    public void onClick(View arg0) {//开始执行timerStartTimer();    }});//关闭mButton1.setOnClickListener(new OnClickListener() {    @Override    public void onClick(View arg0) {//停止执行timerCloseTimer();    }});super.onCreate(savedInstanceState);    }    public void StartTimer() {if (mTimer == null) {    mTimerTask = new TimerTask() {public void run() {    //mTimerTask与mTimer执行的前提下每过1秒进一次这里    mTimerID ++;    Message msg = new Message();    msg.what = LOAD_PROGRESS;    msg.arg1 = (int) (mTimerID);    handler.sendMessage(msg);}    };    mTimer = new Timer();      //第一个参数为执行的mTimerTask    //第二个参数为延迟的时间 这里写1000的意思是mTimerTask将延迟1秒执行    //第三个参数为多久执行一次 这里写1000表示每1秒执行一次mTimerTask的Run方法    mTimer.schedule(mTimerTask, 1000, 1000);}    }    public void CloseTimer() {//在这里关闭mTimer 与 mTimerTaskif (mTimer != null) {    mTimer.cancel();    mTimer = null;}if (mTimerTask != null) {    mTimerTask = null;}/**ID重置**/mTimerID = 0;//这里发送一条只带what空的消息handler.sendEmptyMessage(CLOSE_PROGRESS);    }}


 //AsyncTask执行多线程

package cn.m15.xys;import java.io.InputStream;import java.util.Timer;import java.util.TimerTask;import android.app.Activity;import android.content.Context;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.os.AsyncTask;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.TextView;public class AsyncTaskActivity extends Activity {    /**执行Timer进度**/    public final static int LOAD_PROGRESS = 0;         /**关闭Timer进度**/    public final static int CLOSE_PROGRESS = 1;         /** 开始StartAsync按钮 **/    Button mButton0 = null;            /** 显示内容 **/    TextView mTextView = null;    Context mContext = null;    /**Timer对象**/    Timer mTimer = null;        /**TimerTask对象**/    TimerTask mTimerTask = null;       /**记录TimerID**/    int mTimerID = 0;    @Override    protected void onCreate(Bundle savedInstanceState) {setContentView(R.layout.async);mContext = this;/** 拿到button 与 TextView 对象 **/mButton0 = (Button) findViewById(R.id.button0);mTextView = (TextView) findViewById(R.id.textView0);//开始mButton0.setOnClickListener(new OnClickListener() {    @Override    public void onClick(View arg0) {//开始执行StartAsyncStartAsync();    }});super.onCreate(savedInstanceState);    }    public void StartAsync() {new AsyncTask<Object, Object, Object>() {       @Override    protected void onPreExecute() {//首先执行这个方法,它在UI线程中 可以执行一些异步操作mTextView.setText("开始加载进度");super.onPreExecute();    }    @Override    protected Object doInBackground(Object... arg0) {//异步后台执行 ,执行完毕可以返回出去一个结果object对象//得到开始加载的时间Long startTime = System.currentTimeMillis();for (int i = 0; i < 100; i++) {    // 这里循环加载图片100遍    ReadBitMap(mContext, R.drawable.bg);    //执行这个方法会异步调用onProgressUpdate方法,可以用来更新UI    publishProgress(i);}//得到结束加载的时间Long endTime = System.currentTimeMillis();//将读取时间返回return endTime - startTime;    }    @Override    protected void onPostExecute(Object result) {//doInBackground之行结束以后在这里可以接收到返回的结果对象mTextView.setText("读取100张图片一共耗时" + result+ "毫秒");super.onPostExecute(result);    }            @Override    protected void onProgressUpdate(Object... values) {        //时时拿到当前的进度更新UImTextView.setText("当前加载进度" + values[0]);        super.onProgressUpdate(values);    }}.execute();//可以理解为执行 这个AsyncTask    }    /**     * 读取本地资源的图片     *      * @param context     * @param resId     * @return     */    public Bitmap ReadBitMap(Context context, int resId) {BitmapFactory.Options opt = new BitmapFactory.Options();opt.inPreferredConfig = Bitmap.Config.RGB_565;opt.inPurgeable = true;opt.inInputShareable = true;// 获取资源图片InputStream is = context.getResources().openRawResource(resId);return BitmapFactory.decodeStream(is, null, opt);    }}

 //多线程Looper的使用

package cn.m15.xys;import java.io.InputStream;import android.app.Activity;import android.content.Context;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.os.Bundle;import android.os.Handler;import android.os.Looper;import android.os.Message;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.Toast;public class LooperActivity extends Activity {    /** 发送消息按钮 **/    Button mButton = null;    /** 加载图片前的时间 **/    Long mLoadStatr = 0L;    /** 加载图片后的时间 **/    Long mLoadEnd = 0L;    Context mContext = null;    private Handler handler = new Handler() {public void handleMessage(Message msg) {    new Thread() {@Overridepublic void run() {       //如果handler不指定looper的话    //默认为mainlooper来进行消息循环,    //而当前是在一个新的线程中它没有默认的looper    //所以我们须要手动调用prepare()拿到他的loop     //可以理解为在Thread创建Looper的消息队列    Looper.prepare();            Toast.makeText(LooperActivity.this, "收到消息",Toast.LENGTH_LONG).show();           //在这里执行这个消息循环如果没有这句    //就好比只创建了Looper的消息队列而    //没有执行这个队列那么上面Toast的内容是不会显示出来的    Looper.loop();//如果没有   Looper.prepare();  与 Looper.loop();//会抛出异常Can't create handler inside thread that has not called Looper.prepare()   //原因是我们新起的线程中是没有默认的looper所以须要手动调用prepare()拿到他的loop}    }.start();}};    @Override    protected void onCreate(Bundle savedInstanceState) {setContentView(R.layout.loop);mContext = this;/** 拿到button 与 TextView 对象 **/mButton = (Button) findViewById(R.id.button0);mButton.setOnClickListener(new OnClickListener() {    @Override    public void onClick(View arg0) {new Thread() {    @Override    public void run() {    //发送一条空的消息            //空消息中必需带一个what字段    //用于在handler中接收    //这里暂时我先写成0    handler.sendEmptyMessage(0);    }}.start();    }});super.onCreate(savedInstanceState);    }    /**     * 读取本地资源的图片     *      * @param context     * @param resId     * @return     */    public Bitmap ReadBitMap(Context context, int resId) {BitmapFactory.Options opt = new BitmapFactory.Options();opt.inPreferredConfig = Bitmap.Config.RGB_565;opt.inPurgeable = true;opt.inInputShareable = true;// 获取资源图片InputStream is = context.getResources().openRawResource(resId);return BitmapFactory.decodeStream(is, null, opt);    }}



原创粉丝点击