1

在我的应用程序中,我总是在互联网的帮助下连接到 openfire 服务器。现在,如果连接在两者之间丢失或断开连接,我希望它应该弹出一个窗口,并且在按下 OK 按钮时它应该重新登录该人(就像与服务器的连接丢失时一样 - 即使该人是 1 秒断开连接)。

我正在使用以下代码:

public class ConnectionCheck extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub

        ConnectivityManager connectivityManager =  (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
        NetworkInfo mobileNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

        if(activeNetInfo!=null){
            Toast.makeText( context, "Active Network Type : " + activeNetInfo.getTypeName(), Toast.LENGTH_SHORT ).show();
        }

         if( mobileNetInfo != null )
            {
              Toast.makeText( context, "Mobile Network Type : " + mobileNetInfo.getTypeName(), Toast.LENGTH_SHORT ).show();
            }

    }

假设当 wifi 断开连接时,它再次连接到移动网络(但内部用户没有连接到服务器)

我应该怎么做,即当用户断开连接时 - 即使从服务器一秒钟,它也应该弹出一个窗口。

是否可以??

谢谢

4

2 回答 2

5

-您上面的代码只会检查您的 android 设备与wifi 路由器或手机的数据包服务的连接,但它不会检查 wifi 是否真的有互联网连接工作。

-当我在做一个项目时,我曾经很震惊地找到了这个解决方案,我试着在 stackoverflow 上寻找一个解决方案,但我得到的是和你一样的代码。所以我创建了自己的解决方案。

我需要做一些自定义工作..但是让它运行起来......

我的代码在关闭时从 Wifi 切换到移动网络。

我正在使用端口 37 的 TimeService 来知道 Internet 已死,而 wifi 连接仍处于打开状态

现在我在这里放一个我制作的完整的工作代码。请原谅我,因为DRY(不要重复自己的原则)在这里被滥用了single sensible place所以在生产网络中使用时请重构代码并将重复的代码转换为方法,即转换为a 。

/////---------------------------Intial Available Network Checking



private boolean checkConnection(){


boolean connected = false;
ConnectivityManager cm =  (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

if (cm != null) {
NetworkInfo[] netInfo = cm.getAllNetworkInfo();

for (NetworkInfo ni : netInfo) {
if ((ni.getTypeName().equalsIgnoreCase("WIFI")
|| ni.getTypeName().equalsIgnoreCase("MOBILE"))
& ni.isConnected() & ni.isAvailable()) {
connected = true;
     }

   }
 }


return connected;
} /////---------------------------Intial Available Network Checking

/////--------------------------------------------检查工作的互联网连接

public boolean inetAddr(){

    boolean x1 = false;


    try {
        Socket s = new Socket("utcnist.colorado.edu", 37);

        InputStream i = s.getInputStream();

        Scanner scan = new Scanner(i);

        while(scan.hasNextLine()){

            System.out.println(scan.nextLine());
            x1 = true;
        }
    } catch (Exception e) {


            x1 = false;
    } 

    return x1;

}

/////-------------------------------Check for the working Internet Connection


////-------------------------------Check Mobile Conectivity Again

public boolean mobileConnect(){

    boolean conn = false;
    ConnectivityManager cm =  (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNet = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

    if(activeNet != null){

        conn = true;
    }else{

        conn = false;
    }

    return conn;



}

////------------------------------Check Mobile Conectivity Again

在这里,我正在使用上述方法....

try{    
     if (!checkConnection()){


         AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(YumZingSplashActivity.this);
         myAlertDialog.setTitle("--- Connectivity Check ---");
         myAlertDialog.setMessage("No Internet Connectivity");
         myAlertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {

          public void onClick(DialogInterface arg0, int arg1) {

            YumZingSplashActivity.this.finish();
            //splashHandler.removeCallbacks(launcherRunnable);

          }});
            System.out.println("No Internet Connectivity");

            myAlertDialog.show();           




        }
        else{


              if(inetAddr()){
            aphandle = APIHandling.getInstance();
            aphandle.xmlCreateSession();
            System.out.println("Net Connectivity is Present");
            DURATION = Integer.valueOf(getString(R.string.splash_duration));



            splashHandler = new Handler();

            //  ================ Main Code of the Application
            launcherRunnable = new Runnable() {

                public void run() {
                    Intent i = new Intent(YumZingSplashActivity.this, YumZingTabHostActivity.class);
                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(i);
                    YumZingSplashActivity.this.finish();
                }
            };
            if (DEBUG)
            {
                splashHandler.post(launcherRunnable);
            }
            else{


                splashHandler.postDelayed(launcherRunnable, DURATION);
            }

        }
              else{

                  if(mobileConnect()){


                      if(inetAddr()){
                      aphandle = APIHandling.getInstance();
                        aphandle.xmlCreateSession();
                        System.out.println("Net Connectivity is Present");
                        DURATION = Integer.valueOf(getString(R.string.splash_duration));



                        splashHandler = new Handler();

                        //  ================ Main Code of the Application
                        launcherRunnable = new Runnable() {

                            public void run() {
                                Intent i = new Intent(YumZingSplashActivity.this, YumZingTabHostActivity.class);
                                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                startActivity(i);
                                YumZingSplashActivity.this.finish();
                            }
                        };
                        if (DEBUG)
                        {
                            splashHandler.post(launcherRunnable);
                        }
                        else{


                            splashHandler.postDelayed(launcherRunnable, DURATION);
                        }
                      }else{

                          AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(YumZingSplashActivity.this);
                         myAlertDialog.setTitle("--- Connectivity Check ---");
                         myAlertDialog.setMessage("No Internet Connectivity");
                         myAlertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {

                          public void onClick(DialogInterface arg0, int arg1) {

                            YumZingSplashActivity.this.finish();
                            //splashHandler.removeCallbacks(launcherRunnable);

                          }});
                            System.out.println("No Internet Connectivity");

                            myAlertDialog.show();       
                      }
                  }else{




                         AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(YumZingSplashActivity.this);
                         myAlertDialog.setTitle("--- Connectivity Check ---");
                         myAlertDialog.setMessage("No Internet Connectivity");
                         myAlertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {

                          public void onClick(DialogInterface arg0, int arg1) {

                            YumZingSplashActivity.this.finish();
                            //splashHandler.removeCallbacks(launcherRunnable);

                          }});
                            System.out.println("No Internet Connectivity");

                            myAlertDialog.show();           






                  }

              }
        }

     //setContentView(R.layout.yumzing_splash_layout);
    }  catch(Exception ex){

            System.out.println("Leak ko catch");
        }



    }
于 2013-01-08T05:21:59.130 回答
2

你也可以试试这个服务类。只需设置以秒为单位的时间间隔和要 ping 的 url:

Android 检查互联网连接

只要记住将服务添加到 Manifest 文件中,并添加权限

于 2015-03-21T14:34:27.153 回答