Java/Android Thread pause error - java

i have a class that implements runnable with the run function.
#Override
public void run()
{
while(running)
{
// thread code goes here::
threadCode();////
// thread code ends here
try
{
Thread.sleep(10);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
Now i am trying to pause the thread if something happens.
I tried to use wait() and notify() but it crashed the app, afterwards i came with idea to use the "running" boolean and set it to false as for pause, and then back to true to resume.
Unfortunately it still crashes the app.
It gives me fatal error on logcat.
"Can't create handler inside thread that has not called Looper.prepare()"
Is there any working simple way to pause a thread? ;/
Thx
EDIT:
it's not about thread at all.
I found where it crashes.
It crashes on alert dialog
here is the code of it:
AlertDialog.Builder builder1 = new AlertDialog.Builder(c);
builder1.setTitle("Game over!");
builder1.setMessage("You survived "+secs+"."+msecs+ " seconds.");
builder1.setCancelable(false);
builder1.setPositiveButton("Replay",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id)
{
// intialStuff();
dialog.cancel();
}
});
builder1.setNegativeButton("Rage quit",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
i try to run it on canvas class
maybe it cant work on canvas class?
C is context of main activity.

On Android Threads work differently as against on a regular java 'main' based program. Threads spanned from the UI thread should use a Looper for their own use else they fall back to the main UI thread's Looper. For your query calling Looper.prepare() from inside the run method, probably the fist line inside it would do. However from a long term scalability and correct approach perspective consider using a Loader or an AsynchTask.

There were 2 problems, first was i set int value on the message of the AlertDialog which caused the crash.
The fix is:
setMessage("You survived "+Integer.toString(secs)+"."+Integer.toString(msecs)+" seconds.")
The second problem and the main, i had to use hander on the thread so the AlertDialog will not crash.
Second fix:
create handler.
private Handler threadHandler = new Handler()
{
public void handleMessage(android.os.Message msg)
{
//Go to thread function
threadCode();
}
};
call it from the run function:
#Override
public void run()
{
while(true)
{
try
{
Thread.sleep(10);
//handler
if(running)
threadHandler.sendEmptyMessage(0);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}

Related

Why I am getting an exception while inserting in database using Room library? [duplicate]

What does the following exception mean; how can I fix it?
This is the code:
Toast toast = Toast.makeText(mContext, "Something", Toast.LENGTH_SHORT);
This is the exception:
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:121)
at android.widget.Toast.<init>(Toast.java:68)
at android.widget.Toast.makeText(Toast.java:231)
You need to call Toast.makeText(...) from the UI thread:
activity.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(activity, "Hello", Toast.LENGTH_SHORT).show();
}
});
This is copy-pasted from another (duplicate) SO answer.
You're calling it from a worker thread. You need to call Toast.makeText() (and most other functions dealing with the UI) from within the main thread. You could use a handler, for example.
Look up Communicating with the UI Thread in the documentation. In a nutshell:
// Set this up in the UI thread.
mHandler = new Handler(Looper.getMainLooper()) {
#Override
public void handleMessage(Message message) {
// This is where you do your work in the UI thread.
// Your worker tells you in the message what to do.
}
};
void workerThread() {
// And this is how you call it from the worker thread:
Message message = mHandler.obtainMessage(command, parameter);
message.sendToTarget();
}
Other options:
You could use Activity.runOnUiThread(). Straightforward if you have an Activity:
#WorkerThread
void workerThread() {
myActivity.runOnUiThread(() -> {
// This is where your UI code goes.
}
}
You could also post to the main looper. This works great if all you have is a Context.
#WorkerThread
void workerThread() {
ContextCompat.getMainExecutor(context).execute(() -> {
// This is where your UI code goes.
}
}
Deprecated:
You could use an AsyncTask, that works well for most things running in the background. It has hooks that you can call to indicate the progress, and when it's done.
It's convenient, but can leak contexts if not used correctly. It's been officially deprecated, and you shouldn't use it anymore.
UPDATE - 2016
The best alternative is to use RxAndroid (specific bindings for RxJava) for the P in MVP to take charge fo data.
Start by returning Observable from your existing method.
private Observable<PojoObject> getObservableItems() {
return Observable.create(subscriber -> {
for (PojoObject pojoObject: pojoObjects) {
subscriber.onNext(pojoObject);
}
subscriber.onCompleted();
});
}
Use this Observable like this -
getObservableItems().
subscribeOn(Schedulers.io()).
observeOn(AndroidSchedulers.mainThread()).
subscribe(new Observer<PojoObject> () {
#Override
public void onCompleted() {
// Print Toast on completion
}
#Override
public void onError(Throwable e) {}
#Override
public void onNext(PojoObject pojoObject) {
// Show Progress
}
});
}
----------------------------------------------------------------------------------------------------------------------------------
I know I am a little late but here goes.
Android basically works on two thread types namely UI thread and background thread. According to android documentation -
Do not access the Android UI toolkit from outside the UI thread to fix this problem, Android offers several ways to access the UI thread from other threads. Here is a list of methods that can help:
Activity.runOnUiThread(Runnable)
View.post(Runnable)
View.postDelayed(Runnable, long)
Now there are various methods to solve this problem.
I will explain it by code sample:
runOnUiThread
new Thread()
{
public void run()
{
myactivity.this.runOnUiThread(new Runnable()
{
public void run()
{
//Do your UI operations like dialog opening or Toast here
}
});
}
}.start();
LOOPER
Class used to run a message loop for a thread. Threads by default do
not have a message loop associated with them; to create one, call
prepare() in the thread that is to run the loop, and then loop() to
have it process messages until the loop is stopped.
class LooperThread extends Thread {
public Handler mHandler;
public void run() {
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(Message msg) {
// process incoming messages here
}
};
Looper.loop();
}
}
AsyncTask
AsyncTask allows you to perform asynchronous work on your user
interface. It performs the blocking operations in a worker thread and
then publishes the results on the UI thread, without requiring you to
handle threads and/or handlers yourself.
public void onClick(View v) {
new CustomTask().execute((Void[])null);
}
private class CustomTask extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... param) {
//Do some work
return null;
}
protected void onPostExecute(Void param) {
//Print Toast or open dialog
}
}
Handler
A Handler allows you to send and process Message and Runnable objects
associated with a thread's MessageQueue.
Message msg = new Message();
new Thread()
{
public void run()
{
msg.arg1=1;
handler.sendMessage(msg);
}
}.start();
Handler handler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
if(msg.arg1==1)
{
//Print Toast or open dialog
}
return false;
}
});
Toast.makeText() can only be called from Main/UI thread. Looper.getMainLooper() helps you to achieve it:
JAVA
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// write your code here
}
});
KOTLIN
Handler(Looper.getMainLooper()).post {
// write your code here
}
An advantage of this method is that you can run UI code without Activity or Context.
Try this, when you see runtimeException due to Looper not prepared before handler.
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
#Override
public void run() {
// Run your task here
}
}, 1000 );
I ran into the same problem, and here is how I fixed it:
private final class UIHandler extends Handler
{
public static final int DISPLAY_UI_TOAST = 0;
public static final int DISPLAY_UI_DIALOG = 1;
public UIHandler(Looper looper)
{
super(looper);
}
#Override
public void handleMessage(Message msg)
{
switch(msg.what)
{
case UIHandler.DISPLAY_UI_TOAST:
{
Context context = getApplicationContext();
Toast t = Toast.makeText(context, (String)msg.obj, Toast.LENGTH_LONG);
t.show();
}
case UIHandler.DISPLAY_UI_DIALOG:
//TBD
default:
break;
}
}
}
protected void handleUIRequest(String message)
{
Message msg = uiHandler.obtainMessage(UIHandler.DISPLAY_UI_TOAST);
msg.obj = message;
uiHandler.sendMessage(msg);
}
To create the UIHandler, you'll need to perform the following:
HandlerThread uiThread = new HandlerThread("UIHandler");
uiThread.start();
uiHandler = new UIHandler((HandlerThread) uiThread.getLooper());
Hope this helps.
Reason for an error:
Worker threads are meant for doing background tasks and you can't show anything on UI within a worker thread unless you call method like runOnUiThread. If you try to show anything on UI thread without calling runOnUiThread, there will be a java.lang.RuntimeException.
So, if you are in an activity but calling Toast.makeText() from worker thread, do this:
runOnUiThread(new Runnable()
{
public void run()
{
Toast toast = Toast.makeText(getApplicationContext(), "Something", Toast.LENGTH_SHORT).show();
}
});
The above code ensures that you are showing the Toast message in a UI thread since you are calling it inside runOnUiThread method. So no more java.lang.RuntimeException.
that's what i did.
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast(...);
}
});
Visual components are "locked" to changes from outside threads.
So, since the toast shows stuff on the main screen that is managed by the main thread, you need to run this code on that thread.
Hope that helps:)
I was getting this error until I did the following.
public void somethingHappened(final Context context)
{
Handler handler = new Handler(Looper.getMainLooper());
handler.post(
new Runnable()
{
#Override
public void run()
{
Toast.makeText(context, "Something happened.", Toast.LENGTH_SHORT).show();
}
}
);
}
And made this into a singleton class:
public enum Toaster {
INSTANCE;
private final Handler handler = new Handler(Looper.getMainLooper());
public void postMessage(final String message) {
handler.post(
new Runnable() {
#Override
public void run() {
Toast.makeText(ApplicationHolder.INSTANCE.getCustomApplication(), message, Toast.LENGTH_SHORT)
.show();
}
}
);
}
}
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(mContext, "Message", Toast.LENGTH_SHORT).show();
}
});
Wonderful Kotlin solution:
runOnUiThread {
// Add your ui thread code here
}
first call Looper.prepare() and then call Toast.makeText().show() last call Looper.loop() like:
Looper.prepare() // to be able to make toast
Toast.makeText(context, "not connected", Toast.LENGTH_LONG).show()
Looper.loop()
This is because Toast.makeText() is calling from a worker thread. It should be call from main UI thread like this
runOnUiThread(new Runnable() {
public void run() {
Toast toast = Toast.makeText(mContext, "Something", Toast.LENGTH_SHORT);
}
});
The answer by ChicoBird worked for me. The only change I made was in the creation of the UIHandler where I had to do
HandlerThread uiThread = new HandlerThread("UIHandler");
Eclipse refused to accept anything else. Makes sense I suppose.
Also the uiHandler is clearly a class global defined somewhere. I still don't claim to understand how Android is doing this and what is going on but I am glad it works. Now I will proceed to study it and see if I can understand what Android is doing and why one has to go through all these hoops and loops. Thanks for the help ChicoBird.
For Rxjava and RxAndroid User:
public static void shortToast(String msg) {
Observable.just(msg)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(message -> {
Toast.makeText(App.getInstance(), message, Toast.LENGTH_SHORT).show();
});
}
Coroutine will do it perfectly
CoroutineScope(Job() + Dispatchers.Main).launch {
Toast.makeText(context, "yourmessage",Toast.LENGTH_LONG).show()}
I was running into the same issue when my callbacks would try to show a dialog.
I solved it with dedicated methods in the Activity - at the Activity instance member level - that use runOnUiThread(..)
public void showAuthProgressDialog() {
runOnUiThread(new Runnable() {
#Override
public void run() {
mAuthProgressDialog = DialogUtil.getVisibleProgressDialog(SignInActivity.this, "Loading ...");
}
});
}
public void dismissAuthProgressDialog() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (mAuthProgressDialog == null || ! mAuthProgressDialog.isShowing()) {
return;
}
mAuthProgressDialog.dismiss();
}
});
}
Java 8
new Handler(Looper.getMainLooper()).post(() -> {
// Work in the UI thread
});
Kotlin
Handler(Looper.getMainLooper()).post{
// Work in the UI thread
}
GL
Handler handler2;
HandlerThread handlerThread=new HandlerThread("second_thread");
handlerThread.start();
handler2=new Handler(handlerThread.getLooper());
Now handler2 will use a different Thread to handle the messages than the main Thread.
To display a dialog or a toaster in a thread, the most concise way is to use the Activity object.
For example:
new Thread(new Runnable() {
#Override
public void run() {
myActivity.runOnUiThread(new Runnable() {
public void run() {
myActivity.this.processingWaitDialog = new ProgressDialog(myActivity.this.getContext());
myActivity.this.processingWaitDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
myActivity.this.processingWaitDialog.setMessage("abc");
myActivity.this.processingWaitDialog.setIndeterminate(true);
myActivity.this.processingWaitDialog.show();
}
});
expenseClassify.serverPost(
new AsyncOperationCallback() {
public void operationCompleted(Object sender) {
myActivity.runOnUiThread(new Runnable() {
public void run() {
if (myActivity.this.processingWaitDialog != null
&& myActivity.this.processingWaitDialog.isShowing()) {
myActivity.this.processingWaitDialog.dismiss();
myActivity.this.processingWaitDialog = null;
}
}
}); // .runOnUiThread(new Runnable()
...
Using lambda:
activity.runOnUiThread(() -> Toast.makeText(activity, "Hello", Toast.LENGTH_SHORT).show());
Toast, AlertDialogs needs to run on UI thread, you can use Asynctask to use them properly in android development.but some cases we need to customize the time outs, so we use Threads, but in threads we cannot use Toast,Alertdialogs like we using in AsyncTask.So we need separate Handler for popup those.
public void onSigned() {
Thread thread = new Thread(){
#Override
public void run() {
try{
sleep(3000);
Message message = new Message();
message.what = 2;
handler.sendMessage(message);
} catch (Exception e){
e.printStackTrace();
}
}
};
thread.start();
}
in Above example i want to sleep my thread in 3sec and after i want to show a Toast message,for that in your mainthread implement handler.
handler = new Handler() {
public void handleMessage(Message msg) {
switch(msg.what){
case 1:
Toast.makeText(getActivity(),"cool",Toast.LENGTH_SHORT).show();
break;
}
super.handleMessage(msg);
}
};
I used switch case here, because if you need to show different message in same way, you can use switch case within Handler class...hope this will help you
This usually happens when something on the main thread is called from any background thread. Lets look at an example , for instance.
private class MyTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
textView.setText("Any Text");
return null;
}
}
In the above example , we are setting text on the textview which is in the main UI thread from doInBackground() method , which operates only on a worker thread.
I had the same problem and I fixed it simply by putting the Toast in onPostExecute() override function of the Asynctask<> and it worked.
You need to create toast on UI thread. Find the example below.
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(activity, "YOUR_MESSAGE", Toast.LENGTH_SHORT).show();
}
});
For displaying Toast message please refer to this article
Here is the solution for Kotlin using Coroutine:
Extend your class with CoroutineScope by MainScope():
class BootstrapActivity : CoroutineScope by MainScope() {}
Then simply do this:
launch {
// whatever you want to do in the main thread
}
Don't forget to add the dependencies for coroutine:
org.jetbrains.kotlinx:kotlinx-coroutines-core:${Versions.kotlinCoroutines}
org.jetbrains.kotlinx:kotlinx-coroutines-android:${Versions.kotlinCoroutines}
Create Handler outside the Thread
final Handler handler = new Handler();
new Thread(new Runnable() {
#Override
public void run() {
try{
handler.post(new Runnable() {
#Override
public void run() {
showAlertDialog(p.getProviderName(), Token, p.getProviderId(), Amount);
}
});
}
}
catch (Exception e){
Log.d("ProvidersNullExp", e.getMessage());
}
}
}).start();
Recently, I encounter this problem - It was happening because I was trying to call a function that was to do some UI stuff from the constructor. Removing the initialization from the constructor solved the problem for me.
I got the same problem and this code is working fine for me now.
As an example this is my code to do a task in the background and UI thread.
Observe how the looper is used:
new Thread(new Runnable() {
#Override
public void run() {
Looper.prepare();
// your Background Task here
runOnUiThread(new Runnable() {
#Override
public void run() {
// update your UI here
Looper.loop();
}
});
}
}).start();
i use the following code to show message from non main thread "context",
#FunctionalInterface
public interface IShowMessage {
Context getContext();
default void showMessage(String message) {
final Thread mThread = new Thread() {
#Override
public void run() {
try {
Looper.prepare();
Toast.makeText(getContext(), message, Toast.LENGTH_LONG).show();
Looper.loop();
} catch (Exception error) {
error.printStackTrace();
Log.e("IShowMessage", error.getMessage());
}
}
};
mThread.start();
}
}
then use as the following:
class myClass implements IShowMessage{
showMessage("your message!");
#Override
public Context getContext() {
return getApplicationContext();
}
}

