i want to know that should i run my functions in a thread or write functions code in a thread!
my mean is something like this:
here i used my function in a thread
...
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_disable_stable_mode);
new Thread(new Runnable() {
#Override
public void run() {
function1();
function2();
function3();
}
}).start();
}
void function1(){
//some code
}
void function2(){
//some code
}
void function3(){
//some code
}
...
and here i used one thread for every function:
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_disable_stable_mode);
function1();
function2();
function3();
}
void function1(){
new Thread(new Runnable() {
#Override
public void run() {
//some code
}
}).start();
}
void function2(){
new Thread(new Runnable() {
#Override
public void run() {
//some code
}
}).start();
void function3(){
new Thread(new Runnable() {
#Override
public void run() {
//some code
}
}).start();
...
are are they same in performance?
the first sample code will be execute
function1() and then function2() and then function3()
but
in second sample code will be execute
function1() and function2() and function3() simultaneously
they are not the same method1 different from method2
Related
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();
}
I'm using retrofit2 to get data from web service, but when I called notify() from thread , main thread cannot get it . And hang app , I don't know why . I hope someone can help me .
OnCreate()
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
synchronized (listRespones) {
while (listRespones.size() < 2) {
try {
listRespones.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Thread 1:
apiManager.getChannelListRespone(areaCode).enqueue(new Callback<CommonListRespone>() {
#Override
public void onResponse(Call<CommonListRespone> call, final Response<CommonListRespone> response) {
Thread channel1 = new Thread(new Runnable() {
#Override
public void run() {
synchronized (listRespones) {
CommonListRespone commonChannel = response.body();
listRespones.add(commonChannel);
listRespones.notify();
}
}});
channel1.start();
}
#Override
public void onFailure(Call<CommonListRespone> call, Throwable t) {
}});
Thread 2:
apiManager.getChannelListRespone(areaCode).enqueue(new Callback<CommonListRespone>() {
#Override
public void onResponse(Call<CommonListRespone> call, final Response<CommonListRespone> response) {
Thread channel2 = new Thread(new Runnable() {
#Override
public void run() {
synchronized (listRespones) {
CommonListRespone commonChannel = response.body();
listRespones.add(commonChannel);
listRespones.notify();
}
}
});
channel2.start();
}
#Override
public void onFailure(Call<CommonListRespone> call, Throwable t) {
}
});
I want to call adapter.notifyDataSetChanged() from another thread. I read that I should use an AsyncTask and do the adapter.notifyDataSetChanged() in post execute.
I must execute the AsyncTask every 5 seconds only on the current activity (might be parent or child activity) because only one activity can do the asynctask at the same time.
Should I create a TimerTask which executes the AsyncTask every 5 seconds, stop it when I start another activity and start it back in onResume ?
Here is my code for the thread which updates the ListView of the current Activity.
private void runEventHandler() {
new Thread() {
public void run() {
while (true) {
try {
runOnUiThread(new Runnable() {
#Override
public void run() {
users.add(new User(10, "a", false));
adapter.notifyDataSetChanged();
}
});
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
Now I must be able to update the child activities' ListViews when a new User is added.
one possible way is that you create a flag in both activity to control your threads to be run ( the following codes are not runable just example to understand what you can do):
Activity A
{
public static boolean stopThread = false;
#Override
public void onResume()
{
super.onResume();
// put your code here...
stopThread =false;
runEventHandler();
}
private void runEventHandler() {
new Thread() {
public void run() {
while (A.stopThread != false) {
try {
runOnUiThread(new Runnable() {
#Override
public void run() {
users.add(new User(10, "a", false));
adapter.notifyDataSetChanged();
}
});
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
#Override
protected void onStop(){
super.onStop();
stopThread =true;
}
}
Activity B
{
public static boolean stopThread = false;
#Override
public void onResume()
{
super.onResume();
// put your code here...
stopThread =false;
runEventHandler();
}
private void runEventHandler() {
new Thread() {
public void run() {
while (B.stopThread != false) {
try {
runOnUiThread(new Runnable() {
#Override
public void run() {
users.add(new User(10, "a", false));
adapter.notifyDataSetChanged();
}
});
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
#Override
protected void onStop(){
super.onStop();
stopThread =true;
}
}
also you can use onPause() instead of onStop(). depends on your program concept.
You should a timertask like in link below : https://examples.javacodegeeks.com/android/core/activity/android-timertask-example/
the code to post any change on UIThread if you are in a different thread like doInBackground of AsyncTask:
runOnUiThread(new Runnable() {
#Override
public void run() {
// Here you can set your Ui Components
}
});
I'm programming a small android app in Java/eclipse.
In one part of my app i need a thread, as i build in the following way:
protected void onResume() {
super.onResume();
// we're going to simulate real time with thread that append data to the graph
new Thread(new Runnable() {
#Override
public void run() {
// we add 100 new entries
for (int i = 0; i < 100; i++) {
runOnUiThread(new Runnable() {
#Override
public void run() {
addEntry();
}
});
// sleep to slow down the add of entries
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// manage error ...
}
}
}
}).start();
}
Evertything works fine so far. But now i want to start that thread not automatically. I want to handle ".start()" with a button.
How can i realize it?
I'm very new to Java and Android.
Thanks in Advance!
You can use Handler with Runnable instead of your Thread idea, Check out the following code, it server your purpose,
private Handler broadcastHandler;
private Runnable broadcastRunnable;
protected void onResume() {
super.onResume();
broadcastRunnable = new Runnable() {
#Override
public void run() {
// Your UI related operations
runOnUiThread(new Runnable() {
#Override
public void run() {
addEntry();
}
});
// Add some delay
broadcastHandler.postDelayed(broadcastRunnable, 1000);
}
}
public void onButtonClick(View view) {
broadcastHandler.postDelayed(broadcastRunnable, 1000);
}
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();