Popup in a thread - android

I would like to create a popup after a splashscreen.
But A have a crash. I think, because the popup is create in a thread (but terminated).
So crash..
I don't find a good code :(
Code:
Thread splashTread = new Thread() {
#Override
public void run() {
boolean error = true;
try {
int waited = 0;
Parser parser= Parser();
error = parser.init();
while (waited < _splashTime) {
sleep(100);
waited += 100;
}
} finally {
if(!error){
startActivity(new Intent(getApplicationContext(),
Main.class));
finish();
}else{
createPopup(context);
}
}
}
};

You would have much better luck with a Handler and a Runnable for this type of thing. The contents of the Runnable will still execute on the main thread even though you are posting from a different thread. The Handler class executes in whatever thread it is created in.
Runnable splashRunnable = new Runnable(){
public void run(){
if(!error){
StartActivity(new Intent(getApplicationContext(), Main.class));
finish();
}else createPopup(context);
}
};
//in your thread
mHandler.postDelayed(splashRunnable, _splashTime);

Related

finish Thread actions before activity continues

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();

how to start Asychoronous task in a thread finally block in android

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;
}
}
};

How to quit HandlerThread's looper safely

I have a HandlerThread, to which I keep posting a runnable every 5 seconds. Something like this:
HandlerThread thread = new HandlerThread("MyThread");
thread.start();
Handler handler = new Handler(thread.getLooper());
handler.post(new Runnable() {
public void run() {
//...
handler.postDelayed(this, 5000);
}
});
I need to quit the looper at some point, after 60 seconds or something like that.. so I write:
mainHandler = new Handler(Looper.myLooper()); //main thread's
mainHandler.postDelayed(new Runnable() {
#Override
public void run() {
thread.getLooper().quit();
}
}, 60000);
I think this causes the looper to quit abruptly, so I start getting this "warning" messages:
W/MessageQueue(3726): java.lang.RuntimeException: Handler
(android.os.Handler) {4823dbf8} sending message to a Handler on a dead
thread
I want to avoid this error msg, I thought that I could solve it by using the Looper.quitSafely() method.. but I checked the API and it's no longer available.
Does anyone know what happened to it? (It's not deprecated like some other methods).
Is there some way I can quit the looper safely? Thanks!
You could try to use a boolean to know if the code should be executed. Something like this:
private boolean runHandler = true;
...
HandlerThread thread = new HandlerThread("MyThread");
thread.start();
Handler handler = new Handler(thread.getLooper());
handler.post(new Runnable() {
public void run() {
if(runHandler){
//...
handler.postDelayed(this, 5000);
}
}
});
mainHandler = new Handler(Looper.myLooper()); //main thread's
mainHandler.postDelayed(new Runnable() {
#Override
public void run() {
runHandler = false;
}
}, 60000);
Im not Thread Guru, but this way can give you direction:
...
_thread.setRunning(true);
_thread.start();
..
public void stopThread(){
boolean retry = true;
_thread.setRunning(false);
while (retry) {
try {
_thread.join();
retry = false;
Log.e("test", "thread stopped");
} catch (InterruptedException e) {
Log.e("test", "can't stop thread, retrying...");
// we will try it again and again...
}
}
}
In your thread:
while (isRunning) {
//...
}
1st all you implement run method in loop (while(isRunnig){}).
On finish, you switch flag to false and "wait" for join.

Update UI from running thread

I want to write a download manager app, in the activity I add a progress bar which show the current progress to the user, now if user touch the back button and re-open the activity again this ProgressBar won't be updated.
To avoid from this problem I create a single thread with unique name for each download that keep progress runnable and check if that thread is running in onResume function, if it is then clone it to the current thread and re-run the new thread again but it won't update my UI either, Any ideas !?
#Override
public void onResume()
{
super.onResume();
Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
Thread[] threadArray = threadSet.toArray(new Thread[threadSet.size()]);
for (int i = 0; i < threadArray.length; i++)
if (threadArray[i].getName().equals(APPLICATION_ID))
{
mBackground = new Thread(threadArray[i]);
mBackground.start();
downloadProgressBar.setVisibility(View.VISIBLE);
Toast.makeText(showcaseActivity.this
, "Find that thread - okay", Toast.LENGTH_LONG).show();
}
}
private void updateProgressBar()
{
Runnable runnable = new updateProgress();
mBackground = new Thread(runnable);
mBackground.setName(APPLICATION_ID);
mBackground.start();
}
private class updateProgress implements Runnable
{
public void run()
{
while (Thread.currentThread() == mBackground)
try
{
Thread.sleep(1000);
Message setMessage = new Message();
setMessage.what = mDownloadReceiver.getProgressPercentage();
mHandler.sendMessage(setMessage);
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
}
catch (Exception e)
{/* Do Nothing */}
}
}
private Handler mHandler = new Handler()
{
#Override
public void handleMessage(Message getMessage)
{
downloadProgressBar.setIndeterminate(false);
downloadProgressBar.setProgress(getMessage.what);
if (getMessage.what == 100)
downloadProgressBar.setVisibility(View.GONE);
}
};
Download button code:
downloadBtn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0)
{
downloadProgressBar.setVisibility(View.VISIBLE);
downloadProgressBar.setIndeterminate(true);
downloadProgressBar.setMax(100);
Intent intent = new Intent(showcaseActivity.this, downloadManagers.class);
intent.putExtra("url", "http://test.com/t.zip");
intent.putExtra("receiver", mDownloadReceiver);
startService(intent);
updateProgressBar();
}
});
I'd strongly recommend reading the Android Developer blog post on Painless Threading. As it states, the easiest way to update your UI from another thread is using Activity.runOnUiThread.

How to kill the thread when the new activity is started and how to override the previous thread

i have some 10 activities when the present activity is idle for 10 sec then it should go back to the main page
the code i used in each activity is
final Handler handler=new Handler();
final Runnable r = new Runnable()
{
public void run()
{
handler.postDelayed(this, 10000);
Intent intent = new Intent(Business_Personal.this,PrintoActivity.class);
startActivity(intent);
Thread.interrupted();
}
};
handler.postDelayed(r, 10000);
Thread thread = new Thread()
{
#Override
public void run() {
try {
while(true)
{
sleep(1000);
handler.post(r);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
if i use this above code then till 3rd activity its working fine but in 3rd activity time is out and it's coming back to the main page
i need the code when i enter into next activity it should kill the previous thread and create a new thread
or else
override that previous thread
You need to stop the thread by using some boolean value which you set to false on the Activity's onDestroy or onPause.
while(threadNeeded){
}
public onDestroy(){
threadNeeded = false;
}

Categories

Resources