I do a smooth scroll to defined position.
smoothScrollTo(0, 1000);
After this method execute - i do a couple operations. But i want to do they - after scroll animation end.
I want to detect when scroll animation is finished. How i can do that?
i have do like this,
final ScrollView mScrollView = (ScrollView) findViewById(R.id.scrollview);
layoutSponsorBax.setVisibility(View.VISIBLE);
Timer timer = new Timer();
TimerTask task = new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
ViewGroup relativeL = (ViewGroup) mScrollView
.getChildAt(mScrollView.getChildCount() - 1);
final int sVH = mScrollView.getBottom()
- mScrollView.getTop();
View notePad = relativeL.getChildAt(2);
final int svHeight = 800;
Log.i("svHeight", "svHeight : " + svHeight);
final float duration = 2000;
ctt = new CountDownTimer((int) duration, 1) {
int temp = 0;
public void onTick(long millisUntilFinished) {
try {
Log.i("millisUntilFinished",
"millisUntilFinished : "
+ millisUntilFinished);
Log.i("Height- Temp", "Temp : " + temp);
mScrollView.scrollTo(0, temp);
temp = (int) (((svHeight) - (millisUntilFinished / duration)
* (svHeight)));
} catch (ArithmeticException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public void onFinish() {
}
}.start();
}
});
}
};
int duration = 1400;
timer.schedule(task, duration);
please check this it may be help to you
Related
I need count down timer that whenever I clicked or times up, send result and time score to another activity. So I used thread, but I don't know why in first time run activity it don't show time for some seconds in textview, one more strange thing is that when press back,then go to activity again it works fine.
count down code:
if (flagTime) {
flagTime = false;
new Thread(new Runnable() {
#Override
public void run() {
int counter = 60;
while (function.isActivityVisible() && counter > 0) {
counter--;
final int finalCounter = counter;
try {
Thread.sleep(1000);
G.HANDLER.post(new Runnable() {
#Override
public void run() {
if (function.isActivityVisible()) {
timeSc=finalCounter;
String preSec = "";
if (finalCounter < 10) {
preSec = "0";
}
if (function.isActivityVisible()
&& finalCounter <= 0) {
flagTime = false;
Intent intent = new Intent(
Memorize.this,
MemorizeResult.class);
intent.putExtra("TIME", 60);
intent.putExtra("ARRAY_RESULT",
array_choice);
startActivity(intent);
finish();
}
String score = "00:" + preSec
+ finalCounter;
txt[20].setText( " time ramaining " + score);
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
if (!function.isActivityVisible()) {
flagTime = false;
finish();
}
}
}).start();
}
I use many flag to handle it, but it seems don't work properly.
Try using a CountDownTimer
Something like:
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
I have made a progressbar in android,Which is horizontal,i want to freeze it when any button click in my activity,I have tried as below,But progress still displays.my code is as below:I want to do something like one question loaded after another,and onClick of any button counter and progress state should be stop,but rite now my timer stop but progress still ran up..it not stops.
code
public class QuestionAnswerActivity extends Activity implements OnClickListener {
// visible gone
ArrayList<HashMap<String, String>> QuestionList;
private int progressStatus = 0;
private Handler handler = new Handler();
Intent i;
private boolean run = true;
/**
* Answer [1=true / 0 =false]
*/
int myans;
String ans;
ProgressDialog pDialog;
TextView text_player_one;
String JsonStr;
ArrayList<HashMap<String, String>> questionList;
ImageView player_one_pic;
int count;
private DisplayImageOptions options;
public static ImageLoader imageLoader;
ImageView answer_right_one;
ProgressBar pg_loading;
private CountDownTimer countDownTimer;
TextView timer_text;
private final long startTime = 8 * 1000;
private final long interval = 1 * 1000;
Button opt_1, opt_2, opt_3, opt_4;
Thread splashThread;
TextView answer_question;
LinearLayout answer_linear_3;
// Response variables...!!
// Single player*************************************
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.question_answer_activity);
init();
}
// ***********************************************************************************************
/**
* Initialise the views
*/
#SuppressWarnings({ "deprecation", "unchecked" })
private void init() {
answer_linear_3 = (LinearLayout) findViewById(R.id.answer_linear_3);
answer_linear_3.setVisibility(View.GONE);
questionList = new ArrayList<HashMap<String, String>>();
answer_question = (TextView) findViewById(R.id.answer_question);
player_one_pic = (ImageView) findViewById(R.id.player_one_pic);
text_player_one = (TextView) findViewById(R.id.text_player_one);
text_player_one.setText(Pref.getValue(QuestionAnswerActivity.this,
Const.PREF_NAME, ""));
pg_loading = (ProgressBar) findViewById(R.id.pg_loading_answer);
timer_text = (TextView) findViewById(R.id.timer_text_loading11);
answer_right_one = (ImageView) findViewById(R.id.answer_right_one);
imageLoader = ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration
.createDefault(QuestionAnswerActivity.this));
options = new DisplayImageOptions.Builder().cacheOnDisc(true)
.displayer(new RoundedBitmapDisplayer((int) 3.5f))
.showStubImage(R.drawable.ic_launcher)
.showImageOnFail(R.drawable.ic_launcher).build();
imageLoader.displayImage(Pref.getValue(QuestionAnswerActivity.this,
Const.PREF_PROFILE_PIC, ""), player_one_pic, options);
opt_1 = (Button) findViewById(R.id.option_1);
opt_2 = (Button) findViewById(R.id.option_2);
opt_3 = (Button) findViewById(R.id.option_3);
opt_4 = (Button) findViewById(R.id.option_4);
count = 0;
questionList = (ArrayList<HashMap<String, String>>) getIntent()
.getSerializableExtra("queList");
System.out.println("::::::::My questions::::::::;+++++++"
+ questionList);
/*
* answer_question.setText(questionList.get(count).get("q_title"));
* opt_1.setText(questionList.get(count).get("opt1"));
* opt_2.setText(questionList.get(count).get("opt2"));
* opt_3.setText(questionList.get(count).get("opt3"));
* opt_4.setText(questionList.get(count).get("ans"));
*/
handler.postDelayed(new ViewUpdater(answer_linear_3), 1000);
answer_question.setText(questionList.get(count).get("q_title"));
opt_1.setText(questionList.get(count).get("opt1"));
opt_2.setText(questionList.get(count).get("opt2"));
opt_3.setText(questionList.get(count).get("opt3"));
opt_4.setText(questionList.get(count).get("ans"));
opt_1.setOnClickListener(this);
opt_2.setOnClickListener(this);
opt_3.setOnClickListener(this);
opt_4.setOnClickListener(this);
countDownTimer = new MyCountDownTimer(startTime, interval);
/*
* Initialise NoResponse Timer
*/
timer_text.setText(timer_text.getText()
+ String.valueOf(startTime / 1000));
countDownTimer.start();
new Thread(new Runnable() {
public void run() {
while (progressStatus < 100) {
progressStatus += 1;
// Update the progress bar and display the
// current value in the text view
handler.post(new Runnable() {
public void run() {
if (run) {
pg_loading.setProgress(progressStatus);
pg_loading.setProgressDrawable(getResources()
.getDrawable(R.drawable.progress));
}
}
});
try {
// Sleep for 200 milliseconds.
// Just to display the progress slowly
Thread.sleep(62);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
// ***********************************************************************************************
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
run = false;
switch (v.getId()) {
case R.id.option_1:
if (count <= 7) {
count++;
progressStatus = pg_loading.getProgress();
/* questionTask(count); */
new LeaveResponse()
.execute(questionList.get(count).get("q_id"));
}
break;
case R.id.option_2:
if (count <= 7) {
count++;
progressStatus = pg_loading.getProgress();
new LeaveResponse()
.execute(questionList.get(count).get("q_id"));
}
break;
case R.id.option_3:
if (count <= 7) {
count++;
progressStatus = pg_loading.getProgress();
new LeaveResponse()
.execute(questionList.get(count).get("q_id"));
}
break;
case R.id.option_4:
if (count <= 7) {
count++;
progressStatus = pg_loading.getProgress();
new LeaveResponse()
.execute(questionList.get(count).get("q_id"));
}
/*
* answer_question.setText(QuestionList.get(count).get("q_title"));
* opt_1.setText(QuestionList.get(count).get("opt1"));
* opt_2.setText(QuestionList.get(count).get("opt2"));
* opt_3.setText(QuestionList.get(count).get("opt3"));
* opt_4.setText(QuestionList.get(count).get("ans"));
* timer_text.setText(timer_text.getText() +
* String.valueOf(startTime / 1000));
*
* countDownTimer.start();
* answer_right_one.setVisibility(View.VISIBLE);
* pg_loading.setVisibility(View.GONE); countDownTimer.cancel();
*
* Toast.makeText(QuestionAnswerActivity.this,
* timer_text.getText().toString(), 1).show();
*/
break;
}
}
// ***********************************************************************************************
/**
* CountDown Timer for Starting No response activity if user doesnt
* responds.
*/
public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
public void onpause() {
// TODO Auto-generated method stub
Toast.makeText(QuestionAnswerActivity.this, "Clicked", 1).show();
}
#Override
public void onFinish() {
Toast.makeText(getApplicationContext(), "onFinish",
Toast.LENGTH_SHORT).show();
/*
* If finish , that is user not responding , go to NoResponse
* screen.
*/
Intent intent = null;
intent = new Intent(QuestionAnswerActivity.this,
NoResponseActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
finish();
}
#Override
public void onTick(long millisUntilFinished) {
timer_text.setText("" + millisUntilFinished / 1000);
}
}
#SuppressWarnings("deprecation")
#SuppressLint("NewApi")
void questionTask(int count) throws InterruptedException {
if (count < 8) {
answer_linear_3.setVisibility(View.GONE);
answer_question.setText(questionList.get(count).get("q_title"));
handler.postDelayed(new ViewUpdater(answer_linear_3), 100);
myans = randomGenerator();
System.out.println(":::::::::::::;randomized answer::::::::::::;;;"
+ myans);
if (myans == 1) {
opt_1.setBackgroundDrawable(getResources().getDrawable(
R.drawable.true_selector));
opt_1.setText(questionList.get(count).get("ans"));
opt_2.setText(questionList.get(count).get("opt2"));
opt_3.setText(questionList.get(count).get("opt3"));
opt_4.setText(questionList.get(count).get("opt1"));
} else if (myans == 2) {
opt_2.setBackgroundDrawable(getResources().getDrawable(
R.drawable.true_selector));
opt_1.setText(questionList.get(count).get("opt2"));
opt_2.setText(questionList.get(count).get("ans"));
opt_3.setText(questionList.get(count).get("opt3"));
opt_4.setText(questionList.get(count).get("ans"));
} else if (myans == 3) {
opt_3.setBackgroundDrawable(getResources().getDrawable(
R.drawable.true_selector));
opt_1.setText(questionList.get(count).get("opt1"));
opt_2.setText(questionList.get(count).get("opt2"));
opt_3.setText(questionList.get(count).get("ans"));
opt_4.setText(questionList.get(count).get("opt3"));
} else {
opt_4.setBackgroundDrawable(getResources().getDrawable(
R.drawable.true_selector));
opt_1.setText(questionList.get(count).get("opt1"));
opt_2.setText(questionList.get(count).get("opt2"));
opt_3.setText(questionList.get(count).get("opt3"));
opt_4.setText(questionList.get(count).get("ans"));
}
countDownTimer = new MyCountDownTimer(startTime, interval);
/*
* Initialise NoResponse Timer
*/
timer_text.setText(timer_text.getText()
+ String.valueOf(startTime / 1000));
countDownTimer.start();
}
}
private class ViewUpdater implements Runnable {
private LinearLayout mView;
public ViewUpdater(LinearLayout linView) {
mView = linView;
}
#Override
public void run() {
mView.setVisibility(View.VISIBLE);
}
}
// Answer webservice call..!
private class LeaveResponse extends AsyncTask<String, String, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
countDownTimer.cancel();
pDialog = new ProgressDialog(QuestionAnswerActivity.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
BackendAPIService sh = new BackendAPIService();
String ResponseURL = Const.API_RESPONSE
+ "?os=droid&user_id="
+ Pref.getValue(QuestionAnswerActivity.this,
Const.PREF_USER_ID, "") + "&myrole="
+ Const.MY_ROLL + "&q_id=" + params[0] + "&ans=" + ans
+ "&time=5&game_id=" + Const.GAME_ID + "";
JsonStr = sh.makeServiceCall(ResponseURL, BackendAPIService.GET);
System.out.println("::::::::::::;My Response request::::::::::;;;"
+ ResponseURL);
Log.d("Response: ", "> " + JsonStr);
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
try {
countDownTimer.cancel();
pg_loading.setProgress(0);
progressStatus = 0;
new Thread(new Runnable() {
public void run() {
while (progressStatus < 100) {
progressStatus += 1;
// Update the progress bar and display the
// current value in the text view
handler.post(new Runnable() {
public void run() {
if (run) {
pg_loading.setProgress(progressStatus);
pg_loading
.setProgressDrawable(getResources()
.getDrawable(
R.drawable.progress));
}
}
});
try {
// Sleep for 200 milliseconds.
// Just to display the progress slowly
Thread.sleep(62);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
questionTask(count);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public int randomGenerator() {
Random r = new Random();
int ans = r.nextInt(4 - 1) + 1;
return ans;
}
}
You can easily hold some boolean variable for that case:
private boolean run = true;
then gather all the Buttons onClickListeners in one click listener, like the main one of the class, and upon anyclick make that variable run=false, So, check that before set the progress:
if(run){
pg_loading.setProgress(progressStatus);
}else{
//stop, finish, do whatever you want
}
in onClick listener:
public void onClick(View v) {
// TODO Auto-generated method stub
run = false;
Intent i;
switch (v.getId()) {
.
.
.
}
UPDATE:
make the thread as the following:
new Thread(new Runnable() {
public void run() {
while (progressStatus < 100) {
progressStatus += 1;
// Update the progress bar and display the
// current value in the text view
handler.post(new Runnable() {
public void run() {
if(run){
pg_loading.setProgress(progressStatus);
pg_loading.setProgressDrawable(getResources()
.getDrawable(R.drawable.progress));
}
}
});
try {
// Sleep for 200 milliseconds.
// Just to display the progress slowly
Thread.sleep(62);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
UPDATE 2:
your onPostExcute in the AsyncTask must be:
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
try {
countDownTimer.cancel();
pg_loading.setProgress(0);
progressStatus = 0;
new Thread(new Runnable() {
public void run() {
while (progressStatus < 100) {
progressStatus += 1;
// Update the progress bar and display the
// current value in the text view
handler.post(new Runnable() {
public void run() {
pg_loading.setProgress(progressStatus);
pg_loading
.setProgressDrawable(getResources()
.getDrawable(
R.drawable.progress));
}
});
I'm testing something and I want print out execution time with this code:
private Runnable runnerLog = new Runnable() {
#Override
public void run() {
String timeStamp = new SimpleDateFormat("HH:mm:ss yyyy-dd-MM").format(Calendar.getInstance().getTime());
System.out.println("Current time: " + timeStamp);
mHandlerLogger.postDelayed(runnerLog, mInterval);
}};
The result should be like:
13:45:10
13:45:12
13:45:14
13:45:16
and so on...
but i noticed that sometimes is not difference 2 seconds, but three:
13:45:10
13:45:12
13:45:15
13:45:17
13:45:19
13:45:21
13:45:24
What is the reason for this situation? Is there better solution for executing something each X seconds?
try this
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Thread myThread = null;
Runnable runnable = new CountDownRunner();
myThread= new Thread(runnable);
myThread.start();
}
public void doWork() {
runOnUiThread(new Runnable() {
public void run() {
try{
TextView txtCurrentTime= (TextView)findViewById(R.id.lbltime);
Date dt = new Date();
int hours = dt.getHours();
int minutes = dt.getMinutes();
int seconds = dt.getSeconds();
String curTime = hours + ":" + minutes + ":" + seconds;
txtCurrentTime.setText(curTime);
}catch (Exception e) {}
}
});
}
class CountDownRunner implements Runnable{
// #Override
public void run() {
while(!Thread.currentThread().isInterrupted()){
try {
doWork();
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}catch(Exception e){
}
}
}
}
please try this:
private Handler myhandler ;
private long RETRY_TIME = xx;
private long START_TIME = yy;
//oncreate
myhandler= new Handler();
myhandler.postDelayed(myRunnable, START_TIME);
//your runnable class
private Runnable myRunnable = new Runnable() {
public void run() {
//doing something
myhandler.postDelayed(myRunnable, RETRY_TIME);
}
};
I am trying to display a multiplication table with delay. My code is working fine but I am not able to implement the delay.
Here is My code:
tableButton1 = (Button) findViewById(R.id.Button1);
tableButton1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
str = tableButton1.getText().toString();
a = Integer.parseInt(str);
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 10; i++){
sb.append(a + " x " + i + " = " + i * a+ "\n");
}
s = String.valueOf(sb);
Intent intent=new Intent(getApplicationContext(),TextViewActivity.class);
intent.putExtra("MA", s);
startActivity(intent);
}
});
//Toast.makeText(getApplicationContext(), "Hi" +ss, 222).show();
}
});
Any answer is appreciable.
Thank's in advance
Updated-code:- This code is working with help of #theLittleNaruto
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class TestActivity extends Activity{
Button tableButton1;
TextView txtView;
int value = 0;
static int count = 0;
Handler handle = new Handler();
StringBuilder sb = new StringBuilder();
Runnable r = new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "onrunnable" +sb, 222).show();
// TODO Auto-generated method stub
updateTable();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.text_display);
Toast.makeText(getApplicationContext(), "oncreate" , 222).show();
txtView = (TextView) findViewById(R.id.outputTXT);
tableButton1 = (Button) findViewById(R.id.seven);
tableButton1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "onclick" , 222).show();
value= Integer.parseInt(tableButton1.getText().toString());
updateTable();
}
});
}
public void updateTable(){
count+=1000;
if(count==11000){
//Toast.makeText(getApplicationContext(), "onupdate" , 222).show();
count = 0;
value=0;
handle.removeCallbacks(r);
sb.setLength(0);
}else{
sb.append(value + " x " + count/1000 + " = " + count/1000 * value+ "\n");
handle.postDelayed(r, 1000);
// Toast.makeText(getApplicationContext(), "onupdateElse" +sb, 222).show();
txtView.setText(sb);
}
}
}
Thank you all the supporters and their best try to help me
Why dont you try what the other is saying with this little effort ;)
public class TestActivity extends Activity{
int value = 0;
static int count = 0;
Handler handle = new Handler();
StringBuilder sb = new StringBuilder();
Runnable r = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
updateTable();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.oaot_get);
tableButton1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
value= Integer.parseInt(tableButton1.getText().toString());
updateTable();
}
});
}
public void updateTable(){
count+=1000;
if(count==11000){
count = 0;
value=0;
handle.removeCallbacks(r);
sb.setLength(0);
}else{
sb.append(value + " x " + count/1000 + " = " + count/1000 * value+ "\n");
handle.postDelayed(r, 1000);
}
}
}
Try this
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
str = tableButton1.getText().toString();
a = Integer.parseInt(str);
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 10; i++){
sb.append(a + " x " + i + " = " + i * a+ "\n");
}
}, 5000);
s = String.valueOf(sb);
Intent intent=new Intent(getApplicationContext(),TextViewActivity.class);
intent.putExtra("MA", s);
startActivity(intent);
Add a handler(). Replace your onClick code with:
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
str = tableButton1.getText().toString();
a = Integer.parseInt(str);
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 10; i++)
{
sb.append(a + " x " + i + " = " + i * a+ "\n");
}s=String.valueOf(sb);
Intent intent=new Intent(getApplicationContext(),TextViewActivity.class);
intent.putExtra("MA", s);
startActivity(intent);
}
}, 5000);
Repalce 5000 with the time you want it to be delayed for in milliseconds
Add a Handler that will execute your runnable:
Runnable runnable = new Runnable() {
#Override
public void run() {
str = tableButton1.getText().toString();
a = Integer.parseInt(str);
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 10; i++){
sb.append(a + " x " + i + " = " + i * a+ "\n");
//--ADDED stuff here------------------------------------------------------------
try {
//Sleep will suspend your Thread for 500 miliseconds and resumes afterwards
Thread.sleep(500);
} catch (InterruptedException e) {
Log.e("error, Thread interrupted", e);
}
}
s = String.valueOf(sb);
Intent intent=new Intent(getApplicationContext(),TextViewActivity.class);
intent.putExtra("MA", s);
startActivity(intent);
}
Handler handler = new Handler();
//this will execute your runnable after 500 milliseconds
handler.postDelayed(runnable, 500);
You can use that :
public class Scheduler {
// DATA
private OnScheduleTimeListener mListener;
private Handler mHandler;
private int mInterval; // Between each executions
private static final int DELAY = 100; // before first execution
private boolean mIsTimerRunning;
public static interface OnScheduleTimeListener {
public void onScheduleTime();
}
public Scheduler(int interval) {
super();
mInterval = interval;
mHandler = new Handler();
}
private final Runnable mRunnable = new Runnable() {
#Override
public void run() {
// Do stuff
mListener.onScheduleTime();
// Repeat
mHandler.postDelayed(mRunnable, mInterval);
}
};
public void setOnScheduleTimeListener(OnScheduleTimeListener listener) {
mListener = listener;
}
public void startTimer() {
mIsTimerRunning = true;
mHandler.postDelayed(mRunnable, DELAY);
}
public void stopTimer() {
mIsTimerRunning = false;
mHandler.removeCallbacks(mRunnable);
}
public boolean isTimerRunning() {
return mIsTimerRunning;
}
}
Now to use it :
private void startTimer() {
mScheduler = new Scheduler(INTERVAL);
mScheduler.setOnScheduleTimeListener(new OnScheduleTimeListener() {
#Override
public void onScheduleTime() {
Log.d(TAG, "update");
});
mScheduler.startTimer();
}
private void stopTimer(){
if (mScheduler != null && mScheduler.isTimerRunning()) {
mScheduler.stopTimer();
mScheduler = null;
}
}
Try this....
do {
try {
try {
response_req_sequence = SimpleHttpClient
.sendresponseSequReqRes(response_send_order);
System.out.println("response of sequence request"
+ response_req_sequence);
System.out.println(" i ma in thread");
if (response_req_sequence.trim().length() != 0) {
System.out.println("response in result of sequ"+ response_req_sequence);
break;
}
Thread.sleep(10000);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (Exception e) {
// TODO: handle exception
}
} while (response_req_sequence.trim().equalsIgnoreCase(""));
This is working fine for me. you can customize according to you.
I have a horizontal progress bar in android. I need to make it complete in 60 seconds.
Why doesn't the below code work?
int progress = 0;
progressBarHorizontal.setMax(60);
while(progress < 60) {
progressHandler.postDelayed((new Runnable() {
public void run() {
progressBarHorizontal.setProgress(progress);
}
}),progress * 1000);
progress++;
}
Please suggest some other methods. I tried this:
new Thread(new Runnable() {
int progress = 0;
public void run() {
long timerEnd = System.currentTimeMillis() + 60 * 1000;
while (timerEnd > System.currentTimeMillis() ) {
progress = (int) (timerEnd - System.currentTimeMillis()) / 1000;
// Update the progress bar
progressHandler.post(new Runnable() {
public void run() {
progressBarHorizontal.setProgress(progress);
}
});
try {
Thread.sleep(500);
} catch (InterruptedException e) {
Log.w("tag","Progress thread cannot sleep");
}
}
}
}).start();
But it is not working either.
The second piece of code actually works, the problem was with my logic.
you can try the CountDownTimer :
pd = ProgressDialog.show(MovementEntry.this, "", "Please Wait...",
true, false);
pd.show();
new CountDownTimer(60000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
//this will be done every 1000 milliseconds ( 1 seconds )
int progress = (60000 - millisUntilFinished) / 1000;
pd.setProgress(progress);
}
#Override
public void onFinish() {
//the progressBar will be invisible after 60 000 miliseconds ( 1 minute)
pd.dismiss();
}
}.start();
This one will update the statusbar until it reaches its maximum value:
private int progress = 0;
private final int pBarMax = 60;
...
final ProgressBar pBar = (ProgressBar) findViewById(R.id.progressBar1);
pBar.setMax(pBarMax);
final Thread pBarThread = new Thread() {
#Override
public void run() {
try {
while(progress<=pBarMax) {
pBar.setProgress(progress);
sleep(1000);
++progress;
}
}
catch(InterruptedException e) {
}
}
};
pBarThread.start();
You can try this code for that:
Thread timer = new Thread(){
public void run(){
try{
sleep(10000);
while(progressBarStatus < 10000){
StartPoint.this.runOnUIThread(new Runnable(){
public void run()
{
progressBar.setProgress(progressBarStatus);
progressBarStatus += 1000;
}
});
}
}catch(InterruptedException e){
e.printStackTrace();
}finally{
}
}
};
timer.start();
This code works for me
new Thread(new Runnable() {
public void run() {
long timerEnd = System.currentTimeMillis() + 60 * 1000;
while (timerEnd > System.currentTimeMillis()) {
progress = 60 - (int) (timerEnd - System.currentTimeMillis()) / 1000;
// Update the progress bar
progressHandler.post(new Runnable() {
public void run() {
progressBarHorizontal.setProgress(progress);
}
});
try {
Thread.sleep(500);
} catch (InterruptedException e) {
Log.w("App","Progress thread cannot sleep");
}
}
progressHandler.post(new Runnable() {
public void run() {
okButton.performClick();
}
});
}
}).start();