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.
Related
I built a timer, and even when I go out from the activity, the Timer continues, how can I stop it when I leave the current activity?
Thread:
t = new Thread() {
#Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(5000);
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
output = new teste().execute(getconversationid).get();
setMyInt(output);
Log.e("", output);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
} catch (InterruptedException e) {
}
}
};
t.start();
In onDestroy() or onStop() method stop the timer thread by calling
t.kill();
On the other hand I would recommend using a simple cound down timer class instead of building one yourself. and then call objectname.cancle() in onDestroy or onStop() method.
public class pauseTimer extends CountDownTimer {
public pauseTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
}
}
I have this thread wating for onTouchEvent()
private Runnable disconnectCallback = new Runnable() {
#Override
public void run() {
// Perform any required operation on disconnect
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(),"Your session expired Please Login again",Toast.LENGTH_SHORT).show();
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
final Logout l=new Logout();
l.setContext(Ac2.this);// passing context of Ac3.java to Logout.java
l.execute(sessid,uname);
}
});
}
};
what i want is notify this waiting thread when user touches a mobile screen..
private Runnable disconnectCallback = new Runnable() {
#Override
public void run() {
// Perform any required operation on disconnect
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(),
"Your session expired Please Login again",
Toast.LENGTH_SHORT).show();
try {
synchronized (disconnectCallback) {
disconnectCallback.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
final Logout l = new Logout();
l.setContext(Ac2.this);// passing context of Ac3.java to
// Logout.java
l.execute(sessid, uname);
}
});
}
};
and in onTouch event call:
disconnectCallback.notifyAll();
Try this
private Runnable disconnectCallback = new Runnable() {
#Override
public void run() {
// Perform any required operation on disconnect
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(),
"Your session expired Please Login again",
Toast.LENGTH_SHORT).show();
}
});
try {
synchronized(disconnectCallback){
disconnectCallback.wait();
final Logout l=new Logout();
l.setContext(Ac2.this);// passing context of Ac3.java to Logout.java
l.execute(sessid,uname);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Inside onTouch
synchronized (disconnectCallback) {
disconnectCallback.notify();
}
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.
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;
}
I have this code in android. But when the Thread begging the loading in freezing. How can I prevent this freezing happens. Here is the code related the issue:
private void reload(final String criteria) {
try {
myProgressDialog = ProgressDialog.show(myfiles.this,
"Please wait...", "Loading Your Photos... Please Wait",
false);
new Thread() {
public void run() {
try {
Thread.sleep(2000);
} catch (Exception e) {
}
runOnUiThread(new Runnable() {
#Override
public void run() {
// Fetch the fact
try {
/* here my code */
} catch (Exception e) {
myProgressDialog.dismiss();
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
// Dismiss the Dialog
myProgressDialog.dismiss();
}
}.start();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
It would be great if someone can check
By using runOnUiThread you are doing your intensive load task on the UI thread which will freeze the UI. You want to run your task in a background thread, and then on task completion update the ui.
Thread task = new Thread(new Runnable() {
void run() {
//load some data.
// notify UI thread using Handler
}
});
task.start();