android Thread 非線程更新UI界面(handler,runOnUiThread)解決圖片加載慢的問題

項目背景:

需要將一個LinearLayout(例子中爲:LL_lineChart)中內容截圖,存在本地,並將這張圖片作爲一個LinearLayout(例子中爲:LL_clickfirst,LL_clickcontent)的背景。
加載過程會很慢,並且添加的processdialog會很卡,加載圖片會佔用UI線程,因此,需要將耗時操作添加到線程中。
private void ChartBitmap() {
		LL_lineChart.destroyDrawingCache();
		LL_lineChart.setDrawingCacheEnabled(true);
		LL_lineChart.buildDrawingCache();
				new Thread(new Runnable() {
					
					@Override
					public void run() {
						Bitmap catchbitmap = LL_lineChart.getDrawingCache();
						Bitmap bitmap = Bitmap.createBitmap(catchbitmap, 40, 0, catchbitmap.getWidth() - 40,
								catchbitmap.getHeight() - 70);
						if (catchbitmap != null) {
							try {
								boolean sdCardExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED); // 判斷sd卡是否存在
								if (sdCardExist) // 如果SD卡存在,則獲取跟目錄
								{
									sdDir = Environment.getExternalStorageDirectory();// 獲取跟目錄
								} else {
									UIUtils.showToast(AppContentActivity.this, "SD卡內存不足", Toast.LENGTH_SHORT);
									return;
								}
								File myCaptureFile = new File(sdDir + "/appcontent" + selectTag + ".png");
								BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
								BitmapUtil.getRecordImage(bitmap, Color.parseColor("#dddcdc"), Color.parseColor("#e6e6e6"),
										lineColors).compress(Bitmap.CompressFormat.JPEG, 80, bos);// 將LL_lineChart區域截圖,並保存
								bos.flush();
								bos.close();
							} catch (Exception e) {
								e.printStackTrace();
							}
							final BitmapDrawable blueBitmap = new BitmapDrawable(BitmapUtil.getRecordImage(bitmap,
									Color.parseColor("#d2e5fb"), Color.parseColor("#e5f2fa"), lineColors));
							
							AppContentActivity.this.runOnUiThread(new Runnable() {
								
								@Override
								
								public void run() {
									LL_clickfirst.setBackgroundDrawable(getGrayBitmap(beforeSelectTag));
									LL_clickcontent.setBackgroundDrawable(blueBitmap);
									beforeSelectTag = selectTag;
									LL_clickfirst = LL_clickcontent;
								}
							});
						} else {
							AppContentActivity.this.runOnUiThread(new Runnable() {
								
								@Override
								
								public void run() {
									UIUtils.showToast(AppContentActivity.this, "截圖失敗", Toast.LENGTH_SHORT);
									Log.i("CACHE_BITMAP", "DrawingCache=null");
								}
							});
						}
						AppContentActivity.this.runOnUiThread(new Runnable() {
							@Override		
							public void run() {
								closeDialog();
							}
						});
						
					}
				}).start();

	}

第一步:new Thread
第二步:將耗時操作放在線程中
第三步:將需要放在UI線程中的操作放在Activity.this.runOnUiThread中



Android異步處理系列文章索引參考文獻:

http://blog.csdn.net/mylzc/article/details/6736988

Android異步處理一:使用Thread+Handler實現非UI線程更新UI界面


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章