Java 使用处理程序发送消息,无需排队或延迟
我正在尝试使用处理程序将消息从一个线程发送到我的UI线程。我正在使用pusher API(pusher.com)发送消息。它们很快就出现了,我可以看到它们很快就出现了,但是UI线程需要一段时间才能通过处理程序获取消息,并且它会对消息进行排队,而不是在有消息出现时立即发送和释放 有没有更好的方法不用处理程序就可以做到这一点,或者有没有一种方法可以摆脱队列,以便在消息传入处理程序时立即处理它 这是在发送线程内部传入的消息Java 使用处理程序发送消息,无需排队或延迟,java,android,handler,pusher,Java,Android,Handler,Pusher,我正在尝试使用处理程序将消息从一个线程发送到我的UI线程。我正在使用pusher API(pusher.com)发送消息。它们很快就出现了,我可以看到它们很快就出现了,但是UI线程需要一段时间才能通过处理程序获取消息,并且它会对消息进行排队,而不是在有消息出现时立即发送和释放 有没有更好的方法不用处理程序就可以做到这一点,或者有没有一种方法可以摆脱队列,以便在消息传入处理程序时立即处理它 这是在发送线程内部传入的消息 public void onEvent(String eventName, S
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);
}
}
};
是的,有更好的办法
必须使用处理线程和处理程序功能的AsyncTask
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
}
};
private AsyncTask imageLoader=new AsyncTask()
{
@凌驾
受保护的结果doInBackground(参数)
{
//执行该工作,onPostExecute将处理结果
返回结果;
};
受保护的void onPostExecute(结果)
{
//对UI线程上的结果而不是处理程序执行任何操作
}
};
我在我的活动中使用它,并在其中移动我在单独线程中的代码?