TimerTask doesn't take effect - android

Here's my code:
public class SomeName extends MapActivity implements OnClickListener, OnTouchListener{
public Timer t1 = new Timer();
public TimerTask tt;
public long interval = 5000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.map);
timer();
}
public final void timer()
{
t1 = new Timer();
tt = new TimerTask() {
#Override
public void run() {
systemClick();
}
};
t1.scheduleAtFixedRate(tt, 10000, interval);
}
public void systemClick()
{
Toast.makeText(getApplicationContext(),"System Button Clicked", 5).show();
}
Actually, I want to call some function, where I refresh my location.
But I can't understand why I never get the toast on the screen.
I'm new to android.
Thanks for any help.

use handler in your Activity
final Handler handlerforadd = new Handler();
Runnable runnableforadd = new Runnable() {
#Override
public void run() {
handlerforadd.postDelayed(this, 1000);
}
};
handlerforadd.postDelayed(runnableforadd, 0);

The reason is the Toast has to be done on the UI thread. In your current code the method run() is being executed on a separate thread. I would suggest looking at this article on Processes and Threads. #parag is correct using a Handler is one way to get a reference to the UI thread but there are other methods.

Related

Cyclic restart my application in 3h intervals. How to?

I need to write an application to open the browser (sample site www.onet.pl), which will restart every 3 hours. The commotion of restart was displayed. I managed to create such a layout, but I can not handle the cyclical restart. Please help where to add and what code? One class is enough.
This is my code:
public class MainActivity extends AppCompatActivity {
private Object v;
Handler mHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start(null);
m_Runnable.run();
}
public void start(View v) {
Uri uri = Uri.parse("http://onet.pl");
Intent i = new Intent(Intent.ACTION_VIEW, uri);
startActivity(i);
this.mHandler = new Handler();
}
private final Runnable m_Runnable = new Runnable() {
public void run() {
Toast.makeText(MainActivity.this, "odświezenie strony", Toast.LENGTH_SHORT).show();
MainActivity.this.mHandler.postDelayed(m_Runnable, 15000);
}
};
}
You could use a timer instead of Runnable.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
Toast.makeText(MainActivity.this, "odświezenie strony", Toast.LENGTH_SHORT).show();
//and put the rest of your code here
}
},0,5000);

I am looking to exit a handler and go back to activity code when it has done its job

I have been trying to figure out how to make a countdown timer using 'handler()' and i still don't know how to make it so the app will execute the line "Finished" when the countdown hits 0.
I am after whatever line of code is required for me to enter in the 'UpdateGUI()' to exit the runnable and go back to the main activity to display "Finished".
I have not been coding very long, so maybe it is an obvious answer, but I can't find it on any threads on this page...
Some help would be much appreciated :-)
Thank you
public class MainActivity extends AppCompatActivity {
int i = 10;
TextView tv;
final Handler myHandler = new Handler();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button but = (Button) findViewById(R.id.button);
but.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
tv = (TextView) findViewById(R.id.textView);
Timer myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
UpdateGUI();
}
}, 0, 1000);
tv = (TextView) findViewById(R.id.textView);
tv.setText("Finished");
}
});
}
private void UpdateGUI() {
if (i == 0) {
//this is where i need to enter the code!!
}
else
i--;
myHandler.post(myRunnable);
}
final Runnable myRunnable = new Runnable() {
public void run() {
tv.setText(String.valueOf(i));
}
};
}
If I understand you correctly in case you need to run your runnable after some period of time use Handler method postDelayed(runnable, timeOutInMillis)
UPDATE: example of handler timer
int timesRun;
Handler handler = new Handler();
Runnable runnable = new Runnable() {
public void run() {
runTimer();
i++;
}
};
// call it in button callback
public void runTimer(){
// update your timer here
if (i != 10) // if 10 seconds not passed run it one more time
handler.postDelayed(runnable, 1000); // run every second
}
Note that this is not the most elegant way to do this, but still, it should work

Updating a textview that shows current time every second or minute

