Android后台服务或Receiver在后台检查互联网连接

时间:2013-01-08 04:49:35

标签: android service broadcastreceiver

在我的应用程序中,我总是在互联网的帮助下连接到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断开连接时,它再次连接到移动网络(但内部用户未连接到服务器)

我应该怎样做同样的事情,即当用户断开连接时 - 即使是服务器一秒钟,它也应该弹出一个。

有可能吗?

由于

2 个答案:

答案 0 :(得分:4)

- 您的上述代码只会检查您的Android设备与 wifi路由器或手机的数据包服务的连接性,但不会检查wifi是否确实有互联网连接正常工作。

- 当我在一个项目上工作时,我曾经找到过这个解决方案,我试着通过stackoverflow查找解决方案,但我得到的就是你的代码片段。 所以我创建了自己的解决方案。

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

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

我正在使用端口37的TimeService知道互联网是DEAD而wifi连接仍然是ON

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

/////---------------------------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

///// -------------------------------检查有效的Internet连接

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");
        }



    }

答案 1 :(得分:1)

您也可以尝试此服务类。只需设置以秒为单位的时间间隔和要ping的网址:

Android Check Internet Connection

请记住将服务添加到清单文件,然后添加权限