postDelayed() with messages Android - java

I want my main UI thread to effectively "sleep" for 1 second before sending an empty message to a worker thread to perform some operation.
Sleep() is a problem for me because I cannot quit() the threads properly while it is performing sleep(), so I want to change it to postDelayed(runnable r, long msDelay) but it takes runnable object, not Message. How can I change this code? I am just passing empty message from main UI thread to worker thread.
UI thread:
public class MainActivity extends Activity
{
static Worker w1, w2;
static Handler mainUIHandler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
String sender = msg.getData().getString("SENDER");
if (Objects.equals(sender, "CPU1"))
{
mInfoTextView.setText("worker 1 thinking...");
//how to change the following 2 lines to postDelayed()?
try{
Thread.sleep(1000);
} catch (Exception ignored) { }
w2.handler.sendMessage(w2.handler.obtainMessage());
}
}
};
...
}
and the worker thread
class Worker extends HandlerThread
{
...
Worker(String name)
{
super(name);
}
Handler handler= new Handler()
{
#Override
public void handleMessage(Message msg)
{
//perform work
Foo work = dowork();
//communicate work to the UI thread to update the display
Message message = MainActivity.mainUIHandler.obtainMessage();
Bundle bundle = new Bundle();
bundle.putString("NAME", name);
bundle.putInt("work", work);
message.setData(bundle);
MainActivity.mainUIHandler.sendMessage(message);
}
};
#Override
public void run()
{
this.setName(WorkerThread.class.getName());
this.setPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
}
}
I tried creating a new Runnable() and passing it to postDelayed():
w2.handler.postDelayed(new Runnable()
{
#Override
public void run()
{
System.out.println("hello");
}
}, 1000);
but it's not triggering the handler in w2

You can delay a Message with Handler.sendMessageDelayed():
public class MainActivity extends Activity {
// ...
static Handler mainUIHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
// ...
w2.handler.sendMessageDelayed(w2.handler.obtainMessage(), 1000);
}
}
}

Related

Android HandlerThread update UI without UiHandler

this code works fine and update my "TextView" and also show "Toast"
and that is my Headache as I have tried to to pass A Runnable obj Without including my UiHandler on it as it suppose to be the bridge to update my UI Thread but my activity got updated with no single Error ?????
This not suppose to be as CustomHandlerThread should be A different thread
why this happen ?
My Activity
public class TestActivity extends BaseActivity {
Runnable task;
#BindView(R.id.send_test_message)
Button send_test_message;
private Handler mUiHandler = new Handler();
private MyWorkerThread mWorkerThread;
#Override
public void initViews() {
}
#Override
public void attachViewsListeners() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_activity);
ButterKnife.bind(this);
task = new Runnable() { ///this is normally work I have no problem with
///that
#Override
public void run() {
mUiHandler.post(new Runnable() {
#Override
public void run() {
send_test_message.setText("Change--->1");
}
});
}
};
}
#Override
protected void onStart() {
super.onStart();
mWorkerThread = new MyWorkerThread("myWorkerThread");
mWorkerThread.start();
mWorkerThread.prepareHandler();
mWorkerThread.postTask(task);
mWorkerThread.postTask(new Runnable() { /// why this task work with no
///error ?
#Override
public void run() {
send_test_message.setText("Change--->2");
}
});
}
#Override
protected void onDestroy() {
mWorkerThread.quit();
super.onDestroy();
}
my HandlerThread
//MyWorkerThread.java
public class MyWorkerThread extends HandlerThread {
Handler mWorkerHandler;
public MyWorkerThread(String name) {
super(name);
}
public void postTask(Runnable task) {
mWorkerHandler.post(task);
}
public void prepareHandler() {
mWorkerHandler = new Handler(getLooper());
Log.e("MyWorkerThread--->",Looper.myLooper().getThread().getName()); //-->main
Log.e("MyWorkerThread--->",getLooper().getThread().getName());//-->//myWorkerThread
Log.e("MyWorkerThread--->",Thread.currentThread().getName()); //-->main
}
}
I followed this link as A Referance
is My thread running on the MainThread or getLooper() intialize my
HandlerThread with MainThread Looper ,is those log message are true
please illuminate me
After fill day of debugging i Found out That if i post A Runnable to my
mWorkerThread with sleep() as here i got " Only the original thread that created a view hierarchy can touch its views."
as should be.. but until I know why it not works without it
I wish it would help some one.
try {
TimeUnit.SECONDS.sleep(2);
send_test_message.setText("Change--->");
} catch (Exception e) {
e.printStackTrace();
}

