簡體   English   中英

如何減少或消除從按鈕單擊啟動 Android 活動的延遲

[英]How to reduce or remove the delay on starting an Android activity from button click

我已經注意到這個問題很久了。 當我通過按鈕打開一個活動時,我能感覺到在活動“開始”啟動之前有一點延遲,比如 1 秒,即使這兩個活動都是空的,好像是故意延遲一樣。

我檢查過的每個其他 StackOverflow 線程都有某種負載,這會減慢它的速度。 但是,這完全是空的,沒有負載或后台任務。

我所說的延遲是什么意思:當我單擊按鈕時,該應用程序會在一秒鍾內什么都不做,然后在啟動下一個活動時開始轉換。 用戶可能認為該應用程序沒有響應。

測試設備慢嗎? 我不認為是這樣。

  1. 我已經在 Android 10 VM 中測試過(延遲 1 秒),

  2. Android 9, 8, 7, 6, 5.1, 5 VM(1 秒延遲),

  3. 諾基亞 1 Plus(慢)使用 Android 10 和 9(1/2 秒延遲),

  4. 諾基亞 5.1 與 Android 9(1/4 秒延遲),

  5. Galaxy s6 Edge with Lineage 16 (Android 9) and Android 7.0 stock No Delay,

  6. Galaxy s5 Lineage 15 (Android 8), Lineage 14 (Android 7), Stock 6.0 (1/8 Second delay),

  7. Galaxy m31 和 m21 和 A51 與 Android 9 One UI1? (1/2 秒延遲),

我確實看到了一種模式,即更快的手機延遲更少,無論結果如何,其他應用程序在同一部手機中的響應速度更快。 相同設備上的 Google 應用程序的響應速度要快得多。

安卓工作室 4.0

知道原因嗎?

主要活動代碼:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    
    public void Onclick(View view){
        startActivity(new Intent(this,MainActivity2.class));
    }
}

主活動activity_main:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="Onclick"
        android:text="Open Activity 2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

主活動2

public class MainActivity2 extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
    }
}

MainActivity2 活動_main2:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity2">

</androidx.constraintlayout.widget.ConstraintLayout>

您可以嘗試使用android profiler來跟蹤/調查更多。 但是從整體來看,一個布局簡單的Activity應該不會有任何延遲。 其他可能影響延遲的因素是設備資源可用性。 因此,如果您的代碼與您在問題中提到的相同,則一定是設備性能造成了延遲。

暫無
暫無

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

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