Compare two time continously in android - android

I want to run Async Task in Android every intervals.
my interval is = { 15 min , 30 min , 1 hour ....etc
Depending on the users' choice.
When I start my application then I want to fetch my current time and after every n interval I want to execute Async Task
int intv = 15;
SimpleDateFormat sd = new SimpleDateFormat(
"HH:mm:ss");
Date date = new Date();
sd.setTimeZone(TimeZone.getTimeZone("GMT+05:30"));
System.out.println(sd.format(date));
String currenttime = sd.format(date);
Date myDateTime = null;
try
{
myDateTime = sd.parse(currenttime);
}
catch (ParseException e)
{
e.printStackTrace();
}
System.out.println("This is the Actual Date:"+sd.format(myDateTime));
Calendar cal = new GregorianCalendar();
cal.setTime(myDateTime);
cal.add(Calendar.MINUTE , intv ); //here I am adding Interval
System.out.println("This is Hours Added Date:"+sd.format(cal.getTime()));
try {
Date afterintv = sd.parse(sd.format(cal.getTime()));
if(afterintv.after(myDateTime)){ //here i am comparing
System.out.println("true..........");
new SendingTask().execute; //this is the function i have to execute
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
But I am not getting how to do.

If you want to run the AsyncTask after sometime you can use Thread.sleep in your AsyncTask. In this case is the SendingTask class. Here is a sample:
class SendingTask extends AsyncTask{
// Interval is in milliseconds
int interval = 1000;
public SendingTask(int interval) {
// Setting delay before anything is executed
this.interval = interval;
}
#Override
protected Object doInBackground(Object[] params) {
// Wait according to interval
try {
Thread.sleep(interval);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
// update UI and restart asynctask
textView3.setText("true..........");
new SendingTask(3000).execute();
}
}

Related

Android: Show elapsed time on UI for given start time and continue to update it with handler (timer)

I get a project start time from a web service and work out the time the project had taken up to the current date. I store the datetime I get from the web in the startTimeList.
Here is how I'm getting the current elapsed time on the project:
public void setTimeElapsed() {
try {
Calendar calStart = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
calStart.setTime(sdf.parse(startTimeList.get(0)));
long startMillis = calStart.getTimeInMillis();
long now = System.currentTimeMillis();
long difference = now - startMillis;
Calendar calDiff = Calendar.getInstance();
calDiff.setTimeInMillis(difference);
int eYear = calDiff.get(Calendar.YEAR);
int eMonth = calDiff.get(Calendar.MONTH);
int eDay = calDiff.get(Calendar.DAY_OF_MONTH);
int eHour = calDiff.get(Calendar.HOUR_OF_DAY);
int eMin = calDiff.get(Calendar.MINUTE);
int eSec = calDiff.get(Calendar.SECOND);
mimDuration.setText(String.format("%d Months %d Days %d:%d:%d", eMonth, eDay, eHour, eMin, eSec));
} catch (ParseException e) {
Log.e(TAG, "Error: " + e.getMessage());
}
}
However this does not keep updating the elapsed time for the user to see the real time. I need to add a handler (timer) of some sorts to keep updating the time on the UI.
Any help would be appreciated. Thank you.
You can create a timerTask and use a timer to schedule it periodically. Inside the run method you can update the ui by either using runOnUiThread method or a handler.
So something like
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
Long spentTime = System.currentTimeMillis() - startTime;
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
}
},0, interval);

How to set time out for AsyncTask execution?

I have been trying to create time out while AsyncTask execution more than 1 minute. If the time up, then should exit with Notification.
This is my code:
private class GetLongLat extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
longlatDialog = new ProgressDialog(MainActivity.this);
longlatDialog.setMessage("Fetching Data. Please wait..");
longlatDialog.setCancelable(false);
longlatDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
GPSTracker gpsTracker;
//This is the timer to set time out
Timer timer = new Timer();
timer.schedule(new TaskKiller(this), 3000);
timer.cancel();
do{
gpsTracker = new GPSTracker(MainActivity.this);
gpsTracker.getLocation();
}while(!String.valueOf(gpsTracker.latitude).equals("0.0"));
return null;
}
protected void onCancelled() {
// do something, inform user etc.
Toast.makeText(getApplicationContext(), "Failed getting long lat. Please check your internet connection", Toast.LENGTH_LONG).show();
System.exit(1);
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (longlatDialog.isShowing())
longlatDialog.dismiss();
}
}
And this is a class called in doInBackground to set the time up.
class TaskKiller extends TimerTask {
private AsyncTask<?, ?, ?> mTask;
public TaskKiller(AsyncTask<?, ?, ?> task) {
this.mTask = task;
}
public void run() {
mTask.cancel(true);
}
}
But when i run the code, nothing happen. I mean the progress dialog always run very long time.
EDIT
I have edit my code to call GetLongLat something like this:
GetLongLat n = new GetLongLat();
n.execute();
try {
n.get(3000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TimeoutException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), "Failed getting long lat. Please check your internet connection", Toast.LENGTH_LONG).show();
System.exit(1);
}
But also, doesn't work.
I think you can use AsyncTask.get()
GetLongLat n = new GetLongLat();
n.get(30000, TimeUnit.MILLISECONDS);
you will have to use the n.get in a separate Thread..
Edited: one more different method but not efficient.,
GetLongLat n = new GetLongLat();
n.execute();
Handler handler = new Handler();
handler.postDelayed(new Runnable()
{
#Override
public void run() {
if ( n.getStatus() == AsyncTask.Status.RUNNING )
n.cancel(true);
}
}, 30000 );
why are you canceling the timer? just after calling schedule()?
Cancels the Timer and all scheduled tasks
timer.cancel(); should be removed. check docs for cancel()
You can achieve this behaviour in many ways.
Here's an example using CountDownTimer
// Start your AsyncTask
private YourAsyncTask mTask = new YourAsyncTask().execute();
// Run a timer after you started the AsyncTask
new CountDownTimer(60000, 1000) {
public void onTick(long millisUntilFinished) {
// Do nothing
}
public void onFinish() {
mTask.cancel(true);
}
}.start();
You are cancelling the timer just after initiating it. You can do it like this too. But this type of busy waiting is not recommended at all.
#Override
protected Void doInBackground(Void... arg0) {
GPSTracker gpsTracker;
//This is the timer to set time out
new CountDownTimer(60000, 1000) {
public void onTick(long millisUntilFinished) {
// Do nothing
}
public void onFinish() {
// Set latitude to zero to finish the while loop outside.
// gpsTracker.latitude = "0.0"; // Something like this
}
}.start();
do{
gpsTracker = new GPSTracker(MainActivity.this);
gpsTracker.getLocation();
}while(!String.valueOf(gpsTracker.latitude).equals("0.0"));
return null;
}
Here's another approach. In your doInBackground method, you can use System.currentTimeMillis to check whether 1 minute has elapsed or not.
protected Void doInBackground(Void... arg0) {
GPSTracker gpsTracker;
long startTime = System.currentTimeMillis();
do{
gpsTracker = new GPSTracker(MainActivity.this);
gpsTracker.getLocation();
}while(!String.valueOf(gpsTracker.latitude).equals("0.0")
&& ((System.currentTimeMillis() - startTime) <= 60000);//60000 millisecond = 1 minute
return null;
}
`
Just alter your code like this and check whether your async task is getting cancelled or not.
GetLongLat getLongLatAsync = new GetLongLat();
getLongLatAsync.execute();
try {
Handler handler = new Handler();
/** 1st method **/
handler.postDelayed(new Runnable()
{
#Override
public void run() {
if (getLongLatAsync.getStatus() == AsyncTask.Status.RUNNING )
getLongLatAsync.cancel(true);
}
}, 3000 ); //3 Seconds
/** 1st method ends **/
/** second method */
handler.post(new Runnable()
{
#Override
public void run() {
getLongLatAsync.get(3000, TimeUnit.MILLISECONDS);//You should run it in seperated thread or else it will block ui thread.
}
});
/** Second method ends**/
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TimeoutException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), "Failed getting long lat. Please check your internet connection", Toast.LENGTH_LONG).show();
}
and in the onCancelld method write your logic
#Override
protected void onCancelled() {
Log.d(TAG,"Asynctask has been cancelled.");
}

Android listview timer run in every second

I have a issue with using a timer on a listview.
In the list item I showed using sqlite values. There is a textview which showing time difference of last updated time of the data and current time. i have to show it in every one second. so the user can know how long he updated the record.
I tried this in several ways.
First way
I tried to add timer in adapter class. so for every item new timer is created. so application crashed because of many timers run simultaneously.
Second way
I tried using adapter.notifyDataSetChanged() way. Like as this.
Handler timerHandler = new Handler();
Runnable timerRunnable = new Runnable() {
#Override
public void run() {
if (adapterChatThread != null) {
adapter.notifyDataSetChanged();
}
timerHandler.postDelayed(this, 1000); // run every second
}
};
timerRunnable.run();
I move to another activity when click on list item and user can come back to this Activity.
so in Onresume I used
timerHandler.postDelayed(timerRunnable, 500);
and OnPause
timerHandler.removeCallbacks(timerRunnable);
Issue is data is not showing well. I mean in every second data difference is not one second. some time differnce is 2sec, 5 sec, .. etc.
means timer is not working as I expected.
Third way
I used a asynctask and call it in every second using a timer.
class ThreadTimer extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
return null;
}
#Override
protected void onPostExecute(Void result) {
if (adapter != null)
adapter.notifyDataSetChanged();
super.onPostExecute(result);
}
}
I called this as in here
Handler timerHandler = new Handler();
Runnable timerRunnable = new Runnable() {
#Override
public void run() {
new ThreadTimer().execute();
timerHandler.postDelayed(this, 1000); // run every second
}
};
timerRunnable.run();
previous issue triggered. (data not showing well)
Fourth way
Using AsyncTask as this
class ThreadTimer extends AsyncTask<Void, Void, Void> {
void Sleep(int ms) {
try {
Thread.sleep(ms);
} catch (Exception e) {
}
}
#Override
protected Void doInBackground(Void... params) {
while (threadRun) {
Sleep(1000);
return null;
}
return null;
}
#Override
protected void onPostExecute(Void result) {
adapter.notifyDataSetChanged();
super.onPostExecute(result);
}
}
I called this class in OnResume.
In on pause I set threadRun= false;
issue is same.
please help me.
My requirement is update list item in every second.
Thank you.
edit
here is my adapter class textview update code.
Date lastUpdatedTime;
final ChatThreadDAO ctd = new ChatThreadDAO();
long timeForNextResponse = ctd.getLastRespondedTime(vct.get(position).getThread_id());
try {
if (vct.get(position).getThread_read_status() == 1 && timeForNextResponse > 0) {
final long respTime = timeForNextResponse;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
lastUpdatedTime = formatter.parse(vct.get(position).getLast_updated_time());
final long timeDiff = (new Date()).getTime() - lastUpdatedTime.getTime();
if (timeDiff <= respTime) {
timeForNextResponse = respTime - timeDiff;
ctd.updateTimeRespondToLastMsg(vct.get(position).getThread_id(), timeForNextResponse);
holder.tvChatTimer.setVisibility(View.VISIBLE);
holder.tvChatTimer.setText(timeForNextResponse / 1000 + "");
} else {
ctd.updateTimeRespondToLastMsg(vct.get(position).getThread_id(), 0);
}
} else {
holder.tvChatTimer.setVisibility(View.INVISIBLE);
}
} catch (ParseException e) {
e.printStackTrace();
}
here vct is
Vector vct;
I assign the values to vector in adapter class constructer.
Here is an example similar to your case.
private class connectionControl extends Thread {
boolean stop_ = false;
public void stop_() {
this.stop_ = true;
}
public void run() {
System.out.println("Thread started:" + getClass().getSimpleName());
while(!this.stop_) {
try {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Calendar c = Calendar.getInstance();
int rightNow = c.get(Calendar.SECOND) + c.get(Calendar.MINUTE)*60;
if(rightNow - lastUpdatedTime > 10) {
wirelessIcon.setImageResource(R.drawable.wirelessred);
}
else if(rightNow - lastUpdatedTime > 5) {
wirelessIcon.setImageResource(R.drawable.wirelessyellow);
}
else {
wirelessIcon.setImageResource(R.drawable.wirelessgreen);
}
}
});
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("Thread stoped:" + getClass().getSimpleName());
}
}
You set your lastUpdatedTime the same way you created rightNow whenever you call notifyDataSetChanged() method of your adapter.

Clear Way To Update Widget TextView

The amount of time ive spent trying to get methods like Timer, BroadcastReceiver, AlarmManager etc. to work. All i need is a clear way to update the widget or textview every second.
java.util.Date noteTS = Calendar.getInstance().getTime();
String time = "kk:mm";
String date = "dd MMMMM yyyy";
views.setTextViewText(R.id.tvTime, DateFormat.format(time, noteTS));
views.setTextViewText(R.id.tvDate, DateFormat.format(date, noteTS));
I basically need this to set the text either when the time changes or update every second. Every method ive tried has failed. Can someone please give me the best way to do this and how?
You could use a Handler and a Thread:
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
// update your textview here.
}
};
class TickThread extends Thread {
private boolean mRun;
#Override
public void run() {
mRun = true;
while(mRun) {
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
mHandler.sendEmptyMessage(0);
}
}

Android countdown from one date to another

I'm trying to countdown from a start date to an end date. For example, on 12 October 2012 to 14 October 2012.
I would like to get the current date and from this date do the countdown to the next.
Do you have any good examples?
This might prove too inflexible a solution but you could try converting the dates to long values, subtracting one from the other, and then using the android countdown timer class to do your countdown.
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date a = null, b = null;
try {
a = sdf.parse("14-10-2012");
b = sdf.parse("12-10-2012");
} catch (ParseException e) {
e.printStackTrace();
}
// .getTime() does the conversion: Date --> long
CountDownTimer cdt = new CountDownTimer(a.getTime() - b.getTime(), 1000) {
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
}
public void onFinish() {
// TODO Auto-generated method stub
}
}.start();
more information about the class can be found here:
http://developer.android.com/reference/android/os/CountDownTimer.html

Categories

Resources