0

我需要在没有互联网连接时显示警报消息。我添加了以下代码。但是在没有互联网连接时警报框没有显示。

这是代码:

 if (isNetworkAvailable(getApplicationContext()))
 {
       // Do whatever you want to do
 }
 else{

    try {

        AlertDialog.Builder builder = new AlertDialog.Builder(LiveChat.this);

         builder.setTitle("Message");
        builder.setMessage("Do you want to end the chat session?");
        // Add the buttons

        builder.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {

                        dialog.cancel();
                    }

        });
        AlertDialog alert = builder.create();
        alert.show();

        }
        catch(Exception e)
        {
    System.out.println("alert="+e);
        }
 }

我在 onCreate 中添加了这段代码,

 public boolean isNetworkAvailable(Context context) {

        boolean value = false;
        ConnectivityManager connec = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED
                || connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED) {
            value = true;
        }

        // Log.d ("1", Boolean.toString(value) );
        return value;
    }

当我关闭互联网连接时,会显示警报框,但是在我的应用程序中间,互联网变慢或失去连接,我没有收到任何警报

我需要每秒检查一次互联网是否可用,如果没有连接,我需要显示警报框。

有人可以帮我吗@谢谢

4

5 回答 5

2

我已经检查过这段代码工作正常使用这个创建一个内部,它将每五秒检查一次

    private final long refreshDelay = 5 * 1000;
    SendHttpRequestThread sendHttpRequestThread; 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        sendHttpRequestThread = new SendHttpRequestThread();
        sendHttpRequestThread.start();

    }

 class SendHttpRequestThread extends Thread {

        boolean sendHttpRequest;


        public SendHttpRequestThread() {

            sendHttpRequest = true;
        }

        public void stopSendingHttpRequest() {
            sendHttpRequest = false;
        }

        protected void onStop() {
            sendHttpRequestThread.stopSendingHttpRequest();
            super.stop();
        }

        @Override
        public void run() {
            while (sendHttpRequest) {
               boolean isConnected = isNetworkConnected();
                if(!isConnected){
                    showAlertDialog()
                }


                SystemClock.sleep(refreshDelay);
            }
        }
    }

检查网络连接

  private boolean isNetworkConnected() {
                  ConnectivityManager conManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
                  NetworkInfo netInfo = conManager.getActiveNetworkInfo();
                  if (netInfo == null) {
                   // There are no active networks.
                   return false;
                  } else {
                   return true;
                  }
                 }

显示对话框

 private void showAlertDialog() {
                AlertDialog.Builder builder = new AlertDialog.Builder(
                        this.class);
                builder.setTitle("Error");
                builder.setMessage("No Network Connection").setCancelable(false)
                        .setIcon(R.drawable.error)
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                error = "";
                            }
                        });
                AlertDialog alert = builder.create();
                alert.show();
        }
于 2013-09-06T07:55:37.800 回答
0

试试这个代码,

Boolean isInternetPresent = false;
    ConnectionDetector cd;
cd = new ConnectionDetector(getApplicationContext());
    isInternetPresent = cd.isConnectingToInternet();

    if (!isInternetPresent) {
        // Internet Connection is not present
        alert.showAlertDialog(LoginActivity.this, "Internet Connection Error",
                "Please connect to working Internet connection", false);
        // stop executing code by return
        return;
    }
于 2013-09-06T07:51:23.920 回答
0

我使用以下代码检查互联网是否可用。

public static boolean isOnline(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    }
    return false;
}

if(!isOnline){
  //show alert
}else{
//continue with ur work
}

您还需要在您的清单文件中获得此权限

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

希望这可以帮助你

于 2013-09-06T07:54:16.700 回答
0
//Method to check Internet Availability with Dialog box
public class CheckingInternet{
public static boolean isInternetAvailable(final Context context) {
//      boolean returnTemp = true;

        ConnectivityManager conManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo i = conManager.getActiveNetworkInfo();
        if ((i == null) || (!i.isConnected()) || (!i.isAvailable())) {

        return false;
        }
        return true;
    }   

     public static  void showDialogForInternetConection(Context mContext){

         AlertDialog.Builder netNotAvailable=new AlertDialog.Builder(mContext);
         netNotAvailable.setMessage("Could not find an Internet connection. Please check your settings and try again.");
         netNotAvailable.setTitle("Attention");
         netNotAvailable.setIcon(R.drawable.attention);


         netNotAvailable.setNeutralButton("Ok", new DialogInterface.OnClickListener() {

        //  @Override
            public void onClick(DialogInterface arg0, int arg1) {

            }
        });
         netNotAvailable.show();
     }

//With your Main Activity to show dialog
if(CheckingInternet.isInternetAvailable(mContext)){
//do Something
}
else{
CheckingInternet.showDialogForInternetConection(Context);
}
于 2013-09-06T07:57:31.173 回答
0

我不确定,但是您是否在 UI-Thread 上调用它?如果您不这样做,则可能是问题所在。您只需将代码放入:

getActivity().runOnUiThread(
    new Runnable()
    {
        @Override
        public void run()
        {
            //Your code here
        }
    }
)
于 2013-09-06T07:49:23.470 回答