2013-08-08 2 views

답변

6

당신은 예를 들어 처리기를 사용하고 .removeCallbacks()와 .postDelayed() 메소드마다 사용자가 대화와 상호 작용 호출 할 수 있습니다 감사합니다. 상호 작용시

의 .removeCallbacks() 메소드는 .postDelayed()의 실행을 취소하며, 바로 그 후, 유 .postDelayed()이 Runnable를 내부

으로 새의 Runnable을 시작, 당신은 닫을 수 대화 상자.

// a dialog 
    final Dialog dialog = new Dialog(getApplicationContext()); 

    // the code inside run() will be executed if .postDelayed() reaches its delay time 
    final Runnable runnable = new Runnable() { 

     @Override 
     public void run() { 
      dialog.dismiss(); // hide dialog 
     } 
    }; 

    Button interaction = (Button) findViewById(R.id.bottom); 

    final Handler h = new Handler(); 

      // pressing the button is an "interaction" for example 
    interaction.setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View v) { 


      h.removeCallbacks(runnable); // cancel the running action (the hiding process) 
      h.postDelayed(runnable, 5000); // start a new hiding process that will trigger after 5 seconds 
     } 
    }); 

사용자 상호 작용을 추적, 당신은 사용할 수 있습니다 활동에서 사용할 수

@Override 
public void onUserInteraction(){ 
    h.removeCallbacks(runnable); // cancel the running action (the hiding process) 
    h.postDelayed(runnable, 5000); // start a new hiding process that will trigger after 5 seconds 
} 

합니다.

+0

당신은 나에게 간단한 샘플을 주실 수 있습니까? 안드로이드에 대한 새로운 소식입니다. ( –

+0

핸들러가 아마도 가능할지라도,이 경우 핸들러를 사용하는 방법에 대한 예제를 보여주는 내 게시물을 업데이트했습니다. –

+0

내 대화 상자 시간을 업데이트하는 대화 상자의 모든 내 위젯에 대해 'setOnClickListener()'를 작성해야합니다. 좋은 해결책;) –

1

나는 AsyncTask를 사용하여이 작업을 수행하려면 :

class ProgressDialogTask extends AsyncTask<Integer, Void, Void> { 

    public static final int WAIT_LENGTH = 2000; 
    private ProgressDialog dialog; 

    public ProgressDialogTask(Activity activity) { 
     dialog = new ProgressDialog(activity); 
    } 
    @Override 
    protected void onPreExecute() { 
     dialog.setMessage("Loading"); 
    } 

    @Override 
    protected Void doInBackground(final Integer... i) { 
     long start = System.currentTimeMillis(); 
     while(!isCancelled()&&System.currentTimeMillis()-start< WAIT_LENGTH){} 
     return null; 
    } 

    @Override 
    protected void onPostExecute(final Void v) { 
     if(dialog.isShowing()) { 
      dialog.dismiss(); 
     } 

    } 
} 

그런 다음 클릭에 활동에서 트리거 :

Button button = (Button) findViewById(R.id.button); 
button.setOnClickListener(new OnClickListener() { 

    @Override 
    public void onClick(View v) { 
     ProgressDialogTask task = new ProgressDialogTask(this); 
     task.execute(0); 
    } 
}); 

당신은 또한 System.nanoTime을 (사용할 수있는 더 나은 정밀도를 필요로하는 경우)

0

나는 또한 안드로이드에서 새로 왔지만, 타이머를 만드는 것이 좋습니다. 그리고 타이머 t가 2보다 크거나 같다고 말할 때 당신은 뭔가를합니다.

if (t >= 2.0){ 
//Do whatever you want it to do 
} 

이것은 사용자의 목적에 맞지 않을 수 있지만 결국에는 적은 코드 줄이 필요할 수도 있습니다. (필자가 항상 말하듯이 코드는 코드가 적다) 타이머는 기본적으로 작성하기 쉽지만, 앱에서는 사용하지 않았다. 타이머를 만드는 방법을 구체적으로 알지는 못했지만 YouTube에서 자습서를 찾을 수있을 것입니다.

0

이것은 시간 초과에 관한 것들을 찾을 때 생기는 질문입니다. 나는 AsyncTask, HandlerRunnable을 사용하는 대답을 구현했습니다. 나는 미래의 응답 수색자를위한 잠재적 인 틀로서 나의 대답을 여기에서 제공하고있다. 그 다소 새로

private class DownloadTask extends AsyncTask<Void, CharSequence, Void> { 
    //timeout timer set here for 2 seconds 
    public static final int timerEnd = 2000; 
    private Handler timeHandler = new Handler(); 

    @Override 
    protected void onPreExecute() {    
      ProgressDialog dProgress = new ProgressDialog(/*Context*/); 
      dProgress.setMessage("Connecting..."); 
      dProgress.setCancelable(false); 
      dProgress.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() { 
       @Override 
       public void onClick(DialogInterface dialog, int which) { 
        //Dismissing dProgress 
        dialog.dismiss(); 
        //Removing any Runnables 
        timeHandler.removeCallbacks(handleTimeout); 
        //cancelling the AsyncTask 
        cancel(true); 

        //Displaying a confirmation dialog 
        AlertDialog.Builder builder = new AlertDialog.Builder(/*Context*/); 
        builder.setMessage("Download cancelled."); 
        builder.setCancelable(false); 
        builder.setPositiveButton("OK", null); 
        builder.show(); 
       } //End onClick() 
      }); //End new OnClickListener() 
      dProgress.show(); 
    } //End onPreExecute() 

    @Override 
    protected Void doInBackground(Void... params) { 
      //Do code stuff here 
      //Somewhere, where you need, call this line to start the timer. 
      timeHandler.postDelayed(handleTimeout, timerEnd); 
      //when you need, call onProgressUpdate() to reset the timer and 
      //output an updated message on dProgress. 
      //...   
      //When you're done, remove the timer runnable. 
      timeHandler.removeCallbacks(handleTimeout); 
      return null; 
    } //End doInBackground() 

    @Override 
    protected void onProgressUpdate(CharSequence... values) { 
     //Update dProgress's text 
     dProgress.setMessage(values[0]); 
     //Reset the timer (remove and re-add) 
     timeHandler.removeCallbacks(handleTimeout); 
     timeHandler.postDelayed(handleTimeout, timerEnd); 
    } //End onProgressUpdate() 

    private Runnable handleTimeout = new Runnable() { 
     public void run() { 
       //Dismiss dProgress and bring up the timeout dialog 
       dProgress.dismiss(); 
       AlertDialog.Builder builder = new AlertDialog.Builder(/*Context*/); 
       builder.setMessage("Download timed out."); 
       builder.setCancelable(false); 
       builder.setPositiveButton("OK", null); 
       builder.show(); 
     } 
    }; //End Runnable() 
} //End DownloadTask class 

AsyncTask를 사용하여, 당신은 DownloadTask object을하고 .execute()를 호출해야합니다. 예를 들어

:

DownloadTask dTaskObject = new DownloadTask(); 
dTaskObject.execute(); 
난 사실도 추가로 내 모든 doInBackground() 코드는 함수를 통해 수행 할 수함으로써 참조 것보다이 코드를했다, 그래서 실제로 onProgressUpdate() 전화를했다 및 기타 기능이 DownloadTask를 사용

목적.

관련 문제