簡體   English   中英

Android中5秒后執行函數

[英]Execute function after 5 seconds in Android

我是 android 開發的新手,現在我的啟動器活動只顯示 5 秒,之后我想檢查用戶是否登錄或未運行並執行操作。

這是我的代碼。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    exactPreferences = getSharedPreferences("ExactPreference",MODE_PRIVATE);
    setContentView(R.layout.activity_landing_page);

    session = exactPreferences.getString(Model.getSingleton().SHARED_SESSION_ID,null);
    Log.i("Session Id",session);
        displayData(); // I want to perform this function after 5 seconds.
}


private void displayData() {
    if(session.equals("")){
        Intent loginIntent = new Intent(LandingPage.this,
                LoginActivity.class);
        startActivity(loginIntent);
        Log.i("User Logged In", "False");
    }
    else
    {
        Intent objIntent = new Intent(LandingPage.this,
                IndexPageActivity.class);
        startActivity(objIntent);
        Log.i("User Logged In", "True");
    }

}

您可以使用 Handler 來添加一些延遲。調用如下所示的 displayData displayData()方法,使其在 5 秒后執行。

new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
          displayData();
        }
    }, 5000);

注意:不要使用像Thread.sleep(5000);這樣的線程Thread.sleep(5000); 因為它會阻止您的用戶界面並使其無響應。

使用您希望導致延遲的毫秒數分配millisDelayTime變量。 mActivityActivity 的一個對象,用於提供 Application Context。 在您的情況下, millisDelayTime應初始化為 5000

mActivity.runOnUiThread(new Runnable() {
@Override
    public void run() {
    final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
       @Override
       public void run() {
             //your code here
       }
    }, millisDelayTime);
  }
});

使用倒數計時器

// There's a TextView txtCount in Main Activity

final int secs = 5;
new CountDownTimer((secs +1) * 1000, 1000) // Wait 5 secs, tick every 1 sec
{
    @Override
    public final void onTick(final long millisUntilFinished)
    {
        txtCount.setText("" + (int) (millisUntilFinished * .001f));
    }
    @Override
    public final void onFinish()
    {
        txtCount.setText("GO!");
        finish();
        // Time's up - Start the Login Activity
        final Intent tnt =
            new Intent(getApplicationContext(), LoginActivity.class);
        startActivity(tnt);
    }
}.start();
long delay = 1000;
long period = 50000;
Timer task = new Timer();
task.scheduleAtFixedRate(new TimerTask() {
    @Override
    public void run() {
        getDriver(sessionManager.getKEY(), ride_id);
    }
}, delay, period);

對於 kotlin 方式

Handler().postDelayed({
        //do something
    }, 5000)

試試這個,代碼一鍵創建 CountDownTimer

timer = new CountDownTimer(5000, 5000)
{
    public void onTick(long millisUntilFinished)
    {
    }

    public void onFinish()
    {
        displayData();
    }
};
timer.start();

由於 Handler 現在已棄用,因此請使用以下代碼:

 new Handler(Looper.myLooper()).postDelayed(new Runnable() {
     @Override
     public void run() {
         //do what you want 
     }
 }, 5000);

實現這一目標的最佳選擇是使用Handler

int TIME = 5000; //5000 ms (5 Seconds)

new Handler().postDelayed(new Runnable() {
    @Override
    public void run() {

        function(); //call function!

    }
}, TIME);

如果可能,盡量避免使用 postDelayed。 這是一種不好的做法,因為它可能會丟失對您要在屏幕上繪制的對象的引用並導致 NPE。 改用處理程序。 首先,創建一個全局變量 Handler,您必須在其中“處理”代碼的邏輯。 通過使用函數handleMessage 來實現。

Handler  handler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
        if(msg.what == 1){
            // your code here
        }
    }
};       

然后,無論您想在哪里執行它,只需調用該函數:

// 1 is the ID of your process
handler.sendEmptyMessageDelayed(1, 5000);

請記住,在 onDestroyView 方法(在片段中)或 onDestroy(在活動中)中,您必須調用

    handler.removeMessages(1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM