timer is not working properly android - android

In my app I am using a timer and timerTask to perform a certain task repeatedly. the timer is being used in a service. when I run the timer the TimerTask is not called after a certain delay my code is
`
final Timer timer = new Timer();
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Log.i(TAG, "onStart");
Thread thread = new Thread(this);
thread.start();
try {
Thread.sleep(GlobalClass.time);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void run() {
Log.i(TAG, "onStart");
timer.schedule(new TimerTask() {
#Override
public void run() {
Log.i(TAG, "i am in timertask");
try {
setbackground();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, GlobalClass.time, GlobalClass.time);
}
` GlobalClass.time is a static long variable. please help me.

use handler for calling a function repeatedly
declear in ocCreate()
Handler handler = new Handler();
handler.postDelayed(checkFunction(),1000);
create function depends on your requirement
private Runnable checkFunction(){
Timer t = new Timer();
TimerTask tt = new TimerTask() {
public void run() {
handler.postDelayed(checkFunction(),1000);
/// write coding for your requirement here
}
};
return tt;
}

Related

How to Update UI while a task is running in another thread in android?

I have tried updating my user interface using the text view what i have done is a run a while loop indefinitely and left the thread for sleep for one second..
int i;
while(true)
{
Thread.Sleep(1000);
textView.setText(updateTime);
}
Use runOnUiThread and surround with try catch for Thread.sleep(1000)
int i;
while(true)
{
try {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
textView.setText(updateTime);
}
});
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Try this one arnab...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView textView = (TextView) findViewById(R.id.displayid);
handler = new Handler() {
#Override
public void handleMessage(Message msg) {
bundle = msg.getData();
textView.setText(bundle.getString("mKey"));
}
};
}
public void press(View v) {
new Thread(new Runnable() {
#Override
public void run() {
while (true) {
synchronized (this) {
try {
wait(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
bundle = new Bundle();
message = handler.obtainMessage();
simpleDateFormat = new SimpleDateFormat("hh:mm:ss YYYY/mm/dd", Locale.US);
date = simpleDateFormat.format(new Date());
bundle.putString("mKey", date);
message.setData(bundle);
handler.sendMessage(message);
}
}
}
}).start();
}
Try runOnUiThread:
runOnUiThread(new Runnable() {
#Override
public void run() {
textView.setText(updateTime);
}
});

By starting a new activity, it starts again and again

I set a textview, which I use for timer-function.
When the timer reachs my wanted time it should start a new activity, that set my Layout to another one.
textfield=(TextView)findViewById(R.id.TVTimer);
handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
while (Running){
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
// TODO: handle exception
}
handler.post(new Runnable() {
#Override
public void run(){
number+=1;
textfield.setText(String.valueOf(number));
if (number>5) {
Intent intent = new Intent(getApplicationContext(), Uebung2.class);
startActivity(intent);
}
}
} );
}
}
};
new Thread(runnable).start();
That is the called class:
public class Uebung2 extends Oberklasse {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
//Liegestützen1(2);
setContentView(R.layout.new);
}
}
Now I am having the problem after the timer reached the time, which I want, my app is settin g the layout again and again for every second.
What is the solution to set the layout for once?
beacuse you have place this
handler.post(new Runnable() {
#Override
public void run(){
number+=1;
textfield.setText(String.valueOf(number));
if (number>5) {
Intent intent = new Intent(getApplicationContext(), Uebung2.class);
startActivity(intent);
}
}
} );
inside your while loop.
also check your "number" value.
try your while loop as
int i=1000;
while (i<5000){
try {
Thread.sleep(i);
i+=1000;
}
catch (InterruptedException e) {
e.printStackTrace();
// TODO: handle exception
}
}
and after this execute your runnable.
use this
textfield=(TextView)findViewById(R.id.TVTimer);
boolean loop = true;
handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
while (loop){
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
// TODO: handle exception
}
handler.post(new Runnable() {
#Override
public void run(){
number+=1;
textfield.setText(String.valueOf(number));
if (number>5) {
loop = false; // this will end loop
Intent intent = new Intent(getApplicationContext(), Uebung2.class);
startActivity(intent);
}
}
} );
}
}
};
new Thread(runnable).start();

Show Toast from a thread started in a broadcast receiver

I have a BroadcastReceiver.
There I create a new Thread.
How can I show a toast in that thread?
Thanks
Use below code for perform UI operation from non-UI thread
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// your stuff to update the UI
}
});
Try This code
public void start_insert() {
pDialog.show();
new Thread() {
#Override
public void run() {
int what = 0;
try {
// Do Something in Background
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
what = 1;
e.printStackTrace();
}
handler22.sendMessage(handler22.obtainMessage(what));
}
}.start();
}
private Handler handler22 = new Handler() {
#Override
public void handleMessage(Message msg) {
pDialog.dismiss();
Toast.makeText(getApplicationContext(), "SuccessFull",
10).show();
}
};
Activity_Name.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// your stuff to update the UI
}
});
Use this code to update UI thread or execute any UI related operation.