How to kill a thread while finishing app from an AlertDialog in onBackPressed()?

I have an activity which runs a thread and also on that activity in the onBackPressed() void I have an AlertDialog which closes the activity.
The problem is that the thread is running after the activity was closed.
new Thread((new Runnable() {
#Override
public void run() {
//...
}
})).start();
#Override
public void onBackPressed(){
new AlertDialog.Builder(this)
.setTitle("Quit")
.setMessage("Are you sure you want to quit?")
.setNegativeButton("No", null)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(rest.this, MainActivity.class);
finish();
Thread.currentThread().interrupt();
}
}).create().show();
}
This is a trick , which i used also
Solution 1:-
private boolean isActivityRunning=false;
then in onCreate() set it true
isActivityRunning=true;
then in onStop()
isActivityRunning=false;
And in the thread method use it like
new Thread((new Runnable() {
#Override
public void run() {
if(isActivityRunning){
//do your stuff
}
//...
}
})).start();
Solution 2:- this is better solution according to the usage
Use Handler
private Handler mHandler;
private Runnable mRunnable;
in call this where u want to use
mHandler = new Handler();
mRunnable = new Runnable() {
#Override
public void run() {
// do your stuff here
}
};
Also Override
#Override
protected void onResume() {
super.onResume();
if (mHandler != null) {
if(mHandler!=null){
mHandler.postDelayed(mRunnable, 1000);//time in miliseconds
/
}
}
}
#Override
protected void onPause() {
super.onPause();
if (mHandler != null) {
if(mHandler!=null){
mHandler.removeCallbacks(mRunnable);//time in miliseconds
}
}
}
And you should go through this why we prefer worker thread instead of thread
Difference between UI Thread and Worker Thread in Android?
Make a Boolean flag and run the thread while (flag).
Thread {while (flag) { Your thread code goes here. } }
Change the flag to False in the OnClick function.
Having threads in activities is not a very good idea. The activity lifecycle does not mention that explicitly, but in my experience, the process might not finish and activity instance might not always be garbage collected once you call finish. Also, there are scenarios in which you might want to stop your background operation that are not related to you pressing "back".
Also note, that Thread.currentThread().interrupt() does not signal interrupt to the thread you started, but the to the current thread. Interrupt also does not guarantee that the thread function will finish. In order to interrupt() a thread, you need a reference to it.
To be clear: I advise against such approach. Use services for such processing or at AsyncTasks. Without knowing what you want to achieve, it is hard to say what is the best approach.
If you must stick with your thread-inside-activity idea, I suggest you signal to the thread function that it should exit. For thread signalling, you might want to check the following resources:
https://docs.oracle.com/javase/tutorial/essential/concurrency/
http://tutorials.jenkov.com/java-concurrency/thread-signaling.html
https://stackoverflow.com/a/289463/22099
https://stackoverflow.com/a/6859855/22099

