首先得明白 这是浅谈, 也就是说研究不深入,后续会继续跟踪.

我个人认为 android 线程间通信用 Handler +Message 方式.

进程间通信用AIDL.

呵呵,深知自己能力很差, 只是个人理解,希望明白的告诉我下.

为什么说 handler主要用于线呈间通信呢?


Java代码
package com.ray.handler;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.view.View;

public class BounceView extends View {
float x = 40;

public BounceView(Context context) {
super(context);
}

@Override
protected void onDraw(Canvas canvas) {
x+=10;
Paint mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setColor(Color.GREEN);
canvas.drawCircle(x, 40, 40, mPaint);
}
}

上面的代码就是实现了一个简单的Widget .


package com.ray.handler;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;

public class TestHandler extends Activity {
protected static final int GUIUpdateIDENTIFIER = 0x101;

Thread myRefreshThread = null;
BounceView myBounceView = null;

Handler myHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case TestHandler.GUIUpdateIDENTIFIER:
myBounceView.invalidate();
break;
}
super.handleMessage(msg);
}
};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);

this.myBounceView = new BounceView(this);
this.setContentView(this.myBounceView);
new Thread(new myThread()).start();
}

class myThread implements Runnable {
public void run() {
while (!Thread.currentThread().isInterrupted()) {

[color=White][color=White][color=Red] Message message = new Message();
message.what = TestHandler.GUIUpdateIDENTIFIER;

TestHandler.this.myHandler.sendMessage(message);
[/color][/color][/color]
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
}

红色这几句很诡异,就是用来给Ui主线程发消息.  UI主线程据说有消息队列,呵呵.Handler在哪个现成创建的.默认就和哪个线程的Looper 绑定. 就可以往哪个线程的消息队列丢消息.

我现在还不太明白的是.  Handler丢了消息,  在绑定的线程中 为什么Handler又能处理消息呢?

Handler Looper关系还要进一步研究.

主要是为了定时,或中断,或通知更新UI. 又不使UI反应停止或太慢,用多线程发消息办法很不错.

呵呵,多少有点收获吧,回帖子吧?

更多相关文章

  1. 浅析Android中的消息机制-解决:Only the original thread that cr
  2. Android异步消息机制之Handler
  3. Android的Handler机制详解3_Looper.looper()不会卡死主线程
  4. Android之Handler用法总结
  5. Android开发之消息处理机制(一)——Handler
  6. Android异步加载图像小结 (含线程池,缓存方法)
  7. android 面试题集
  8. Titanium 使用刘明星的Jpush module做android端的消息推送
  9. android 电容屏(二):驱动调试之基本概念篇

随机推荐

  1. androidQ 访问SD卡权限问题
  2. java后台接收android客户端通过http方式
  3. android 通过handler实现异步处理
  4. android Textview颜色渐变
  5. android用于打开各种文件的intent
  6. android PopupWindow 底部阴影外部空间取
  7. Android(安卓)BaseExpandableListAdapter
  8. Android:横行滚动且隔行变色的ListView控
  9. Android屏幕点亮(常亮)及屏幕解锁和锁定
  10. Android(安卓)关于wifi管理的代码