2010-11-22 40 views
0

我有使用Internet的应用程序的工作。Android中的Internet连接

  • 它包含URL的XML解析。 比
  • 显示进度对话框在解析 时间。
  • 解析完成时停止对话框。
  • 在ListView中设置TEXT(数据)。

我的问题是,当设备连接到互联网比我的应用程序工作正常但是当设备没有连接到互联网“进度对话框”运行无限时间。

我想,如果设备没有连接到互联网或WiFi停止对话。这个怎么做?
有什么想法? 对不起家伙....我改变了主意,我想检查互联网连接,当我点击按钮。什么是截至目前为止我已经试过..

public void onCreate(Bundle savedInstanceState) { 

     super.onCreate(savedInstanceState); 
     setContentView(R.layout.homelayout); 
     mclip = (ImageButton) findViewById(R.id.clip); 
     mclip.setClickable(true); 
     mclip.setFocusable(true); 

     mclip.setOnClickListener(new OnClickListener() { 

      public void onClick(View view) { 
       ConnectivityManager cm = (ConnectivityManager)    getSystemService(Context.CONNECTIVITY_SERVICE); 
       NetworkInfo netInfo = cm.getActiveNetworkInfo(); 
       if (netInfo != null && netInfo.isConnectedOrConnecting()) { 
       //if it is connected to internet than start Another Activity. 
       startActivity(new Intent(ListViewExample.this, ClipOfDay.class)); 
       } else if (netInfo == null) { 
        AlertDialog alertDialog = new AlertDialog.Builder(ListViewExample.this).create(); 
        alertDialog.setTitle("Connection Problem"); 
        alertDialog.setMessage("You are not connected to Internet"); 
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() { 

         public void onClick(DialogInterface dialog, int which) { 
          return; 
         } 
        }); 
        alertDialog.show(); 
       } 

      } 
     }); 
     } 

但这不是working.if设备没有连接到互联网,比我想显示AlertDialog。否则会启动Activity。任何人都可以告诉我该怎么办?
谢谢。

回答

2

检查网络连接
检查连接

ConnectivityManager cMgr = (ConnectivityManager) con.getSystemService(Context.CONNECTIVITY_SERVICE); 
      NetworkInfo netInfo = cMgr.getActiveNetworkInfo(); 
      String status = netInfo.getState().toString(); 
      if (status.equals("CONNECTED")) { 
       //DO you work 
      } else { 
       Log.e("error", "No connection available "); 
      } 
0
  • 首先检查网络或无线网络连接,然后运行你的代码
  • 使用尝试,渔获量,在某些情况下发生异常,因为连接错误的,在catch块删除对话框。



这可以是这样的一种方法..............
希望它可以帮助.......

+0

你是对的,但我怎么能检查是什么?我是新来的机器人,所以我不知道如何检查互联网连接。感谢您的回复。 – Piyush 2010-11-22 06:08:53

+1

检查:HTTP://stackoverflow.com/questions/1560788/how-to-check-internet-access-on-android-inetaddress-never-timeouts,尽量响应由埃迪·发送 – viv 2010-11-22 06:12:50

1

使用这两种方法来检查连接的简单代码:

Context.getSystemService(Context.CONNECTIVITY_SERVICE).getNetworkInfo(ConnectivityManager.TYPE_MOBILE) 
Context.getSystemService(Context.CONNECTIVITY_SERVICE).getNetworkInfo(ConnectivityManager.TYPE_WIFI) 

然后解析返回的结果以知道连接是否可用。 如果它可用,那么只做事情并把对话框。

或者,您也可以弹出对话框了,做任何网络操作之前​​,检查是否与这些方法连接,如果连接不可用,隐藏/取消对话框并显示错误消息。 否则,请进行网络操作。 是的,总是有一个try-catch块。