How to sleep only after executing a command?

I have a DialogFragment, with a public interface and a method to save the callback:
public class ChooseExportTypeDialogFragment extends DialogFragment{
public interface ExportTypeClickListener{
public void doPositiveClick(ExportTypeEnum exportType);
}
public void setOnConfirmClickListener( ExportTypeClickListener callback ){
this.callback = callback;
}
//...
}
I declare a DialogFragment like this:
final ChooseExportTypeDialogFragment chooseExportTypeDialogFragment = new ChooseExportTypeDialogFragment();
chooseExportTypeDialogFragment.setOnConfirmClickListener( new ExportTypeClickListener() {
#Override
public void doPositiveClick( ExportTypeEnum exportType ) {
toast.setText("Preparing Export...");
toast.show();
controller.onExport( adapter.getSelected() , exportType);
chooseExportTypeDialogFragment.dismiss();
}
} );
chooseExportTypeDialogFragment.show( controller.getSupportFragmentManager(), "notification" );
In the method onExport(), I perform a Thread.sleep(3000) (among other things).
It seems that when doPositiveClick() is invoked, the sleeping (which is in onExport()) occurs before toast.show(). I tried to put both operations (toast.show() and .onExport()) in synchronized blocks, hoping the sleep will start only after finishing toast.show(), but the same problem happens.
I also tried putting toast.show() in a thread, then .start() it and .join() it. And only then call onExport(). Same problem
How can I show the toast and only then let onExport() start?
Thread.sleep is rather problematic in Android espessially when performed in the UI thread because it can cause other elements (in your case Toast) to stop responding. An alternative to your problem is to execute your controller.onExport() logic inside a handler.
#Override
public void doPositiveClick( ExportTypeEnum exportType ){
toast.setText("Preparing Export...");
toast.show();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
controller.onExport( adapter.getSelected() , exportType);
}
}, 3500);
chooseExportTypeDialogFragment.dismiss();
}
You might also need to disable clickability of your Dialog buttons while waiting for the toast text to finish.