Hi Iam trying to update 3 textviews every second. I have written this piece of code. the thread starts normally but the textviews they do not get updated. I am passing a function inside the text parameters of the texts views that gets the current system time (using Calendar) in digits but then converts it to letters. example: for 3.45 THREE FORTYFIVE. any help would be appreciated. thanks
public class MainActivity extends Activity {
TextView currentv;
GetDate gd;
TextView currentmin;
TextView currentmins;
private Handler mHandler;
private boolean Running = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
currentv = (TextView) this.findViewById(R.id.tvtimehour);
currentmin = (TextView) findViewById(R.id.tvtimemin);
currentmins = (TextView) findViewById(R.id.tvtimesecond);
gd = new GetDate();
currentv.setText(gd.calculateTimeHour());
currentmin.setText(gd.calculateTimeMinute());
currentmins.setText(gd.calculateTimeMinuteDigit());
mHandler = new Handler();
Runnable runb = new Runnable(){
#Override
public void run(){
while(Running == true){
try{
Thread.sleep(1000);
}
catch(Exception e){
e.printStackTrace();
}
mHandler.post(new Runnable(){
#Override
public void run(){
currentv.setText(gd.calculateTimeHour());
currentmin.setText(gd.calculateTimeMinute());
currentmins.setText(gd.calculateTimeMinuteDigit());
}
});
}
}
};
new Thread(runb).start();
}
Try this,
private MyTimerTask mytask;
private Timer timer;
mytask = new MyTimerTask();
timer = new Timer();
timer.schedule(mytask, 0,60000);
Timer class:
class MyTimerTask extends TimerTask {
#Override
public void run() {
// TODO Auto-generated method stub
runOnUiThread(new Runnable() {
public void run() {
// Do your stuff here it will work
currentv.setText(gd.calculateTimeHour());
currentmin.setText(gd.calculateTimeMinute());
currentmins.setText(gd.calculateTimeMinuteDigit());
}
});
}
}
Use Timer for this, I think because Thread can not update your UI.

Timer and TextView

I'm trying to understand how to use a timer.
In my MainActivity.class, inside on create method, i have this code
Timer timer = new Timer();
TimerTask updateM = new GestioneSlide();
timer.scheduleAtFixedRate(updateM , 1000, 5000); // i want to do a thing every second for 5 seconds
then i have another class where i override the method run, and where i want to write something in a texview that is in my MainActivity.class
class GestioneSlide extends TimerTask {
#Override
public void run() {
MainActivity.TextViewName.setText("bla bla");
}
}
My app crash, if i delete the MainActivity.TextViewName.setText("bla bla"); i have no problem. Probably i can't write in that textview that way
What did i do wrong?
The timer does not fire its actions in GUI thread. Use runOnUiThread to switch into it. Assuming GestioneSlide is the inner class of your Activity, write
class GestioneSlide extends TimerTask {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
MainActivity.TextViewName.setText("bla bla");
}
}
}
Make a Handler and show msg inside handler.
private class mainTask extends TimerTask
{
public void run()
{
toastHandler.sendEmptyMessage(0);
}
}
private final Handler toastHandler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
Toast.makeText(getApplicationContext(), "test", Toast.LENGTH_SHORT).show();
}
};

Create a Timer to send HTTP request Periodically - Android

I want to end HTTP request from a Android device to a web server and check a particular data of a database periodically (once a minute). I couldn't implement a timer for this.
Thanks
public class MyActivity extends Activity {
Timer t ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
t = new Timer();
t.schedule(new TimerTask() {
public void run() {
//Your code will be here
}
}, 1000);
}
}
Try AlarmManager running Service. I wouldn't recommend sending request each minute thou, unless it's happening only when user manually triggered this.
TimerTask doAsynchronousTask;
final Handler handler = new Handler();
Timer timer = new Timer();
doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
if(isOnline){// check net connection
//what u want to do....
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 10000);// execute in every 10 s
The most easy method is to loop a Handler:
private Handler iSender = new Handler() {
#Override
public void handleMessage(final Message msg) {
//Do your code here
iSender.sendEmptyMessageDelayed(0, 60*1000);
}
};
To start the loop call this sentence:
iSender.sendEmptyMessage(0);

Categories

Resources