当前位置: 代码迷 >> Android >> 【安卓】线程小结
  详细解决方案

【安卓】线程小结

热度:57   发布时间:2016-04-28 04:25:22.0
【安卓】线程总结

安卓中控制线程其实我们之前在JAVA中原理并没有多少区别,只是因为我们不能直接利用Thread让这个线程运行起来,而是要通过一个中间

?

安卓中控制线程:
1、创建一个继承自View的类
2、定义一个Handler类对象handler,创建Callback的一个对象,重写其中的handleMessage方法,让它可以进行重绘,并传给handler。
3、重写onDraw方法
4、创建线程并启动

?

?

import java.util.ArrayList;import java.util.Random;import android.content.Context;import android.graphics.Bitmap;import android.graphics.Bitmap.Config;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.os.Handler;import android.os.Handler.Callback;import android.os.Message;import android.util.AttributeSet;import android.view.MotionEvent;import android.view.View;public class DrawView extends View {	private Bitmap bitmap;	private Canvas canvas;	private Paint paint = new Paint();	private ArrayList<Ball> list = new ArrayList<Ball>();	private Handler handler;	public DrawView(Context context) {		this(context, null);	}	public DrawView(Context context, AttributeSet attrs) {		this(context, attrs, 0);	}	public DrawView(Context context, AttributeSet attrs, int defStyle) {		super(context, attrs, defStyle);		// 实例化handler		handler = new Handler(callback);		// 创建并启动线程		Thread t = new Thread(r);		t.start();	}	// 重写onDraw方法	public void onDraw(Canvas canvas) {		// 实例化bitmap和canvas		if (bitmap == null) {			bitmap = Bitmap.createBitmap(this.getWidth(), this.getHeight(),					Config.ARGB_8888);			this.canvas = new Canvas(bitmap);			canvas.drawColor(Color.RED);		}		// 循环遍历画出小球		for (int i = 0; i < list.size(); i++) {			Ball ball = list.get(i);			ball.move();			ball.draw(canvas);		}		canvas.drawBitmap(bitmap, 0, 0, paint);	}	public boolean onTouchEvent(MotionEvent event) {		switch (event.getAction()) {		case MotionEvent.ACTION_UP:			float x = event.getX(),			y = event.getY();			// 随机x和y,vx,vy			Random r = new Random();			float vx = 1 + r.nextInt(3),			vy = 1 + r.nextInt(3);			// 新增一个ball			Ball ball = new Ball(x, y, vx, vy);			list.add(ball);			break;		}		return true;	}	public Callback callback = new Callback() {		public boolean handleMessage(Message msg) {			invalidate();			return false;		}	};	public Runnable r = new Runnable() {		public void run() {			while (true) {				try {					Thread.sleep(100);				} catch (InterruptedException e) {					// TODO Auto-generated catch block					e.printStackTrace();				}				handler.sendEmptyMessage(0);			}		}	};}

?
??????????? 但是当我们启动线程的时候,我们可能需要读取很多数据,比如图片,如果我们在线程里面再去提取我们所需要的图片的话,这个线程会变得相当卡。我们在玩游戏的时候,经常会发现游戏会出现“游戏正在加载中”这样的进度条,这就是在进行数据加载的工作,先把我们所需要的数据先读取到内存中,我们在线程中只需要调用就可以了。这个时候我们需要一个继承自Application的类,来实现我们加载数据的方法loa()。同时,我们还需要在AndroidManifest中把Application中的Name设置为MyApplication。

?

?

??????????? 我们这时候讲到计时器的实现方法,其实代码很简单,我们只需要实例化一个Timer类的对象,实例化TimerTask的对象并实现抽象方法。

		// 计时器		Timer timer = new Timer();		TimerTask task = new TimerTask() {			public void run() {				application.getList().add(new Ball(0, 0, 1, 1));			}		};		timer.schedule(task, 1000, 5000);//每5秒进行一次任务

?下面还是上代码:

?

?

//Ball类import android.graphics.Bitmap;import android.graphics.Canvas;import android.graphics.Paint;public class Ball extends Entity {	private float x, y, vx, vy;	private Paint paint = new Paint();	public Ball(float x, float y, float vx, float vy) {		this.x = x;		this.y = y;		this.vx = vx;		this.vy = vy;	}	public void draw(Canvas canvas) {		// Bitmap bitmap = MyApplication.		/*		 * // 保存旋转之前的状态		 * 		 * canvas.save(); canvas.rotate(4, 40, 40);		 * 		 * // 还原状态 canvas.restore();		 */		Bitmap bitmap = MyApplication.getInstance().getBitmap("first");		canvas.drawBitmap(bitmap, x, y, paint);	}	public void move() {		x += vx;		y += vy;	}}

?

?

import java.io.IOException;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import android.app.Application;import android.content.Context;import android.graphics.Bitmap;import android.graphics.BitmapFactory;public class MyApplication extends Application {	public ArrayList<Entity> list = new ArrayList<Entity>();	private HashMap<String, Bitmap> maps = new HashMap<String, Bitmap>();	private static MyApplication instance;	public MyApplication() {		super();		instance = this;	}	public static MyApplication getInstance() {		return instance;	}	public List<Entity> getList() {		return list;	}	public void load(Context context) {		try {			Bitmap img = BitmapFactory.decodeStream(context.getResources()					.getAssets().open("first.jpg"));			maps.put("first", img);			img = BitmapFactory.decodeStream(context.getResources().getAssets()					.open("second.jpg"));			maps.put("second", img);		} catch (IOException e) {			e.printStackTrace();		}	}	// 得到我们需要的图片的缓冲图的方法	public Bitmap getBitmap(String string) {		return maps.get(string);	}}

?

import java.util.List;import java.util.Timer;import java.util.TimerTask;import android.content.Context;import android.graphics.Canvas;import android.graphics.Color;import android.util.AttributeSet;import android.view.SurfaceHolder;import android.view.SurfaceHolder.Callback;import android.view.SurfaceView;public class MySurfaceView extends SurfaceView implements Callback, Runnable {	private SurfaceHolder holder;	private MyApplication application;	public MySurfaceView(Context context) {		this(context, null);	}	public MySurfaceView(Context context, AttributeSet attrs) {		this(context, attrs, 0);	}	public MySurfaceView(Context context, AttributeSet attrs, int defStyle) {		super(context, attrs, defStyle);		holder = this.getHolder(); //		holder.addCallback(this); // 添加回调接口		application = (MyApplication) context.getApplicationContext();		application.load(context);		application.getList().add(new Ball(100, 100, 1, 1));		// 计时器		Timer timer = new Timer();		TimerTask task = new TimerTask() {			public void run() {				application.getList().add(new Ball(0, 0, 1, 1));			}		};		timer.schedule(task, 1000, 5000);// 每5秒进行一次任务	}	public void surfaceCreated(SurfaceHolder holder) {		// 在创建的时候的时候启动线程		Thread t = new Thread(this);		t.start();	}	public void surfaceChanged(SurfaceHolder holder, int format, int width,			int height) {	}	public void surfaceDestroyed(SurfaceHolder holder) {	}	public void run() {		while (true) {			try {				Thread.sleep(100);			} catch (InterruptedException e) {				e.printStackTrace();			}			Canvas canvas = null;			try {				// 得到画布对象				canvas = holder.lockCanvas();				canvas.drawColor(Color.BLACK);				List<Entity> list = application.getList();				for (int i = 0; i < list.size(); i++) {					Entity e = list.get(i);					e.draw(canvas);					e.move();				}			} catch (Exception e) {				e.printStackTrace();			} finally {				if (canvas != null)					holder.unlockCanvasAndPost(canvas);			}		}	}}

?

?

?

  相关解决方案