2012-09-19 104 views
0

我想从一个线程发送消息到我的UI线程使用处理程序。我使用推送器API(pusher.com)发送消息。并且他们正在进入,我可以看到他们快速进入,但UI线程需要一段时间才能通过处理程序获取消息,并在队列中排队而不是发送并释放。发送消息与处理程序没有队列或延迟

有没有更好的方式做到这一点没有处理程序或一种方法来摆脱队列,以便一旦消息进入处理程序处理它呢?

这是发送已经走在了线程

public void onEvent(String eventName, String eventData, String channelName) { 

        String sentence = new String(eventData); 
        try { 

         Message msg = new Message(); 
         Bundle b = new Bundle(); 
         b.putString("message",sentence); 
         msg.setData(b); 
         // send message to the handler with the current message handler 
         mHandler.sendMessage(msg); 
          } catch (Exception e) { 
         Log.v("Error", e.toString()); 

          } 
        Log.e("server Thread", eventData); 
       // mHandler.obtainMessage(MakeLightActivity.PACKET_CAME,sentence).sendToTarget(); 


       } 

内部消息,这就是我看完我的UI线程内

private final Handler mHandler = new Handler() { 
    @Override 
    public void handleMessage(Message msg) { 



      Bundle b = msg.getData(); 
      String key = b.getString("message"); 
      incomingMessage = key; 
      if (key.length() >= 30){ 

       Log.d(TAG, "key" + key); 
      messageCame(key); 
      } 

     } 




}; 

回答

0

是的,有一个更好的办法 你必须使用AsyncTask来处理线程和Handler的功能。

private AsyncTask<Params, Progress, Result> imageLoader = new AsyncTask<Params, Progress, Result>() 
{ 
    @Override 
    protected Result doInBackground(Params) 
    { 
     // do the work and onPostExecute will handle the result 
     return result; 
    }; 

    protected void onPostExecute(Result result) 
    { 
     // do whatever with the result on the UI thread instead of a Handler 
    } 

}; 
+0

和我在我的活动中使用它,并移动我在我的单独线程中的代码? –