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.
Related
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();
}
Is it possible to do splash screen that will execute HTTP request and if this request is executing too long, i.e. 7-10 seconds, then abort the request and jump to the main activity?
The below code is what I did, but it doesn't work - the timeout isn't working, the HTTP request and jumping are working. As I understand, it's possible to use the AsyncTask's get() method or handler with delay. Get() method should be in separate thread but it doesn't work. How to do this task?
EDIT:
public class SplashActivity extends Activity {
private static final String TAG = "SplashActivity";
private Handler handler = new Handler();
private Runnable r;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_layout);
if (Helpers.isNetworkConnected(getApplicationContext())) {
Log.d(TAG, "Has Internet");
final DownloadFAQ downloadFAQ = new DownloadFAQ();
new Thread(new Runnable() {
public void run() {
try {
Log.d(TAG, "Timing...");
downloadFAQ.execute().get(1000, TimeUnit.MILLISECONDS);
SplashActivity.this.runOnUiThread(new Runnable() {
public void run() {
Log.d(TAG, "redirect");
redirect();
}
});
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
downloadFAQ.cancel(true);
Log.d(TAG, "Task has benn canceled");
if (downloadFAQ.isCancelled())
redirect();
}
}
}).start();
} else {
r = new Runnable() {
public void run() {
redirect();
}
};
handler.postDelayed(r, 2500);
}
}
private class DownloadFAQ extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
Log.d(TAG, "Execute task");
ServerAPI server = new ServerAPI(getApplicationContext());
server.serverRequest(ServerAPI.GET_FAQ, null);
return null;
}
}
private void redirect() {
Intent i = new Intent(SplashActivity.this, TabsActivity.class);
startActivity(i);
finish();
}
#Override
protected void onDestroy() {
super.onDestroy();
handler.removeCallbacks(r);
}
}
because you are trying to start AsyncTask again inside doInBackground when it's still running . change your code as to get it work :
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_layout);
downloadFAQ = new DownloadFAQ();
new Thread(new Runnable() {
public void run() {
try {
downloadFAQ.execute().get(2000, TimeUnit.MILLISECONDS);
SplashActivity.thisrunOnUiThread(new Runnable() {
public void run() {
// start Activity here
Intent i = new Intent(SplashActivity.this,
TabsActivity.class);
SplashActivity.this.startActivity(i);
SplashActivity.this.finish();
}
});
} 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
e.printStackTrace();
}
}
}).start();
}
and you will need to remove downloadFAQ.get(2000, TimeUnit.MILLISECONDS); from doInBackground method change your AsyncTask as
private class DownloadFAQ extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
ServerAPI server = new ServerAPI(getApplicationContext());
server.serverRequest(ServerAPI.GET_FAQ, null);
return null;
}
protected void onPostExecute(Void result) {
}
}
consider using asyncTask status:
AsyncTask.Status
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.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ThraedDemo objDemo = new ThraedDemo();
Thread objThread = new Thread() {
#Override
public void run() {
objDemo.firstMethod();
}
};
objThread.start();
}
class ThraedDemo {
private void firstMethod() {
Thread objThread = new Thread() {
#Override
public void run() {
try {
((ImageView)findViewById(R.id.ImageViewnumber)).setImageResource(nums[n]);
Thread.sleep(10000);
Log.v("Thread","1111111111111111sleep");
} catch (InterruptedException ex) {
System.out.println("interuped exception" + ex.getMessage());
}
secondMethod();
}
private void secondMethod() {
Thread objThread = new Thread() {
#Override
public void run() {
try {
((ImageView)findViewById(R.id.ImageViewResult)).setImageResource(nums[n+1]);
n++;
Thread.sleep(10000);
Log.v("Thread","22222222222 sleep");
} catch (InterruptedException ex) {
System.out.println("interuped exception" + ex.getMessage());
}
firstMethod();
}
};
objThread.start();
}
};
objThread.start();
}
}
I use the above code but it is not running.it got CalledFromWrongThreadException what is the problem inb the above code.Please give me some suggestions.Thanks in advance
I think you can't do view modifications from another thread than the UI thread, so either create handlers in the oncreate and post your thread to it, or use AsyncTask, or runOnUIThread method to send portions of code directly to the UI thread.
I edited your 2nd function code, I see your code is loop forever cause the firstMethod call secondMethod and the secondMethod call the new firstMethod to start and then loop forever. I removed it and moved the code update ImageView into the UI Thread, could you try this:
class ThraedDemo {
private void firstMethod() {
Thread objThread = new Thread() {
#Override
public void run() {
try {
runOnUiThread(new Runnable() {
public void run(){
((ImageView)findViewById(R.id.ImageViewnumber)).setImageResource(nums[n]);
}
});
Thread.sleep(10000);
Log.v("Thread","1111111111111111sleep");
} catch (InterruptedException ex) {
System.out.println("interuped exception" + ex.getMessage());
}
secondMethod();
}
};
objThread.start();
}
private void secondMethod() {
Thread objThread2 = new Thread() {
#Override
public void run() {
try {
runOnUiThread(new Runnable() {
public void run(){
((ImageView)findViewById(R.id.ImageViewnumber)).setImageResource(nums[n+1]);
}
});
n++;
Thread.sleep(10000);
Log.v("Thread","22222222222 sleep");
} catch (InterruptedException ex) {
System.out.println("interuped exception" + ex.getMessage());
}
}
};
objThread2.start();
}
}
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();