How to late thread run in android - android

In my code I have a thread. You can see the code of thread,
public class MainAsyncHome extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
return null;
}
#Override
protected void onPostExecute(String xml) {
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
I run this thread in my main activity onCreate method as following way
new MainAsyncHome().execute(null);
But I want to give time out for this thread. It means when main activity run I want late to run this thread. I know it can do using sleep method. But How I can late for running this thread just like that way.
I'm stuck with this problem.
pls give me answer. Thanks

Use Handler class, and define Runnable handleMyAsyncTask that will contain code executed after 3000 msec delay:
mHandler.postDelayed(MainAsyncHome, 1000*3); //Delay of three seconds
The answer is taken from here.
To put it in the code:
private final static int INTERVAL = 1000 * 3; //3 seconds
Handler m_handler;
Runnable MainAsyncHome = new Runnable()
{
#Override
public void run() {
doSomething();
m_handler.postDelayed(MainAsyncHome, INTERVAL);
}
}
void startRepeatingTask()
{
MainAsyncHome.run();
}
void stopRepeatingTask()
{
mHandler.removeCallback(MainAsyncHome);
}
Hope it works.

I normally use CountDownTimer, suppose a 3 seconds of delay:
CountDownTimer timer = new CountDownTimer(3000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
//do things, start your Task
//remember we are still in the main thread!
}
}.start();
Get more info at:
http://developer.android.com/reference/android/os/CountDownTimer.html

Use a CountDownTimer like this.
Start your timer in onCreate.
CountDownTimer timer=new CountDownTimer(Delay,TimeIntervalToCallOnTick) {
#Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
}
#Override
public void onFinish() {
// TODO Auto-generated method stub
//start your asynctask
}
};

Related

execute a function within a timer

I ve got this function here:
public void stoprecording()
{
this.recorder.stop();
this.recorder.reset();
this.recorder.release();
}
which stops the recoridng. This is within the class Audio. I also got this function here:
public void recordtimer(final int timer)
{
/*First Part with timer*/
Thread thread = new Thread(new Runnable()
{
#Override
public void run()
{
CountDownTimer countDowntimer = new CountDownTimer(timer, 100000)
{
public void onTick(long millisUntilFinished) {}
public void onFinish() {
this.stoprecording();
}
};countDowntimer.start();
}
});
thread.start();
this.stoprecording();
}
also within the class Audio. I canĀ“t execute this.stoprecording(); because the class CountDownTimer doesn t have this function. How can I execute this function?
Looking at your code it seems there is no need to call stoprecording() from this, since it does not belong to CountDownTimer class you have defined.
Just call it like
public void onFinish() {
stoprecording();
}
or if you want to definitely use this, follow the #gary111 suggestion thus doing
public void onFinish() {
YourClass.this.stoprecording();
}

Show ProgressBar for a few seconds in Android

I have to wait some seconds in my Android App and I want to show a progress bar during this time, how can I do this?
for example :
#Override
protected void onCreate(Bundle savedInstanceState) {
timeForShow(5 //second);
}
.
.
.
private void timeForShow(long mytime){
myprogress.setVisibility(View.VISIBLE);
Waiting for mytime...
myprogress.setVisibility(View.GONE);
}
this is my code but it does not work:
Long timerforprogressbar ;
#Override
protected void onCreate(Bundle savedInstanceState) {
timerforprogressbar = (long) 5000 ;
new MyProgressBar().execute((Void)null);
}
.
.
.
class MyProgressBar extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
progressbar.setVisibility(View.VISIBLE);
try {
Thread.sleep(timerforprogressbar);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
progressbar.setVisibility(View.GONE);
}
}
my progress bar :
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:indeterminateDrawable="#drawable/progress" >
</ProgressBar>
progressbar is my progress bar,plz help me,tnx.
For your specific use case it would be simpler to use a Handler:
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
progressbar.setVisibility(View.GONE);
}
}, timerforprogressbar);
You did not mention how your progressbar is constructed but if you simply want an indeterminate progress to show, then constructing it programatically would be the most simple thing to do I think.
private ProgressDialog working_dialog;
private void showWorkingDialog() {
working_dialog = ProgressDialog.show(context, "","Working please wait...", true);
}
private void removeWorkingDialog() {
if (working_dialog != null) {
working_dialog.dismiss();
working_dialog = null;
}
}
That would make the code look like:
showWorkingDialog();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
removeWorkingDialog();
}
}, timerforprogressbar);
You can always use the CountDownTimer:
public void timer() {
countDownTimer=new CountDownTimer(20000, 1000) { //display a delay of 20 seconds
public void onTick(long millisUntilFinished) {
if (somethingToBreakTheCount)
countDownTimer.onFinish();
txtDebug.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
txtDebug.setText("Done!");
finish();
}
}.start();
}
// We can achieve this by using Coroutines.
// Simply start a coroutine and change the progress of progressbar by changing the dispatcher context after few milliseconds.
// Here I am showing the progress for 1 second before moving to next fragment.
CoroutineScope(Dispatchers.IO).launch {
for (i in 0..100) {
delay(10)
withContext(Dispatchers.Main) {
binding.progressBar.progress = i
}
}
//Navigate to next fragment using nav contorller or with Intents for next Activity
navController.navigate(R.id.action_startFragment_to_listFragment)
}
Updating progress dialog in Activity from AsyncTask
There re is a method for async tasks for progress updates.
Here is a link to a better post on it
As a simpler solution than an AsyncTask, you can always look into using a CountDownTimer for this action.
If you are performing a task in AsyncTask doInBackground(), then you can initiate your progressBar in onPreExecute() and disable it in onPostExecute().