Android: runOnUiThread does not always choose the right thread?

I've got an activity that keeps reading words to the user, and using onUtteranceCompleted with textTospeech to display something when the code is completed.
Inside onUtteranceCompleted I have this code to delay a function with a second:
Runnable task = new Runnable() {
public void run() {
//runs on ui
runOnUiThread(new Runnable() {
public void run() {
readWord();
}
});
}
};
worker.schedule(task, 1, TimeUnit.SECONDS);
This seems like it works well, but I think it is causing a problem.
When I rotate the screen of my phone (I guess this starts a new activity).
I hear some words being read in the background. I guess this is because of runOnUiThread() which makes the activity continue in the background.
How could I avoid 2 activities running ? I would prefer if I don't have to stop the screen from rotating on doing some weird patch!
Thank you
EDIT:
public void readWord() {
if (this.readingOnPause) {
return;
}
txtCurrentWord.setText(currentItem[1]);
this.hashAudio.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,"word");
this.tts.setLanguage(Locale.US);
this.tts.speak(this.currentItem[1], TextToSpeech.QUEUE_FLUSH,this.hashAudio);
}
EDIT2:
instantiation of worker:
private static final ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor();
I would use a Handler instead of runOnUiThread().
For one thing, you're using a Thread that starts another Thread - why?
Secondly, if you create a simple Handler, it should kill itself on the rotate config change. IE:
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
// do your background or UI stuff
}
};
Then later use a Thread to call the handler, which will kick off whatever process you want to run on the UI thread:
new Thread() {
#Override
public void run() {
long timestamp = System.currentTimeMillis();
// thread blocks for your 1 second delay
while (System.currentTimeMillis() - timestamp <= 1000) {
// loop
}
handler.sendEmptyMessage(0);
}
}.start();
Ok so this is a fix I've come up with, if someone has a better solution, I'm listening.
I've added android:configChanges="keyboardHidden|orientation" inside the activity in the androidmanifest
2.
and then a function that is called when the screen is rotate:
#Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
setContentView(R.layout.streaming);
initializeUI(); //contains all the findViewByID etc...
}

