androidhandlerprogressdialogdelayed-execution

How to delay code execution (draw the path) for few seconds?


This is the problem about loading. My application should wait for 3 seconds and then draw path. Now, the loading message box appears within 3 seconds but the application does not wait for 3 seconds and draw immediately . Is there any problem in my coding ?

Many Thanks!!

 public void drawpath(){
       // first to do some checking
    if (sourceLat.equals("22.3366467")  && destinationLat.equals("35.68449"))
        ShowMsgDialog("Please enter the starting point and destination");
    else if (sourceLat.equals("22.3366467") )
        ShowMsgDialog("Please enter the starting point by touch");
    else if (destinationLat.equals("35.68449") )
        ShowMsgDialog("Please enter the destination by touch");

    else if (pairs != null ){
        //  go to loading function
        loading();
        // Start to draw the path
        String[] lngLat = pairs[0].split(",");

        GeoPoint startGP = new GeoPoint((int) (Double.parseDouble(lngLat[1]) * 1E6), (int) (Double.parseDouble(lngLat[0]) * 1E6));

         mc = mapView.getController();
         geoPoint = startGP;
         mc.setCenter(geoPoint);
         mc.setZoom(15);
         mapView.getOverlays().add(new DirectionPathOverlay(startGP, startGP));

                ...... 
        }

in the loading() function:

private void loading() {
    progressDialog = ProgressDialog.show(this, "Showing Data..", "please wait", true, false);
    new Thread()
    { 
      public void run()
      { 
        try{ 
          sleep(3000);
        }
        catch (Exception e){
          e.printStackTrace();
        }
        finally{
            progressDialog.dismiss();    
        }
      }
    }.start(); 
}

Solution

  • A handler would do the job very easily.You won't need a separate thread or AsyncTask().

    Use a Handler in your Activity to delay events such as calling the method drawPath() in your case:

    private RefreshHandler mRedrawHandler = new RefreshHandler(); 
     private RefreshHandler mRedrawHandler = new RefreshHandler(); 
    
         class RefreshHandler extends Handler {  
                @Override  
                public void handleMessage(Message msg) {  
              drawPath(); 
                }  
    
                public void sleep(long delayMillis) {  
                  this.removeMessages(0);  
                  sendMessageDelayed(obtainMessage(0), delayMillis);  
                }  
              };  
    

    In your onCreate() of Activity (or In onClick() of any button, whenever you want to start a delay), call mRedrawHandler.sleep(3000); , drawPath(); is a method where you are starting the draw.