簡體   English   中英

當Android應用中無法使用互聯網連接時,如何暫停當前活動

[英]How to pause the current activity when internet connection is not available in android app

我的Android應用需要互聯網連接。 我已經使用broadcastreceiver來監視網絡連接狀態。 但是,當網絡連接斷開時,如何暫停活動?

如果您獲得網絡連接的狀態,則在未連接的情況下,只需調用Activity的onPause方法即可?

public void onPause() {
    super.onPause();
    //pause anything else
}

然后當您再次連接網絡時調用onResume嗎?

public void onResume() {
    super.onResume();
    //resume application
}

這取決於您暫停活動的意思:

  • 如果要阻止用戶在沒有互聯網的情況下對活動執行任何操作,則應顯示無網絡視圖並隱藏其他所有內容
  • 如果您想實際觸發該活動的暫停,我認為只有在您轉到其他活動時才會發生
  • 您還可以完成活動並顯示一條祝酒消息,如果沒有互聯網連接就無法工作

請提供更多說明,我可能會為您提供幫助

  • 更新:

根據您的評論,您可以顯示帶有重試按鈕的視圖並隱藏ListView

您還可以使用ListView.setEmptyView(View) ,看看此StackOverflow帖子, 關於ListView上的setEmptyView不在Android應用程序中顯示其視圖

但是我通常在RelativeLayout內部創建類似的內容:

`

<LinearLayout
    android:id="@+id/layoutNoInternet"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    android:visibility="gone">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:text="Please check your internet connection!" />

    <Button
        android:id="@+id/btnRetry"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Retry"/>
</LinearLayout>

<ListView
    android:id="@+id/listView"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

`

我將沒有互聯網布局的visibility設置為gonevisible

暫無
暫無

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

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