Why the thread behaves this way in my example?

Can someone explain to me 2 things about the thread code that I finally made almost working the way it should. I want to do a periodic task in the background every x seconds and be able to stop and start it at will. I coded that based on the examples I found, but I'm not sure if I made it in the right way. For the purpose of debugging, the task is displaying a time with custom showTime().
public class LoopExampleActivity extends Activity {
TextView Napis, Napis2;
Button button1,button_start,button_stop;
Handler handler = new Handler();
Boolean tread1_running = true;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Napis = (TextView) findViewById(R.id.textView1);
Napis2 = (TextView) findViewById(R.id.textView2);
button1 = (Button) findViewById(R.id.button1);
button_stop = (Button) findViewById(R.id.button_stop);
button_start = (Button) findViewById(R.id.button_start);
button_stop.setOnClickListener(new OnClickListener() {
#Override
public void onClick (View v) {
tread1_running = false;
}
});
button_start.setOnClickListener(new OnClickListener() {
#Override
public void onClick (View v) {
tread1_running = true;
}
});
thread.start();
}// endof onCreate
final Runnable r = new Runnable()
{
public void run()
{
handler.postDelayed(this, 1000);
showTime(Napis2);
}
};
Thread thread = new Thread()
{
#Override
public void run() {
try {
while(tread1_running) {
sleep(1000);
handler.post(r);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
}
Now the questions are:
1)Will my thread quit forever if I stop it with the stop button?
2)Why can't I start it again with the start_button? If I add the tread.start() in a button, will it crash?
3) I tried a second version when I let the thread run and put a condition into the handler. The only way I can get it to work is to loop conditionaly in the handler by adding an
if (thread1_running) {
handler.postDelayed(this, 2000);
showTime(Napis2);
}
And changing the condition in a thread start to while (true) but then I have an open thread that is running all the time and I start and stop it in a handler, and it posts more and more handlers.
So, finally I get to the point it looks like that:
final Runnable r = new Runnable()
{
public void run()
{
if (thread1_running) handler.postDelayed(this, 1000);
showTime(Napis2);
}
};
Thread thread = new Thread()
{
#Override
public void run() {
try {
while(true) {
sleep(1000);
if (thread1_running) handler.post(r);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Is the proper way to do that is to start and stop a whole thread? Or that is the best way?
The best way to achieve something like that would be, in my humble opinion, to postDelayed(Runnable, long).
You could do something like this. Class definition:
private Handler mMessageHandler = new Handler();
private Runnable mUpdaterRunnable = new Runnable() {
public void run() {
doStuff();
showTime(Napis2);
mMessageHandler.postDelayed(mUpdaterRunnable, 1000);
}
};
And control true run/stop like this:
To start:
mMessageHandler.postDelayed(mUpdaterRunnable, 1000);
And to stop:
mMessageHandler.removeCallbacks(mUpdaterRunnable);
It's much much simpler, in my humble opinion.
Threads a described by a state machine in java.
When a thread get outs of its run method, it enters in the stopped state and can't be restarted.
You should always stop a thread by getting it out of its run method as you do, it s the proper way to do it.
If you want to "restart the thread", start a new instance of your thread class.
You should better encapsulate your thread and its running field. It should be inside your thread class and the class should offer a public method to swich the boolean. No one cares about your datastructure, hide them. :)
You should consider using runOnUIThread for your runnable, its much easier to use than handlers.

Categories

Resources