I made a script which detects if there's internet connection:
public static boolean isOnline() {
try {
InetAddress.getByName("google.hu").isReachable(3);
return true;
} catch (UnknownHostException e){
return false;
} catch (IOException e){
return false;
}
}
If there's no internet the app will warn the user and the quit! But how to delay super.onBackPressed for 20 seconds? :)
this.toast1 = new Toast(getApplicationContext());
toast1.setGravity(Gravity.CENTER, 0, 0);
toast1.setDuration(20000);
toast1.setView(layout);
toast1.show();
super.onBackPressed();
Thread delayThread= new Thread(new Runnable()
{
#Override
public void run()
{
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
activityInstance.this.runOnUiThread(new Runnable()
{
#Override
public void run()
{
super.onBackPressed();
}
});
}
});
delayThread.start();
The easiest is to create a Handler in onCreate()and use postDelayed() with a Runnable that calls super.onBackPressed()
Related
I have IntentService that need to wait in method a() for results of onReceive() of BroadcastReceiver().
For now i use lmao wait(5000)... so it's not too elegant
IntentService:
private boolean methodA() {
try {
synchronized (mLocalBroadcastReceiver) {
mLocalBroadcastReceiver.wait(3000);
}
} catch (InterruptedException e) {
Log.e(TAG,"error, thread interrupted");
e.printStackTrace();
}
if(CONSTANT == true){
return true;
else
return false;
}
BroadCastRecievier:
#Override
public void onReceive(Context context, Intent intent) {
CONSTANT = true //changes somehow between true/false
}
In other words: return value of methodA depends on results of onReceive(). How to synchronize two threads?
Finally i used thread like that:
private void waitForResponse() {
//wait for response
thread = new WaitForStatus();
thread.run();
try {
synchronized (thread) {
thread.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private class WaitForAppStatus implements Runnable {
#Override
public void run() {
while (true) {
if (CONSTANT != -1) {
break;
} else {
try {
wait(400);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
Aoa. I'm facing a problem with androird surfaceView.. I'm trying to animate a ball by changing its x,y coordinates. But ball is disappearing... Please see the code and identify the issue,
regards.`
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawBitmap(tile1, axisX, axisY,null); //LINE ONE objects
canvas.drawBitmap(tile2, axisX+78, axisY,null);
canvas.drawBitmap(tile3, axisX+156, axisY,null);
canvas.drawBitmap(tile4, axisX+234, axisY,null);
canvas.drawBitmap(movingStick, (mWidth-movingStick.getWidth())/2, mHeight-200,null);
canvas.drawBitmap(mBall, balCurrPosX,balCurrPosY ,null);
}
//thread code
Thread t=new Thread(new Runnable() {
private boolean moveUp = true;
#Override
public void run() {
// TODO Auto-generated method stub
try{
while (true) {
if (balCurrPosY >= mHeight){
moveUp= false;
}else if(balCurrPosX<=0){
moveUp = true;
}
if(moveUp)
balCurrPosY--;
else
balCurrPosY++;
Thread.sleep(2000);
postInvalidate();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});`
You forgot to start your new Thread at the end of your code :
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
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.
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.