can anybody tell me,
how can get data(message) from message queue ?
or how can send message from main thread to other thread ?.
Thanks
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);
not any other Thread.. you can sen it main Thread or Ui thread, using Handler..
create handler and send a runnable object as anarguement..
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();
}
Related
this is a piece of code from my project, i need this thread to be over untill the end and only then go to the last Log.i() and finish the function.
public void delay3Seconds(final String txt1, final String txt2, final String s, final Intent i)
{
//keepMoving= false;
counter= 3;
secondsBool= true;
if(!errorMonitor)
{
Log.i("Main.delay3Seconds()", s+" in 3 seconds");
new Thread()
{
public void run()
{
while(secondsBool)
{
try {
Thread.sleep(1500);
}
catch (InterruptedException e){e.printStackTrace();}
if(!errorMonitor)
{
handler.post(new Runnable()
{
public void run()
{
final DialogFragment loadDF= new RecDialog(MainActivity.this, txt1, txt2, s+(counter--)+" שניות", null, false, true, ll.getWidth(), ll.getHeight());
loadDF.show(getSupportFragmentManager(), "RecDialog");
dialog.dismiss();
dialog= loadDF;
if(counter == 0)
secondsBool= false;
}
});
}
else
secondsBool= false;
}
if(!errorMonitor)
{
handler.post(new Runnable()
{
public void run()
{
dialog.dismiss();
if (i.resolveActivity(getPackageManager()) != null)
{
Log.i("Main.delay3Seconds()", "resolveActivity != null");
setResolveNotFail(true);
Log.i("Main.delay3Seconds()", "resolveNotFail = "+resolveNotFail);
startActivity(i);
}
else
{
Log.i("Main.delay3Seconds()", "resolveActivity == null");
setResolveNotFail(false);
Log.i("Main.delay3Seconds()", "resolveNotFail = "+resolveNotFail);
}
}
});
}
}
}.start();
}
Log.i("Main.delay3Seconds()", "(end) resolveNotFail = "+resolveNotFail);
}
i can't figure out how to do that. i tried using synchronized(), but i probably use it wrong because the function finishes itself first and only then the thread works, simultaneously to the activity.
i would appreciate any tips on how to do that..
That's absolutely not how or why you use a Thread. First off, if this is the UI thread you should never pause it for 3 seconds. Second, the entire point of a Thread is to work in parallel. You never want one thread to pause and wait for another. If you need something on Thread A to occur only when Thread B is done, you send a message via a handler, semaphore or other method to Thread A when Thread B is done.
Looking at your code, it seems like you should throw it out and reimplement it with a timer.
https://docs.oracle.com/javase/tutorial/essential/concurrency/join.html
Just call the .join() method after you start your thread so the calling thread will wait until your new thread executes.
Something like this:
Thread t = new Thread(...);
t.start();
t.join();
i want to do some stuff on every few seconds in my app, for that purpose , i have implemented HandlerThread & handler via following code
handlerThread = new HandlerThread(getClass().getSimpleName());
handlerThread.start();
handler = new Handler(handlerThread.getLooper(), new Callback() {
#Override
public boolean handleMessage(Message msg) {
//my code here
return l.this.handleMessage(msg);
}
});
I initiate this handler by sending message from onCreate()
I handle the message as follows :
private boolean handleMessage(Message msg) {
switch (msg.what) {
default:
return false;
case MY_MESSAGE:
if(handler_stop==0)
{
checkLauncher();
sendMessage(MY_MESSAGE); // I Send the message from here to make //this continuous
}
}
return true;
}
It's Working fine but it Sends message too fast , i mean constantly , instead i want this message to be sent after 2 or 3 seconds , In Short , i want to repeat task every 2-3 seconds.
How can i do this on above code ? please some one help
First declare one global varialbe for Handler to update the UI control from Thread, like below:
Handler mHandler = new Handler();
Now create one Thread and use while loop to periodically perform the task using the sleep method of the thread.
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while (true) {
try {
Thread.sleep(10000);// change the time according to your need
mHandler.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
// Write your code here to update the UI.
}
});
} catch (Exception e) {
// TODO: handle exception
}
}
}
}).start();
Else just add this in your code:
handler.postDelayed(new Runnable(){
public void run() {
// do something
}}, 20000);
Why not to use Handler.sendMessageDelayed? It allows you to schedule your message to be delivered to the Handler with delay that you specify. So your code will look like this:
private boolean handleMessage(Message msg) {
switch (msg.what) {
default:
return false;
case MY_MESSAGE:
if(handler_stop == 0) {
checkLauncher();
sendMessageDelayed(MY_MESSAGE, 2000); // Send message everytime with 2 seconds delay
}
}
return true;
}
hi i have an simple way for doing this
try this
Runnable runnable;
final Handler handler = new Handler();
runnable = new Runnable() {
public void run() {
// HERE I AM CHANGING BACKGROUND YOU CAN DO WHATEVER YOU WANT
_images[i].setBackgroundResource(imageArray[0]);
i++;
handler.postDelayed(this, 1000); // for interval...
}
};
handler.postDelayed(runnable, 1000); // for initial delay..
worked for me hope you will also find it working
thanks
Vote Up if find usefull.
i want to start Asynchoronous task after some sleep time. For that i am using thread and i start my asynchronous task in that thread finally block. But it gives cant create a handler inside a thread exception.
i am using the following logic.
thread= new Thread()
{
public void run()
{
try
{
int waited = 0;
while (waited < 300)
{
sleep(100);
waited += 100;
}
}
catch (InterruptedException e)
{
// do nothing
}
finally
{
Load ld=new Load();
ld.execute();
}
}
};
thread.start();
Well, first of all, if the final goal is to run AsyncTask after some delay, I would use Handler.postDelayed instead of creating separate Thread and sleeping there:
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
new Load().execute();
}
}, 300); //300ms timeout
But, if you really wanna make fun of Android, you can create HandlerThread - special thread which has looper in it, so your AsyncTask will not be complaining anymore:
thread= new HandlerThread("my_thread")
{
public void run()
{
try
{
int waited = 0;
while (waited < 300)
{
sleep(100);
waited += 100;
}
}
catch (InterruptedException e)
{
// do nothing
}
finally
{
Load ld=new Load();
ld.execute();
}
}
};
thread.start();
Please note that you are responsible for calling quit() on this thread. Also I'm not sure what happens if you quit this thread before AsyncTask is done. I don't remember where AsyncTask posts its results - to the main thread, or to the thread it was called from...
In any case, second option is just a mess, so don't do it:) Use the first one
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// Do whatever you want.
}
}, SPLASH_TIME_OUT);
}
You can use like above. there SPLASH_TIME_OUT is the millisecond value that u want to make a delay.
Use Handler class, and define Runnable YourAsyncTask that will contain code executed after sleepTime
mHandler.postDelayed(YourAsyncTask, sleepTime);
You must run AsyncTask in UI thread, so you can use something like this:
class YourThread extends Thread{
private Activity _activity;
public YourThread(Activity _activity){
this activity = _activity;}
public void run()
{
try
{
int waited = 0;
while (waited < 300)
{
sleep(100);
waited += 100;
}
}
catch (InterruptedException e)
{
// do nothing
}
finally
{
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Load ld=new Load();
ld.execute();
}
});
}
}
}
and in your activity call thread like this:
YourThread thread = new YourThread(this);
thread.start();
also note: use soft reference to activity or do not forget kill thred when activity will be destroyed.
just do your like below code:
define a thread globally.
public static Thread thread;
thread= new Thread() {
public void run() {
sleep(time);
Message msg = setTextHandler.obtainMessage(2);
setTextHandler.sendMessage(msg);
}
};
thread.start();
and your handler look like
private final Handler setTextHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
if (thread!= null) {
thread.interrupt();
thread= null;
}
switch (msg.what) {
case 2: //do your work here
Load ld=new Load();
ld.execute();
break;
}
}
};
I have a child thread running to do a task infinitely. I want to (1) constantly send data back to the UI thread, and (2) occasionally send data (corresponding to buttons) to the child thread to pause/continue the infinite task. My problem is that the child thread gets stuck in the looper, meaning the task does not execute.
My questions is this: How do I get the child thread to receive messages from the UI thread without blocking the infinite task?
This is what I have so far:
For task (1), I have a handler in my UI thread, which works, and an infinite loop in the child thread that sends back a message, which works by itself.
In UI thread:
mMainHandler = new Handler() {
public void handleMessage(Message msg) {
Bundle b;
b = msg.getData();
if (msg.what==1)
Log.i("main", "from child (running) - " + b.getBoolean("running"));
else if (msg.what == 2)
Log.i("main", "from child (count) - " + b.getInt("count"));
}
};
In child thread (currently using a dummy task until I get the framework worked out):
while (true) {
if (running) {
try {
curCount += up;
if (curCount == maxCount)
up = -1;
else if (curCount == minCount)
up = 1;
Thread.sleep(1000);
} catch (InterruptedException e) {
Log.e("", "local Thread error", e);
}
Bundle b = new Bundle(1);
b.putInt("count", curCount);
Message toMain = mMainHandler.obtainMessage();
toMain.what = 2;
toMain.setData(b);
mMainHandler.sendMessage(toMain);
}
}
For task (2), I have a method in my UI thread corresponding to a button press that sends a message to the child thread, which works, and a handler in the child thread, which works by itself.
In UI thread:
private void sendRunning(boolean running) {
if (mChildHandler != null) {
Bundle b = new Bundle(1);
b.putBoolean("running", running);
Message msg = mChildHandler.obtainMessage();
msg.what = 1;
msg.setData(b);
mChildHandler.sendMessage(msg);
}
}
In child thread:
Looper.prepare();
mChildHandler = new Handler() {
public void handleMessage(Message msg) {
Bundle b;
if (msg.what==1){
b = msg.getData();
running = b.getBoolean("running");
Log.i(INNER_TAG, "from main (running) - " + b.getBoolean("running"));
Log.i(INNER_TAG, "running - " + running);
try {
Message toMain = mMainHandler.obtainMessage();
toMain.what = 1;
toMain.setData(b);
mMainHandler.sendMessage(toMain);
} finally {}
}
}
};
Looper.loop();
Each one of those scenarios works fine alone, but trying to do both at the same time is the problem. If I put the infinite task after the Looper.loop(), it is never reached. If I put it before the Looper.prepare(), it is run once. If I put it withing the looper, it is still only run once.
Any ideas would be greatly appreciated :)
Here is my full code (minus package/imports) for reference:
public class MainActivity extends Activity {
Thread thread;
private Handler mMainHandler, mChildHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMainHandler = new Handler() {
public void handleMessage(Message msg) {
Bundle b;
b = msg.getData();
if (msg.what==1)
Log.i("main", "from child (running) - " + b.getBoolean("running"));
else if (msg.what == 2)
Log.i("main", "from child (count) - " + b.getInt("count"));
}
};
thread = new ChildThread();
thread.start();
// Get a reference to the button
Button buttonStart = (Button)findViewById(R.id.btnStart);
Button buttonStop = (Button)findViewById(R.id.btnStop);
// Set the click listener to run my code
buttonStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this,
"Starting...", Toast.LENGTH_SHORT).show();
sendRunning(true);
}
});
buttonStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this,
"Stopping...", Toast.LENGTH_SHORT).show();
sendRunning(false);
}
});
}
private void sendRunning(boolean running) {
if (mChildHandler != null) {
Bundle b = new Bundle(1);
b.putBoolean("running", running);
Message msg = mChildHandler.obtainMessage();
msg.what = 1;
msg.setData(b);
mChildHandler.sendMessage(msg);
}
}
#Override
protected void onDestroy() {
Log.i("tag", "stop looping the child thread's message queue");
mChildHandler.getLooper().quit();
super.onDestroy();
}
class ChildThread extends Thread {
private static final String INNER_TAG = "ChildThread";
private boolean running = true;
final int maxCount = 10;
final int minCount = 0;
public int curCount = minCount;
private int up = 1;
public void run() {
while (true) {
if (running) {
try {
curCount += up;
if (curCount == maxCount)
up = -1;
else if (curCount == minCount)
up = 1;
Thread.sleep(1000);
} catch (InterruptedException e) {
Log.e("", "local Thread error", e);
}
Bundle b = new Bundle(1);
b.putInt("count", curCount);
Message toMain = mMainHandler.obtainMessage();
toMain.what = 2;
toMain.setData(b);
mMainHandler.sendMessage(toMain);
}
this.setName("child");
Looper.prepare();
mChildHandler = new Handler() {
public void handleMessage(Message msg) {
Bundle b;
if (msg.what==1){
b = msg.getData();
running = b.getBoolean("running");
Log.i(INNER_TAG, "from main (running) - " + b.getBoolean("running"));
Log.i(INNER_TAG, "running - " + running);
try {
Message toMain = mMainHandler.obtainMessage();
toMain.what = 1;
toMain.setData(b);
mMainHandler.sendMessage(toMain);
} finally {}
}
}
};
Log.i(INNER_TAG, "Child handler is bound to - " +
mChildHandler.getLooper().getThread().getName());
Looper.loop();
}
}
}
}
Just Use Intent service rather then this thread so you can manage all UI of your update and what ever you want to do with UI in intent service one broadcast receiver is using and its very easy to handle threads and infect your your UI is nit hand or lock while your background process run .
I ended up just using a variable time for the thread to avoid the situation. Thanks for the advice.
hi i am working on custom toast , and i am able to do that, but after when i move to next activity the thread is running or active of back activity , so what should i do for removing that thread or stop this thread.
my code is given below :
public void customToast(int x, int y, String str) {
if (Util.tipson == true) {
toast = new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP, x, y);
LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
toastView = li.inflate(R.layout.toastlayout, null);
toast.setView(toastView);
TextView text = (TextView) toastView.findViewById(R.id.text);
text.setText(str);
// toast.show();
fireLongToast();
}
}
private void fireLongToast() {
t = new Thread() {
public void run() {
int count = 0;
try {
while (true && count < 40) {
try {
toast.show();
sleep(100);
count++;
} catch (Exception e) {
// TODO: handle exception
}
// do some logic that breaks out of the while loop
}
toast = null;
toastView = null;
} catch (Exception e) {
Log.e("LongToast", "", e);
}
}
};
t.start();
}
You Need to stop your thread by yourself. Since java doesn't allow you to use stop() function.
Write class for your Thread as this
public class YourThread extends Thread {
private volatile boolean stopped = false;
public void run() {
int count = 0;
try {
while (true && count < 40 && !stopped) {
try {
toast.show();
sleep(100);
count++;
} catch (Exception e) {
// TODO: handle exception
}
// do some logic that breaks out of the while loop
}
toast = null;
toastView = null;
} catch (Exception e) {
Log.e("LongToast", "", e);
}
}
public void stopThread() {
stopped = true;
}
}
Now when your Activity which has the Thread Finishes stop Your thread
#Override
protected void onDestroy() {
if(isFinishing())
yourThreadVariable.stopThread();
}
Dont know for sure, but you can call the function join of thread in onDestroy of your activity.
To stop the thread you can just use interrupt(). But for better solution I would say not to use Thread. Just create a Handler with Runnable and manage your Runnable using Handler, that would be a nice way as Android has given Handler for managing one or more Runnables.
Creating a Runnable
Runnable runnable = new Runnable() {
#Override
public void run() {
// put your code stuff here
}
};
To start Runnable use
handler.postDelayed(runnable, your_time_in_millis);
To stop Runnable use
handler.removeCallbacks(runnable);
Does finishing the activity have any effect?
I would like to suggest Lalit Poptani method too and implement this:
protected void onStop(){
handler.removeCallbacks(runnable);
super.onStop();
}
The documentation for the method:
onStop,Called when the activity is no longer visible to the user, because another activity has been resumed and is covering this one. This may happen either because a new activity is being started, an existing one is being brought in front of this one, or this one is being destroyed.
http://developer.android.com/reference/android/app/Activity.html