Runnables没有被Android中的Handler执行

时间:2013-01-21 04:31:00

标签: android multithreading handler runnable

我的android应用程序中有一个IntentService类,它将UDP数据包发送到服务器。在我之前的实现中,我没有使用处理程序,代码工作正常。我想在发送之前实现数据包的排队。所以我创建了两个runnables,分别用于写入和读取队列。并尝试使用处理程序执行它们。但是runnables没有被执行,并且抛出了NullPointerExecption。我认为我的处理程序实现有问题。我想知道使用处理程序执行runnables的正确方法。提前致谢。我在下面发布了一些代码片段和logcat:

wHandler = new Handler();
rHandler = new Handler();
writer = new Runnable(){
    public void run(){
            switch (pType) {
            case 0:
                while (send) {
                    queueMessageForSending(msg.getBytes());
                }
            case 1:
                // Float f = new Float(delayField.getString());
                // for(int i=0;i<2000;i++)
                while (send) {
                    try {
                        Thread.currentThread().sleep(delay);
                    } catch (Exception e) {
                    }
                    if(send)
                        queueMessageForSending(msg.getBytes());
                }
                // break;
            case 2:
                // for(int i=0;i<10000;i++)
                while (send) {
                    int u = want(30);
                    // int e=(int)Math.floor(-1*log(u)/(log((float)2.718)*2));
                    // System.out.println(e);
                    String data1 = "";
                    while ((u--) > 0)
                        data1 = data1 + msg;
                    if(send)
                        queueMessageForSending(data1.getBytes());
                }
                // break;
            case 3:
                //float f2 = Float.parseFloat(delayField.getText().toString());
                // for(int i=0;i<50;i++)
                while (send) {
                    int u = want(30);
                    // int e=(int)Math.floor(-1*log(u)/(log((float)2.718)*2));
                    System.out.println(u);
                    String data1 = "";
                    while ((u--) > 0)
                        data1 = data1 + msg;
                    System.out.println("data length :" + data1.length());
                    try {
                        Thread.currentThread().sleep(delay);
                    } catch (Exception e) {
                    }
                    if(send)
                        queueMessageForSending(data1.getBytes());
                }

            }
            wHandler.post(this);
        }
    };
    reader = new Runnable(){
        public void run(){
            while(send){
                if (!writeQueue.isEmpty())
                {
                    byte[] sendData = (byte[]) writeQueue.elementAt(0);
                    sendPacket(sendData);
                }
            }
            rHandler.post(this);
        }
    };

wHandler.post(writer);
rHandler.post(reader);

void sendPacket(byte[] data) {
    //if(socket!=null){
    try {
        System.out.println("\nClient:: Sending packet: " + " to " + addr
                + port);
        if(seq==100000)
        {
         seq=0;
        }
        Date d = new Date();
        Calendar c = Calendar.getInstance();
        c.setTime(d);
        String time = c.get(Calendar.HOUR_OF_DAY) + ":" +
        c.get(Calendar.MINUTE) + ":" +
        c.get(Calendar.SECOND);
    //System.out.println(time);
        long sentTime = c.getTime().getTime();
        //System.out.println(sentTime+"  "+seq);
        header=" "+seq+" "+sendData.length+"  "+sentTime+"  "+time+"  ";
        seq++;

        String s1= new String(sendData);
        String s2= header+s1;
       // System.out.println(s2);
        byte[] sendDataFinal = (byte[]) s2.getBytes();
        spacket = new DatagramPacket(sendDataFinal, sendDataFinal.length, addr, port);
        socket.send(spacket);
        writeQueue.remove(data);
        String resultTxt="Sent Packet at:"+DateFormat.format("MM/dd/yy h:mmaa", System.currentTimeMillis());
        broadcastIntent1.putExtra(PARAM_OUT_MSG, resultTxt);
        sendBroadcast(broadcastIntent1);
    } catch (Exception e) {
        System.out.println("Error:" + e.getMessage());
        e.printStackTrace();
        return;
    }
}

void queueMessageForSending(byte[] data)
{
    if (data.length > DEFAULT_DATAGRAM_SIZE)
    {
    throw new IllegalArgumentException(
    "Message too long: limit is " +
    DEFAULT_DATAGRAM_SIZE + " bytes");
    }
    synchronized(writeQueue)
    {
    writeQueue.addElement(data);
    writeQueue.notify();
    }
}

logcat的:

01-21 09:46:59.022: E/AndroidRuntime(915): FATAL EXCEPTION: IntentService[UdpService]
01-21 09:46:59.022: E/AndroidRuntime(915): java.lang.NullPointerException
01-21 09:46:59.022: E/AndroidRuntime(915):  at com.example.udpmessageclient.UdpSendService$1.run(UdpSendService.java:119)
01-21 09:46:59.022: E/AndroidRuntime(915):  at android.os.Handler.handleCallback(Handler.java:615)
01-21 09:46:59.022: E/AndroidRuntime(915):  at android.os.Handler.dispatchMessage(Handler.java:92)
01-21 09:46:59.022: E/AndroidRuntime(915):  at android.os.Looper.loop(Looper.java:137)
01-21 09:46:59.022: E/AndroidRuntime(915):  at android.os.HandlerThread.run(HandlerThread.java:60)

1 个答案:

答案 0 :(得分:0)

在这样的runnables中启动这些Thread

Thread t =new Thread(new Runnable() {

        public void run() {
            // do whatever you want to do inside runnable

            // after functionality inside runnable is complete...call handler
            Message msg= new Message();
            msg.what=1;
            h.sendMessage(msg);
        }
});

之后,您可以在handler

中执行所需的功能
 Handler h =new Handler(){
        public void handleMessage(android.os.Message msg)
        {
            // do whatever you want to do in handler            
        } 
    };