Luc*_*asM 5 java sockets multithreading android android-asynctask
我需要将一些数据从主线程发送到另一个线程。我已经阅读了很多关于线程、异步任务和处理程序的材料,但也许它们给我带来了一些困惑。我读到我需要为我的“第二个线程”创建一个处理程序,以便我可以从主线程向它发送消息(现在我不担心将任何内容发送回主线程)。
我需要第二个线程连接到服务器(通过套接字)并在某些用户事件上发送一些日期。我正在尝试以有效的方式执行此操作(不要打开/关闭不必要的套接字连接)。所以我想知道我应该把我的打开套接字命令放在哪里?此外,在我的处理程序的 handleMessage() 方法中,我需要对套接字输出流的引用,以便将数据发送到服务器。
我目前有以下代码:
protected void initThread(){
this.thread = new HandlerThread(WorkerHandler.class.getCanonicalName()){
@Override
public void run() {
super.run();
try{
handler = new WorkerHandler(getLooper());
}catch(Exception e){
e.printStackTrace();
}
}
};
this.thread.start();
}
Run Code Online (Sandbox Code Playgroud)
initThread() 方法在我的活动的 onCreate() 方法中调用。
下面是我的自定义处理程序类的代码:
public class WorkerHandler extends Handler {
protected Socket socket;
protected BufferedWriter writer;
public WorkerHandler(Looper looper) throws Exception{
super(looper);
this.socket = new Socket("192.168.1.7", 5069);
this.writer = new BufferedWriter(new OutputStreamWriter(this.socket.getOutputStream(), "utf-8"));
}
public BufferedWriter getWriter(){
return this.writer;
}
public Socket getSocket(){
return this.socket;
}
@Override
public void handleMessage(Message msg) {
Draw draw = (Draw) msg.obj;
if (draw != null){
if (getWriter() != null){
try{
getWriter().write(DrawUtil.toJson(draw)+"\n");
getWriter().flush();
}catch(IOException e){
e.printStackTrace();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
}
再次,在我的活动中,我触发了 sendDataToServer() 方法
protected void sendDataToServer(){
Draw draw = new Draw(getFlowType(), getID(), getSeq(), Calendar.getInstance(), startX, startY, endX, endY);
if (getWorkerHandler() != null){
Message msg = getWorkerHandler().obtainMessage();
msg.obj = draw;
getWorkerHandler().sendMessage(msg);
}
}
Run Code Online (Sandbox Code Playgroud)
但是我对 WorkerHandler 对象的引用始终为空。我很确定我误解了一些概念......你能给我一些提示吗?
非常感谢!
你不能这样做。您已经使用创建了第二个线程HandlerThread。AHandlerThread是一个Thread具有Looper. run()这就是方法中发生的事情HandlerThread。它正在运行 Looper 循环。这意味着run()中的方法HandlerThread只有在退出时才会完成Looper。
在你的initThread()方法中你写道:
@Override
public void run() {
super.run(); // <-- This call runs the Looper loop and doesn't complete!!
try{
handler = new WorkerHandler(getLooper());
}catch(Exception e){
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
您可以看到您的重写run()方法首先调用super.run(). 这会运行 Looper 循环但不会完成。所以你的其余代码initThread()永远不会执行。
如果你想使用 aHandlerThread()那么你就不能弄乱它的run()方法。如果您希望它为您做事,那么您需要Runnable向其发布消息,并在那里完成您的工作。这是一个例子:
HandlerThread handlerThread = new HandlerThread("myHandlerThread");
handlerThread.start();
// Now get the Looper from the HandlerThread so that we can create a Handler that is attached to
// the HandlerThread
// NOTE: This call will block until the HandlerThread gets control and initializes its Looper
Looper looper = handlerThread.getLooper();
// Create a handler attached to the background message processing thread
handler = new Handler(looper, this);
Run Code Online (Sandbox Code Playgroud)
现在您可以将消息和Runnable消息发布到“处理程序”。在此示例中,消息将由handleMessage()创建类的重写方法进行处理。
编辑:提供处理程序回调的代码示例
如果您像这样修改它,您可以使用您的WorkerHandler类来处理回调(我已将名称更改为,Worker因为它不是真正的Handler,它只是实现了Handler.Callback接口):
public class Worker implements Handler.Callback {
protected Socket socket;
protected BufferedWriter writer;
public Worker() throws Exception{
this.socket = new Socket("192.168.1.7", 5069);
this.writer = new BufferedWriter(new OutputStreamWriter(this.socket.getOutputStream(), "utf-8"));
}
public BufferedWriter getWriter(){
return this.writer;
}
public Socket getSocket(){
return this.socket;
}
@Override
public void handleMessage(Message msg) {
Draw draw = (Draw) msg.obj;
if (draw != null){
if (getWriter() != null){
try{
getWriter().write(DrawUtil.toJson(draw)+"\n");
getWriter().flush();
}catch(IOException e){
e.printStackTrace();
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在,您需要创建此类的实例Worker,并在创建Handler. 在您的活动中执行以下操作:
HandlerThread handlerThread = new HandlerThread("myHandlerThread");
handlerThread.start();
Looper looper = handlerThread.getLooper();
// Create an instance of the class that will handle the messages that are posted
// to the Handler
Worker worker = new Worker();
// Create a Handler and give it the worker instance to handle the messages
handler = new Handler(looper, worker);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10369 次 |
| 最近记录: |