How to waits the thread till another thread completes

I want to show the progress dialog while loading the images in grid view.
The problem i'm facing was the current thread and Progress Dialog thread running simultaniously.
public String Method1(){
String output="";
final ProgressDialog aProgDialogL = ProgressDialog.show(this, "", "Loading...");
Thread thread = new Thread() {
public void run () {
//My codes
aHandlerL.post(new Runnable() {
#Override
public void run() {
//Post Runnable codes
aProgDialogL.dismiss();
}
});
}
};
thread.start();
/*
*
*
* OTHER CODES
*
*
*/
return output;
}
In the above example I need to run the code inside Progress Dialog Thread. After it finish executing i need to run my "OTHER CODES". How to do it?
.
I tried using Async task. Before async task completes method1 gets extcuted and reurning the string.
public String Method1(){
String result="";
new GetImages().execute();
return result;
}
public class GetData extends AsyncTask<Void, Void, Integer>{
#Override
protected void onPreExecute() {
aProgDialogL = ProgressDialog.show(Main.this, "", "Loading...");
}
#Override
protected Integer doInBackground(Void... params) {
//Progress Dialig Code
return null;
}
#Override
protected void onPostExecute(Integer result) {
aProgDialogL.dismiss();
//OTHER CODES
super.onPostExecute(result);
}
}
You can use Async task. http://developer.android.com/reference/android/os/AsyncTask.html. There is a good tutorial here. http://www.vogella.com/articles/AndroidPerformance/article.html.Also have a look at this link
http://developer.android.com/guide/components/processes-and-threads.html. Use asynctask modify it according to your needs.
doInBackground()- For long running operations. Don't update ui here.
onPreExecute()- update ui before running the operatio nin background.
onPostExecute()- update ui after running the operation.
I would suggest you to take somewhat different approach.
Dont involve any threads in Method1() function.Rather your Method1() function should be run under separate thread.
Below snippet will help you.
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((Button) findViewById(R.id.btnPopup))
.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
new Thread() {
public void run() {
String answer = Method1();
runOnUiThread(new Runnable() {
#Override
public void run() {
// Here you will write the code which is
// to be executed on main thread.
}
});
};
}.start();
}
});
}
public String Method1() {
// Write code
return "result";
}
}
Instead of that : What about use Timer After specific Time Stop Your thread and and write your code you want after stop statement Like that :
Timer timer=new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
thread.stop;
// Other code }
}, Time You want );

Countdown Timer which shows on the UI with AsyncTask

I'm trying to implement a Countdown Timer which shows on the UI,
I thought this was a clean and elegant solution but Logcat throws
AndroidRuntime(3282): java.lang.RuntimeException: An error occured while executing doInBackground()
,
private class UpdateCountdownTask extends AsyncTask<Long, Long, Void> {
#Override
protected Void doInBackground(Long... millisUntilFinished) {
new CountDownTimer(millisUntilFinished[0], 1000) {
#Override
public void onTick(long millisUntilFinished) {
publishProgress(millisUntilFinished);
}
#Override
public void onFinish() {
((TextView) findViewById(R.id.answer)).setText(answer);
}
};
return null;
}
#Override
protected void onProgressUpdate(Long... millisUntilFinished) {
super.onProgressUpdate(millisUntilFinished);
((TextView) findViewById(R.id.timer)).setText(""
+ millisUntilFinished[0] / 1000);
}
}
Still don't fully understand threads. Can anyone tell me what I'm doing wrong?
Thanks.
UPDATE: Very Sorry. I am an absolut incompetent. I had forgotten to call the metod start() on the counter. :P
I finally went for implementing the countdown with the CountDownTimer by itself. Sill don't know if this actually runs on a separate thread or not but it works now.
CountDownTimer myCounter = new CountDownTimer(millisUntilFinished, 1000) {
#Override
public void onTick(long millisUntilFinished) {
((TextView) findViewById(R.id.timer)).setText(""
+ millisUntilFinished / 1000);
System.out.println("I am ticking");
}
#Override
public void onFinish() {
}
};
myCounter.start();
I think the problem is the onFinish() method inside CountDownTimer. Here you're modifiying the UI thread, and you cannot do this from a background thread. So you have to put ((TextView) findViewById(R.id.answer)).setText(answer); inside onPostExecute() method. I mean:
protected void onPostExecute(String result) {
super.onPostExecute(result);
((TextView) findViewById(R.id.answer)).setText(answer);
}
I hope this works.
You will not be able to connect the UI when doing somthing in background.In my opinion what you want is possible if you use a thread.This will make your work much more easier.A small piece of code is shown below.I hope this may help you.I am trying to set an image instead you can settext.Here i had done using a thread and a handler.Its impossible to connect the UI inside the thread.In assynctask When you are doing something in background you are compleatly inside the thread.Thats why you are getting a error here.Otherwinse you can do it in Postexecute()
Thread animator = new Thread() {
public void run() {
int i = 0;
try {
sleep(2000);
while (i < 4) {
sleep(50);
handler.sendMessage(handler.obtainMessage(i));
i++;
}
} catch (Exception e) {
}
}
};
animator.start();
handler = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == 0) {
animatedimage.setImageResource(R.drawable.sub1);
} else if (msg.what == 1) {
animatedimage.setImageResource(R.drawable.sub2);
} else if (msg.what == 2) {
animatedimage.setImageResource(R.drawable.sub3);
} else if (msg.what == 3) {
animatedimage.setImageResource(R.drawable.sub4);
}
}
};
Have you consider using Handler to update UI every second?
checkout http://developer.android.com/resources/articles/timed-ui-updates.html

Android: TimerTask scheduled for repetition getting fired only once

Ok this is a very weird problem I am having, and I'm pretty sure that I am messing up somewhere, but I can't quite figure out where.
What I am trying is -
Schedule a Timer to execute a TimerTask every five seconds
The TimerTask in turn executes an AsyncTask (which in this case simple sleeps for a second before returning the static count of the number of AsyncTasks).
Finally, the aforementioned count is updated in the UI.
And of course, the appropriate Handlers and Runnables have been used to post asynchronous messages from other threads to the UI.
This code executes only once. I expect it to fire every 5 seconds. Here's the code.
Note: I had no idea what to do with the Looper. I put it there after trial and error!
public class TimerAsyncMixActivity extends Activity {
public static final String TAG = "TimerAsyncMix";
static int executionCount = 0;
Handler mHandler = new Handler();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new Timer().schedule(new MyTimerTask(this), 0, 5000);
}
class MyAsyncTask extends AsyncTask<String, Void, Integer>{
#Override
protected Integer doInBackground(String... params) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ++executionCount;
}
#Override
protected void onPostExecute(Integer result) {
mHandler.post(new UpdateUiThread(TimerAsyncMixActivity.this, result));
super.onPostExecute(result);
}
}
}
class MyTimerTask extends TimerTask{
private TimerAsyncMixActivity tma;
public MyTimerTask(TimerAsyncMixActivity tma) {
this.tma = tma;
}
#Override
public void run() {
Looper.prepare();
Log.d(TimerAsyncMixActivity.TAG, "Timer task fired");
tma.new MyAsyncTask().execute();
Looper.loop();
Looper.myLooper().quit();
}
}
class UpdateUiThread implements Runnable{
int displayCount;
TimerAsyncMixActivity tma;
public UpdateUiThread(TimerAsyncMixActivity tma, int i) {
this.displayCount = i;
this.tma = tma;
}
#Override
public void run() {
TextView tv = (TextView) tma.findViewById(R.id.tvDisplay);
tv.setText("Execution count is : "+displayCount);
}
Can anyone point me to what I'm doing wrong?
techie, this is how I implemented similar things. I'm won't claim that this is the best way, but it has worked for me and doesn't look too bad.
I have the following code in my activity. I create an async task when the activity starts and I stop it onPause. The AsyncTask does whatever it needs to do, and updates the UI on onProgressUpdate() (which is run on the UI thread, so there's no need to use a Handler).
private Task task;
#Override
protected void onPause() {
task.stop();
task = null;
}
#Override
protected void onResume() {
task = new Task();
task.execute();
}
private class Task extends AsyncTask<Void, String, Void> {
private boolean running = true;
#Override
protected Void doInBackground(Void... params) {
while( running ) {
//fetch data from server;
this.publishProgress("updated json");
Thread.sleep(5000); // removed try/catch for readability
}
return null;
}
#Override
protected void onProgressUpdate(String... values) {
if( ! running ) {
return;
}
String json = values[0];
//update views directly, as this is run on the UI thread.
//textView.setText(json);
}
public void stop() {
running = false;
}
}
Do not use a timer. If your phone goes to sleep, the timer is suspended too. Use AlarmManager.

Categories

Resources