簡體   English   中英

如何在使用服務的 android 中互聯網連接不可用時顯示對話框

[英]How to display dialog when internet connection not available in android using services

我正在創建一個 android 應用程序。 當互聯網連接不可用時,我需要顯示一個對話框。我不需要在每個活動中編寫網絡連接檢查。 如何在android中使用服務來實現這一點?

創建一個名為CheckConnection的類,如下所示

比您在要檢查互聯網連接是否可用的地方調用這個類

代碼

public class ConnectionCheck {

    public boolean isNetworkConnected(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        if (ni == null) {
            // There are no active networks.
            return false;
        } else
            return true;
    }

    public AlertDialog.Builder showconnectiondialog(Context context) {

        final AlertDialog.Builder builder = new AlertDialog.Builder(context)
                .setIcon(R.mipmap.ic_launcher)
                .setTitle("Error!")
                .setCancelable(false)
                .setMessage("No Internet Connection.")
                .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });

        return builder;
    }
}

打電話給你想檢查互聯網連接的班級:如上行

ConnectionCheck connectionCheck = new ConnectionCheck();
        if (connectionCheck.isNetworkConnected(this)){// or your context pass here
            //operation you want if connection available
        }else {
            connectionCheck.showconnectiondialog(this);  //context pass here
        }

並且您必須在ManifestActivity.xml添加訪問網絡狀態和 Internet 的權限:

<uses-permission android:name="android.permission.INTERNET"/> 
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE">

暫無
暫無

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

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