Send message to UI thread

I create a thread to listening the input stream of the serial port.
And when there is input data coming, I want to send a message to UI thread.
Before doing my task, I try to send message from the thread with interval 5000 ms, and send a message to UI thread and Toast it.
From the log, I know that the thread is created and running succefully, but the number is not toasted in the UI thread.
I think it may be due to fail to send a message from the thread to UI thread, or fail to handle the message in the MessageQueue of UI thread.
What's wrong with my code?
Many thanks!
MainActivity.java:
public class MainActivity extends Activity {
...
#Override
protected void onCreate(Bundle savedInstancesState) {
...
setMessageProcessor();
SerialPortListener.start();
}
private void setMessageProcessor() {
new Handler(Looper.getMainLooper()) {
public void handleMessage(Message msg) {
Toast.makeText(MainActivity.this,
"Message: " + msg.obj.toString(),
Toast.LENGTH_SHORT).show();
}
};
}
}
SerialPortListener.java:
public class SerialPortListener {
...
private static int testNumber = 1;
public static void start() {
...
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
while (true) {
Message msg = new Message();
msg.obj = testNumber++;
new Handler(Looper.getMainLooper()).sendMessage(msg);
Log.i("TEST", "TEST);
try {
Thread.sleep(5000);
} catche(Exception e) {
...
}
}
}
});
thread.start();
}
}
It's because you are creating a second Handler bound to the main thread from within your "reader thread". Don't use an anonymous object for the handler in the main thread, make it a member field. Then in your reader thread, send the Message to that specific Handler:
private void setMessageProcessor() {
mHandler = new Handler() {
...
}
}
public class SerialPortListener {
...
private static int testNumber = 1;
public static void start() {
...
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
while (true) {
Message msg = mHandler.obtainMessage();
msg.obj = testNumber++;
msg.sendToTarget();
Log.i("TEST", "TEST);
...
}
}
}

Is it possible to perform separate network thread within a same activity without wait?

I am performing two class which is extending ASyncTask and both have different functions but because of the second class my first class is lagging. So what i want to know is, is there any better solution to code in such a way that both of the operation will perform the task without making other operation to wait?
Updated with code
For the first call in the onCreate()
new connection().execute(); //
Some task performed by the same class called
public class connection extends AsyncTask {
#Override
protected Object doInBackground(Object... arg0) {
//some operation
return value;
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
String m = String.valueOf(o);
if (o != null) {
someoperation
} else {
edittxt.setTextColor(Color.RED);
edittxt.setText("No Internet Connection");
}
}
}
similarly i am performing the other class that i have.
You can use AsyncTask.executeOnExecutor with THREAD_POOL_EXECUTOR, the default executor is SERIAL_EXECUTOR.
You can create two separate threads and perform your operations. It will quarantine, that all operations will be performed async.
final Handler handler = new Handler();
Thread operation1 = new Thread(new Runnable() {
#Override
public void run() {
doOperation1();
handler.run(new Runnable(){
#Override
public void run() {
onPostExecute1();
}
});
}
});
Thread operation2 = new Thread(new Runnable() {
#Override
public void run() {
doOperation2();
handler.run(new Runnable(){
#Override
public void run() {
onPostExecute2();
}
});
}
});
operation1.start();
operation2.start();

Calling Method w/ Argument on Main Thread from Secondary Thread

Like the title suggest I have an android project with a MainActivity class that has a TextView that I want to set the text of after receiving a message. I also have a class that runs a ServerSocket on a separate thread that receives the string message I want to display.
Part of my MainActivity looks like this,
private Handler UIHandler = new Handler();
private RemoteControlServer remoteConnection;
public static final int controlPort = 9090;
public class MainActivity extends Activity implements SensorEventListener
{
...
remoteConnection = new RemoteControlServer(controlPort, UIHandler);
...
private class RemoteControlServer extends RemoteControl
{
RemoteControlServer(int port, Handler ui)
{
super(port, ui);
}
#Override
public void onReceive(String[] msg)
{
//updates messages textview
}
#Override
public void onNotify(String[] msg)
{
//updates notification textview
}
}
}
The RemoteControlServer implementation of code that calls the onReceive(String[] msg) and also handles receiving messages on the different thread looks like this,
...
public abstract void onReceive(String[] msg);
public abstract void onNotify(String[] msg);
...
controlListener = new Thread(new Runnable()
{
boolean running = true;
public void run()
{
String line = null;
while(running)
{
try
{
//Handle incoming messages
...
onReceive(messages);
}
catch (final Exception e)
{
UIHandler.post(new Runnable()
{
public void run()
{
onNotify("Wifi Receive Failed " + e.toString() + "\n");
}
});
}
}
}
});
...
I'm getting the error "Only the original thread that created a view hierarchy can touch its views." when onReceive() is called and throws the exception and calls onNotify() with the exception description. Why does the onNotify() work but the otherone does not? How can I correctly call the listener to the the TextView and update its text? Thanks
private class RemoteControlServer extends RemoteControl
{
...
public class BridgeThread implements Runnable
{
String[] msgArray = null;
public BridgeThread(String[] msg)
{
msgArray = msg;
}
public void run()
{
runOnUiThread(new Runnable()
{
#Override
public void run()
{
TextView zValue = (TextView) findViewById(R.id.connectionStatus);
zValue.setText(msgArray[0]);
}
});
}
}
#Override
public void onReceive(String[] msg)
{
BridgeThread bridgeTest = new BridgeThread(msg);
bridgeTest.run();
}
...
}

How to stop series of postDelayed handlers

I have a series of postDelayed handlers. I'm having trouble to set a mathode that stops the handlers when the user is tapping on the stop button at any time I he wants.
I'll appreciate any help someone able to provide.
Thanks
while (!lessonIsRunning) {
Handler handler0 = new Handler();
handler0.postDelayed(new Runnable() {
#Override
public void run() {
plate1.setVisibility(ImageView.VISIBLE);
plate2.setVisibility(ImageView.VISIBLE);
plate3.setVisibility(ImageView.VISIBLE);
}
}, 6000);
Handler handler1 = new Handler();
handler1.postDelayed(new Runnable() {
#Override
public void run() {
apples1.setVisibility(ImageView.VISIBLE);
}
}, 9000);
Handler handler2 = new Handler();
handler2.postDelayed(new Runnable() {
#Override
public void run() {
plus1.setVisibility(TextView.VISIBLE);
}
}, 9250);
}
public void stopLesson(View V){
}
instead of writing the Runnable task in an anonymous way you must define it with a name, so that later you will have a link to it to remove:
//there is no need for multiple handlers
//handler must be declared outside all functions, in order for you to use it everywhere.
Handler handler = new Handler();
Runnable myFirstTask = new Runnable (){
#Override
public void run() {
plate1.setVisibility(ImageView.VISIBLE);
plate2.setVisibility(ImageView.VISIBLE);
plate3.setVisibility(ImageView.VISIBLE);
} };
Runnable mySecondTask = new Runnable(){
#Override
public void run() {
plus1.setVisibility(TextView.VISIBLE);
}
};
Runnable myThirdTask = new Runnable(){
#Override
public void run() {
apples1.setVisibility(ImageView.VISIBLE);
} }
//you can put different tasks on the same handler object
while (!lessonIsRunning) {
handler.postDelayed(myFirstTask,6000);
handler.postDelayed(mySecondTask,9250);
handler.postDelayed(myThirdTask,9000);
}
public void stopLesson(View V){
//notice that you don't need these, because the handlers are not recursive
//you don't have lines "handler.postDelayed(sameTask,someTime);"
//in your run Method of the runnable
if(handler!=null){
handler.removeCallbacks(myFirstTask);
handler.removeCallbacks(mySecondTask);
handler.removeCallbacks(myThirdTask);
//if this method is inside onPause or onDestroy add this line as well:
handler=null;
}
}
you can give
handler0.removeCallbacksAndMessages(null);
handler1.removeCallbacksAndMessages(null);
handler2.removeCallbacksAndMessages(null);
a try. The doc says when you submit a null token all callbacks and message are removed.

Categories

Resources