timer.setText("setTextHere") does not work inside the thread

timer.setText("setTextHere") does not work inside the thread.
Thread thread1 = new Thread(){
TextView timer;
int t;
public void run(){
timer=(TextView) findViewById(R.id.timer);
try{
timer.setText("setTextHere");
sleep(5000);
}
catch(Exception e){
e.printStackTrace();
}
finally{
Intent new1 = new Intent("com.example.app1.MENU");
startActivity(new1);
}
}
};
thread1.start();
_t = new Timer();
_t.scheduleAtFixedRate( new TimerTask() {
#Override
public void run() {
_count++;
runOnUiThread(new Runnable() //run on ui thread
{
public void run()
{
_tv.setText( "" + _count );
}
});
}
}, 1000, 1000 );
You cannot touch UI from background thread. Try to use AsyncTask http://developer.android.com/reference/android/os/AsyncTask.html
On your onCreate() add:
h = new Handler();
add this somewhere:
class SetText implements Runnable {
public void run() {
// do UI task
timer.setText("setTextHere");
}
}
on someFunction() modify like this:
...
try
{
h.post( new SetText() );
sleep(5000);
}
...
final TextView timer = (TextView) findViewById(R.id.timer);
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(2000);
timer.post(new Runnable() {
public void run() {
timer.setText("setTextHere");
}
});
} catch (Exception e) {
e.printStackTrace();
} finally {
Intent new1 = new Intent("com.example.app1.MENU");
startActivity(new1);
}
}
}).start();
you could use this and initialize the setText before initializing the Thread
Thread thread1 = new Thread(){
int t;
public void run(){
try{
sleep(5000);
}
catch(Exception e){
e.printStackTrace();
}
finally{
Intent new1 = new Intent("com.example.app1.MENU");
startActivity(new1);
}
}
};
TextView timer;
timer=(TextView) findViewById(R.id.timer);
timer.setText("setTextHere");
thread1.start();

Automatically Refresh JmDNS Services in Activity

I'm trying to automatically refresh JmDNS services in the background. Nothing is happening when I try:
#Override
public void onDestroy() {
try {
hiNeighborService.unregisterListener(this);
this.unbindService(this.serviceConnection);
} catch (Exception ex) {
Log.e(LOG_TAG, "Exception occur during destroying the app.");
}
super.onDestroy();
}
#Override
public void onStart() {
/*new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
refreshServices();
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();*/
ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool(5);
// This schedule a runnable task every 2 minutes
scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
public void run() {
rebindService();
refreshServices();
}
}, 0, 1, TimeUnit.SECONDS);
super.onStart();
}
#Override
public void onRestart() {
/*new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
refreshServices();
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();*/
ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool(5);
// This schedule a runnable task every 2 minutes
scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
public void run() {
rebindService();
refreshServices();
}
}, 0, 1, TimeUnit.SECONDS);
super.onRestart();
}
#Override
public void onResume() {
/*new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
refreshServices();
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();*/
ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool(5);
// This schedule a runnable task every 2 minutes
scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
public void run() {
rebindService();
refreshServices();
}
}, 0, 1, TimeUnit.SECONDS);
super.onResume();
}
This is my resfreshServices() method:
private void refreshServices() {
Log.i(LOG_TAG, "Refresh available neighbors...");
final List<Neighbor> activeNeighbors = this.hiNeighborService
.getActiveNeighbors();
Log.d(LOG_TAG, activeNeighbors.size() + " active neighbors are found!");
new Thread(new Runnable() {
public void run() {
Log.i(LOG_TAG, "refresh UI...");
try {
synchronized (activeNeighborsViewModel) {
activeNeighborsViewModel.clear();
for (Neighbor neighbor : activeNeighbors) {
NeighborViewModel vm = new NeighborViewModel(
neighbor);
vm.setNeighborUnreadCount(ConnectActivity.this
.getUnreadMessageCount(neighbor));
if (activeNeighborsViewModel.contains(vm)) {
activeNeighborsViewModel.remove(vm);
}
activeNeighborsViewModel.add(vm);
}
}
notifyServiceListChanged();
Log.i(LOG_TAG, "refresh completed!");
} catch (Exception ex) {
ex.printStackTrace();
Log.e(LOG_TAG, ex.toString());
}
}
}).start();
}
Normally that gets call when a button is clicked however I would like it to be automatic. This code doesn't do anything unless I hit the Resfresh button that call resfreshServices(). I attempted to try it with threads but the activity closes and so does the app. Any ideas?
First a little comment on your code. Why are you implementing the same code three times in three different methods. I assume that you are programming android (loking at your method names). The method onresume is executed every time the activity is started or resumed. See this link for more information on this topic.
Ok, then... Did you already check the docs for more information about the ScheduledExecutorService?
Now for the jmdns issue. The jmDns library has a build in functionality to update the services. you can listen to new services and take the appropriate action when new services are available. I do not think, that repeated polling of the services is the right approach.
Look here for a little tutorial on using jmdns in android.

Categories

Resources