簡體   English   中英

Android中的互聯網連接

[英]Internet Connection in Android

我正在研究使用Internet的應用程序。

  • 它包含從URL進行XML解析。
  • 在解析時間時顯示進度對話框。
  • 解析完成后,停止對話框。
  • 在ListView中設置TEXT(Data)。

我的問題是,當設備連接到互聯網時,我的Apps可以正常工作,但是當設備未連接到互聯網時,“進度對話框”將無限期運行。

如果設備未連接到互聯網或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();
                }

            }
        });
       }

但這不起作用。如果設備未連接到互聯網,則我想顯示AlertDialog。 否則它將啟動Activity。 誰能告訴我該怎么辦?
謝謝。

檢查網絡連接
用於檢查連接的簡單代碼

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

使用以下兩種方法來檢查連接性:

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

然后解析返回的結果以了解連接是否可用。 如果可用,則僅執行操作並放入對話框。

或者,您也可以彈出對話框,在執行任何網絡操作之前​​,請檢查這些方法的連接性,如果連接不可用,請隱藏/取消對話框並顯示錯誤消息。 否則,請執行網絡操作。 是的,始終有一個try-catch塊。

  • 首先檢查是否已連接互聯網或wifi,然后運行代碼
  • 使用try,catch,以防由於連接錯誤而導致某些異常,請刪除catch塊中的對話框。



這可以是執行此操作的一種方法。
希望能幫助到你.......

暫無
暫無

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

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