Reputation: 11
can anybody tell me, how can get data(message) from message queue ? or how can send message from main thread to other thread ?.
Thanks
Upvotes: 1
Views: 10001
Reputation: 701
When an application first starts on a device
private final Handler handler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
if (WHAT == msg.what) {
textView.setMaxLines(msg.arg1);
textView.invalidate();
} else if (WHAT_ANIMATION_END == msg.what) {
setExpandState(msg.arg1);
} else if (WHAT_EXPAND_ONLY == msg.what) {
changeExpandState(msg.arg1);
}
super.handleMessage(msg);
}
};
You can use various technique to create a thread in android.
private void doAnimation(final int startIndex, final int endIndex, final int what) {
thread = new Thread(new Runnable() {
@Override public void run() {
if (startIndex < endIndex) {
// if start index smaller than end index ,do expand action
int count = startIndex;
while (count++ < endIndex) {
Message msg = handler.obtainMessage(WHAT, count, 0);
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.sendMessage(msg);
}
} else if (startIndex > endIndex) {
// if start index bigger than end index ,do shrink action
int count = startIndex;
while (count-- > endIndex) {
Message msg = handler.obtainMessage(WHAT, count, 0);
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.sendMessage(msg);
}
}
// animation end,send signal
Message msg = handler.obtainMessage(what, endIndex, 0);
handler.sendMessage(msg);
}
});
thread.start();
}
Please note: usually prepare() and loop() are already called in the Activity, so we should perform the following check:
if (Looper.myLooper() == null) {
Looper.prepare();
}
Upvotes: 0
Reputation: 54735
If you want to receive messages on a thread you should run a Looper and create a message Handler bound to this looper. The UI thread has a looper by default. There's a convenient class for creating threads with loopers called HandlerThread. Here's a good article about Handlers and Loopers: Android Guts: Intro to Loopers and Handlers.
EDIT:
HandlerThread thread = new HandlerThread("Thread name");
thread.start();
Looper looper = thread.getLooper();
Handler handler = new Handler(looper) {
@Override
public void handleMessage(Message msg) {
switch(msg.what) {
case SOME_MESSAGE_ID:
// SOME_MESSAGE_ID is any int value
// do something
break;
// other cases
}
}
};
handler.post(new Runnable() {
@Override
public void run() {
// this code will be executed on the created thread
}
});
// Handler.handleMessage() will be executed on the created thread
// after the previous Runnable is finished
handler.sendEmptyMessage(SOME_MESSAGE_ID);
Upvotes: 9
Reputation: 13501
not any other Thread.. you can sen it main Thread or Ui thread, using Handler
..
create handler and send a runnable object as anarguement..
Upvotes: 0