一、runOnUiThread的用法
runOnUiThread是Activity的内部方法,使用时最好指定当前的环境变量(Context)。
new Thread(new Runnable() { @OverrIDe public voID run() { runOnUiThread(new Runnable() { public voID run() { Toast.makeText(mainActivity.this,"UI *** 作。。。",0).show(); } }); } }).start();
执行runOnUiThread这个方法会调用父类中的
public final voID runOnUiThread(Runnable action){ if(Thread.currentThread()!=mUiThread){ mHandler.post(action); }else{ action.run(); }}
二、新线程中VIEw直接在UI线程中更新的方法
textVIEw.postDelayed(new Runnable() { @OverrIDe public voID run() { textVIEw.setText("Test VIEw.post(Runnable)"); } },1000);- textVIEw.post(new Runnable() { @OverrIDe public voID run() { textVIEw.setText("Test VIEw.postDelay(Runnable,long)"); } });
三、Handler(消息传递机制)使用
Handler myHandler = new Handler(){ public voID handleMessage(Message msg){ super.handleMessage(msg); }};
也可以继承handler
class MyHandler extends handler{ public MyHandler(){ } @OverrIDe public voID handleMessage(Message msg){ super.handleMessage(msg); }}
分发Message或者Runnable对象到handler所在的线程中一般handler在主线程中。
handler中一些分发消息的方法:
post(Runnable) postAtTime(Runnable,long) postDelay(Runnable,long) sendEmptyMessage(int what) sendMessage(Message) senMessageAtTime(Message,long) sendMessageDelayed(Message,long)post方式添加一个实现Runnable接口的匿名对象到消息对列中,在目标收到消息后就可以以回调的方式在自己的线程中执行
Message对象所具有的属性:
属性 | 类型 | 描述 |
---|---|---|
arg1 | int | 用来存放整型数据 |
arg2 | int | 用来存放整型数据 |
obj | Object | 用来存放发送给接收器的Object任意对象 |
replyTo | Messager | 用来指定此Message发送到何处的可选Message对象 |
what | int | 用于指定用户自定义的消息代码这样接受者就可以了解这个消息的信息 |
Message message = Message.obtain();message.arg1 = 1;message.arg2 = 2;message.obj = "Demo";message.what = 3;Bundle bundle = new Bundle();bundle.putString( "name","Lucy");message.setData(bundle);
下面贴上一段示例代码(开启新线程实现电子广告牌)
public class MainActivity extends Activity implements Runnable { private ImageVIEw iv; private TextVIEw tv; private Handler handler; private int[] path = new int[]{R.drawable.img01,R.drawable.img02,R.drawable.img03,R.drawable.img04,R.drawable.img05,R.drawable.img06}; private String[] Title = new String[]{"编程词典系列","高效开发","快乐分享","用户人群","快速学习","全方位查询"}; private int index =0; @OverrIDe protected voID onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentVIEw(R.layout.activity_main); iv = (ImageVIEw) findVIEwByID(R.ID.imageVIEw1); tv = (TextVIEw) findVIEwByID(R.ID.textVIEw1); Thread t = new Thread(this); t.start(); handler = new Handler(){ public voID handleMessage(Message msg){ if (msg.what ==1) { tv.setText(msg.getData().getString("Title")); iv.setimageResource(path[msg.arg1]); } super.handleMessage(msg); } }; } @OverrIDe public voID run() { while(!Thread.currentThread().isInterrupted()){ index = new Random().nextInt(path.length); Message m = handler.obtainMessage(); m.arg1 = index; Bundle bundle = new Bundle(); m.what = 1; bundle.putString("Title",Title[index]); m.setData(bundle); handler.sendMessage(m); try { Thread.sleep(2000); } catch (InterruptedException e) { // Todo auto-generated catch block e.printstacktrace(); } } } }
四、AsyncTask异步任务的用法
AsyncTask定义的三种泛型
params: 启动任务执行的输入参数,如:http请求的URL progress:后台任务执行的百分比 result:返回结果,如:String、List集合等private class MyTask extends AsyncTask<params,progress,result> { ... }
示例代码:
private class DownloadfilesTask extends AsyncTask<URL,Integer,Long> { protected Long doInBackground(URL... urls) { int count = urls.length; long totalSize = 0; for (int i = 0; i < count; i++) { totalSize += Downloader.downloadfile(urls[i]); publishProgress((int) ((i / (float) count) * 100)); // Escape early if cancel() is called if (isCancelled()) break; } return totalSize; } protected voID onProgressUpdate(Integer... progress) { setProgresspercent(progress[0]); } protected voID onPostExecute(Long result) { showDialog("Downloaded " + result + " bytes"); } }
获取网络图片的示例代码:
public class MainActivity extends ActionBaractivity { private ImageVIEw iv; private button bt; private String imagePath = "http://192.168.1.1/sa"; private ProgressDialog dialog; @OverrIDe protected voID onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentVIEw(R.layout.activity_main); iv = (ImageVIEw) findVIEwByID(R.ID.imageVIEw1); bt = (button) findVIEwByID(R.ID.button1); dialog = new ProgressDialog(this); dialog.setTitle("提示信息:"); dialog.setMessage("正在下载。。。"); bt.setonClickListener(new OnClickListener() { @OverrIDe public voID onClick(VIEw v) { new MyTask().execute(imagePath); } }); } public class MyTask extends AsyncTask<String,VoID,Bitmap>{ @OverrIDe protected Bitmap doInBackground(String... params) { httpClIEnt httpClIEnt = new DefaulthttpClIEnt(); httpGet httpGet = new httpGet(params[0]); Bitmap bitmap = null; try { httpResponse httpResponse = httpClIEnt.execute(httpGet); if (httpResponse.getStatusline().getStatusCode()==200) { httpentity httpentity = httpResponse.getEntity(); byte[] data = EntityUtils.toByteArray(httpentity); bitmap= BitmapFactory.decodeByteArray(data,data.length); } } catch (Exception e) { e.printstacktrace(); } return bitmap; } @OverrIDe protected voID onPreExecute() { super.onPreExecute(); dialog.show(); } @OverrIDe protected voID onPostExecute(Bitmap result) { super.onPostExecute(result); iv.setimageBitmap(result); dialog.dismiss(); } } }总结
以上是内存溢出为你收集整理的总结Android中多线程更新应用的页面信息的方式全部内容,希望文章能够帮你解决总结Android中多线程更新应用的页面信息的方式所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)