In my program I want this alert dialog to show after 3000ms. how can I do this? I tried a lot but I couldnt. any Idea?
Help is always appreciated...!
AlertDialog.Builder successfullyLogin = new Builder(Register.this);
successfullyLogin.setCancelable(false);
successfullyLogin.setMessage("Successfully Login !");
// successfullyLogin.wait(3000);// this line is nt working
successfullyLogin.setPositiveButton("Ok",new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog,int which)
{
}
});
I think the wait function you are calling should be specifically used for multithreading...
try this...
new Thread()
{
public void run()
{
sleep(3000);
AlertDialog.Builder successfullyLogin = new Builder(LWM.this);
successfullyLogin.setCancelable(false);
successfullyLogin.setMessage("Successfully Login !").show();
}
};
The wait method is part of java.lang.Object and causes the calling thread to wait until another thread calls the notify() or notifyAll() method of this object or until the specified timeout expires. It's not used to implement "sleep" like functionality.
You could start an AsyncTask (that will start a background thread). In the doBackGround, you could sleep the thread for 3 seconds (not blocking the UI), and in your doPostExecute you can pop the dialog.
Instead of showing an alert box why dont u put an suucess message as a toast for 3 seconds....
or else if u want to show the alert box for 3 seconds first remove the ok button then use handlers for close the alert box...
You could use AsyncTask or Timer to accomplish that. If you use AsyncTask, sleep in the background and show the dialog in onPostExecute
The accepted answer here should give you a good head start. Just substitute toast for dialog and you're done.
How to display toast inside timer?
i.e. Use a timer to create a new thread to count down your 3 seconds, and use a handler to display your dialog or toast message on the main UI thread.
Create a Handler in your Activity's class (can be assigned local variable). Then set it up to send a sendEmptyMessageDelayed() inOnStart(). Then, in your handler, create the alert dialog. Note that, since an Activity can be terminated at any time by Android, you need to also override OnStop()in your Activity and call removeMessages() on your handler. If you don't do this, the message is left in the queue but your Activitiy will have already been terminated when the event fires. The result is a rather confusing Exception.
This approach also has the benefit of being able to terminate the message from firing in the first place. For instance, if you finish doing whatever needs to be done before then, you can simply remove the message from the queue and it won't fire.
Related
Because you must include a legal notice when using google maps on android I added the following code to my fragment:
//in oncreate view method
_noticeMaps.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Toast.makeText(getActivity().getApplicationContext(), "Loading", Toast.LENGTH_LONG).show();
showLegalNotice();
}
});
public void showLegalNotice(){
_legalNotice = GooglePlayServicesUtil.getOpenSourceSoftwareLicenseInfo(getActivity());
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Legal Notice");
builder.setMessage(_legalNotice);
AlertDialog dialog = builder.create();
dialog.show();
}
Because the legal notice takes a long time to be placed in the setMessage the app shows the dialog after a few seconds (5+). Thats why i added the toast before the showLegalNotice to notice the user that its loading. However the toast shows after the dialog is loaded. Why isnt the toast showing before the dialog is loading? I call showLegalNotice AFTER i create the toast. I know i can fix it with threads but I want to understand why the toast is showing after the dialog is created.
The best solution is to put the legalNotice method codes in an AsyncTask. The Toast is shown after the dialog because you are doing the heavy work on the UI thread which is making it busy and that's why the toast is lagging behind.
If you don't know about AsyncTask, you can learn about it here. You can show the Toast in the preExecute() method of the AsyncTask. It will be guaranteed that the toast will be shown before any other action is taken.
UPDATE
Yes, you are right. The code is run in a sequential manner so the Toast should have been shown before the method runs. But try to think in a different way.
The Toast is an system UI component. You call show() on toast and your code moves to the next heavy or long-running task almost instantly.
There is always a slight delay for the toasts to be drawn or initiated on your screen and it also depends on various flavours of Android. So, before the toast starts to draw on the screen, the UI thread gets busy or jammed on performing a long-running task and looses frames.
Just when the long-running task of your method ends, the UI thread gets free once again and is able to resume drawing the toast. That is why, the toast is displayed, but always after the method completed its execution.
I want to show up pop up window after an activity has been launched. It is just like after a few seconds delay pop up should come. How can I implement that?Any ideas or examples?? If so I will be helpful ..Thanks in advance.
Many ways to do so.
If you have a list of Activities where you want to show the POP-up, you can uses two ways:
Create a service which actively checks for the foreground [Top most activities] in the stack and if the activity on which you want to show the pop-up, just send the broadcast to show the pop-up.
Create a Class which extends a Asynctask class, which waits for Xsecs in doinbackground and shows a pop-up over onpostexecute, Just call the execute of the Asynctask class while oncreate ends if you want to show only one time.
Asynctask class will be the best to use in such scenario. By this you can re-use this asynctask class every where in the project.
new Handler().postDelayed(new Runnable(){ #Override
public void run() {
// This method will be executed once the timer is over
//call your toast here.
//TIME_OUT is no of milliseconds you want to wait before Toast is popped.
} },TIME_OUT);
Hope this helps.
I'm connecting to bluetooth in background and I want to show alert or toast befor processing socket.
Here is my code
mmSocket.connect();
connectionHandler.post(new Runnable() {
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(BluetoothSampleActivity.this);
builder.setMessage("conneted");
builder.show();
}
});
manageConnectedSocket(mmSocket);
but as I understand alert will be shown only when this will end his work. How can i show alert BEFORE executing manageConnectedSocket(mmSocket);?
P.S.: I tryed runOnUiThread - it didn't help
I suggest to move your logic from a normal Thread to an AsyncTask. Whenever you have to do heavy work but also to interact with the UI, AsyncTask is the best practice.
On the preExecute() method you show the dialog or update UI, on doInBackground you do whatever you need to do and on onPostExecute you dismiss the dialog or re-update the UI.
Here the AsyncTask doc.
En plus, if you need to show a progress of the work that you are doing in background, it comes super easy thanks to the methods publishProgress/onProgressUpdate.
I want to make a Progress Dialog Box in my app to use when sending some information. But the code I wrote won't work. It the method send() executes but the dialog box never appears because it dismisses very quickly
Here is my code :
ProgressDialog myProgressDialog = ProgressDialog.show(Tents.this,
"Please wait...", "Sending...", true);
send();
myProgressDialog.dismiss();
goFour();
How do I make the Dialog Box Last a little longer?
First of all - you should not do send() in the same thread as show() and dismiss() - because you are effectively blocking UI thread during sending. The dialog will actually never show - because in order to show it after show() is called, you need to give the control back to the main looper in UI thread and simply finish handling whatever event you are handling. Otherwise the UI thread will never have a chance to draw your dialog.
The best idea is to start running send() in AsyncTask and call dismiss() in onPostExecute() (see http://developer.android.com/reference/android/os/AsyncTask.html to get idea how to run async task).
You are probably getting a progress dialog, but having it immediately dismiss as it has nothing to wait for.
I'll pretend you want this in OnCreate for my example:
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ProgressDialog pd = ProgressDialog.show(this, "Please wait...", "Sending...");
new Thread(new Runnable(){
public void run() {
send();
pd.dismiss();
}
}).start();
gofour();
}
EDIT: If it still goes away immediately, make sure send(); does something that actually takes some time. ;)
The UI thread is used to start send() , this will not work and progress dialog will not be shown .
Call send in another thread or AsynTask doBackground and on completion dismiss the dialog.
If your send action is completing so quickly that the dialog is not displaying properly, might I suggest instead using an indeterminate progress bar in the upper right corner of your activity via requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS) and then utilizing setProgressBarIndeterminateVisibility(true/false).
"I guess my real question would then be how do I make it so that it lasts a little longer?" My answer would be WHY???!!!
I think you would be better showing an alert dialog to confirm your send function has completed, it would be annoying for the user having to wait for no reason!
I am developing my first Androïd application and I'm facing a problem when I want to display a ProgressDialog to indicate that a process is being run.
In my application, the user triggers a time consuming task by pressing a Button. The "OnClick" function of my "OnClickListener" is called when the user presses the Button. In this function, here is what I'm currently doing :
- creation and configuration of an instance of the ProgressDialog class,
- creation of a thread dedicated to the time consuming task,
- attempt to display the ProgressDialog using the "show" method,
- start of the thread,
- main Activity suspended (call of the "wait" function)
- wake up of the main Activity by the thread when it is finished
- removal of the ProgressDialog by calling the "dismiss" function.
Everything works fine (the result of the long task is correct) but the ProgressDialog nevers appears. What am I doing wrong?
Thanks in advance for the time you will spend trying to help me.
You should not call wait() to the Main Activity/UI thread, because this is actually freezing the UI including your ProgressDialog, so it has no time to fade in and will never be shown.
Try to use multithreading correctly: http://developer.android.com/resources/articles/painless-threading.html
final Handler transThreadHandler = new Handler();
public void onClick(View v) {
// show ProgressDialog...
new Thread(){
public void run(){
// your second thread
doLargeStuffHere();
transThreadHandler.post(new Runnable(){public void run(){
// back in UI thread
// close ProgressDialog...
}});
}
}.start();
}
I would suggest using AsyncTask, as it's purpose is exactly to handle this kind of problem. See here for instructions how to use it. Note that the linked page in Floern's answer also recommends the use of AsyncTask.
You would need to do the following:
subclass AsyncTask
override it's onPreExecute() method to create and show a ProgressDialog. (You could hold a reference to it in a member of your subclass)
override it's doInBackground() method to execute your time consuming action.
override it's onPostExecute() method to hide your dialog.
in your activity, create an instance of your subclass and call execute() on it.
If you make your subclass an inner class of your activity, you can even use all of your activity's members.