如何判斷軟體程式是否連網 連網狀態提示資訊Android實現_Android

來源:互聯網
上載者:User

在項目中,經常需要判斷是否有網路連接。最近學習了如何判斷軟體是否連網,如果沒有連網,彈出提示資訊,串連網路。

效果:

(1)連網情況下:

 

(2)不連網情況下:

(3)點擊“檢測設定”:

源碼下載:http://xiazai.jb51.net/201605/yuanma/MyApplication(jb51.net).rar

判斷我們的軟體是否連網,看代碼吧:

  /**   * 檢測網路連接   *   * @param con   * @return   */  public boolean isNetworkAvailable(Context con) {    ConnectivityManager cm = (ConnectivityManager) con        .getSystemService(Context.CONNECTIVITY_SERVICE);    if (cm == null)      return false;    NetworkInfo netinfo = cm.getActiveNetworkInfo();    if (netinfo == null) {      return false;    }    if (netinfo.isConnected()) {      return true;    }    return false;  }

如果沒有連網,彈出提示框,提示設定網路連接:

  /**   * 提示設定網路連接對話方塊   *   * @param context   */  public void showNetDialog(final Context context) {    mMaterialDialog = new MaterialDialog(context)    .setMessage("世界上最遙遠的距離就是沒網")    .setPositiveButton("檢查設定", new View.OnClickListener() {      @Override      public void onClick(View v) {        Intent intent = null;        try {        @SuppressWarnings("deprecation")        String sdkVersion = android.os.Build.VERSION.SDK;        if (Integer.valueOf(sdkVersion) > 10) {           intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);        } else {           intent = new Intent();           ComponentName comp = new  ComponentName("com.android.settings", "com.android.settings.WirelessSettings");           intent.setComponent(comp);           intent.setAction("android.intent.action.VIEW");        }           context.startActivity(intent);        } catch (Exception e) {           e.printStackTrace();        }           mMaterialDialog.dismiss();      }      }).setNegativeButton("取消", new View.OnClickListener() {        @Override        public void onClick(View v) {           mMaterialDialog.dismiss();      }    });    mMaterialDialog.show();  }

怎麼做判斷處理:

  /**   * 判斷是否連網   */  private void checkNet() {    if(!mCheckNetWork.isNetworkAvailable(getApplication())){      mCheckNetWork.showNetDialog(MainActivity.this);    }else {      Toast.makeText(MainActivity.this,      "有網路,哈哈",Toast.LENGTH_SHORT).show();    }  }

具體代碼如下:

MainActivity.java

package com.bzu.gxs.chectnetwork;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.Toast;public class MainActivity extends Activity implements View.OnClickListener{  private CheckNetWork mCheckNetWork =new CheckNetWork();  private Button btn_check;  @Override  protected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    init();  }  /**   * 點擊事件   *   * @param view   */  @Override  public void onClick(View view) {    switch (view.getId()){      case R.id.btn_check:        checkNet();    }  }  /**   * 判斷是否連網   */  private void checkNet() {    if(!mCheckNetWork.isNetworkAvailable(getApplication())){      mCheckNetWork.showNetDialog(MainActivity.this);    }else {      Toast.makeText(MainActivity.this,      "有網路,哈哈",Toast.LENGTH_SHORT).show();    }  }  /**   * 初始化   */  private void init() {    btn_check = (Button) findViewById(R.id.btn_check);    btn_check.setOnClickListener(this);  }}

CheckNetWork.java

package com.bzu.gxs.chectnetwork;import android.content.ComponentName;import android.content.Context;import android.content.Intent;import android.media.browse.MediaBrowser;import android.net.ConnectivityManager;import android.net.NetworkInfo;import android.os.Build;import android.view.View;import me.drakeet.materialdialog.MaterialDialog;/** * 網路檢測 * Created by GXS on 2016/5/13. */public class CheckNetWork {  private MaterialDialog mMaterialDialog;  /**   * 檢測網路連接   *   * @param con   * @return   */  public boolean isNetworkAvailable(Context con) {    ConnectivityManager cm = (ConnectivityManager) con        .getSystemService(Context.CONNECTIVITY_SERVICE);    if (cm == null)      return false;    NetworkInfo netinfo = cm.getActiveNetworkInfo();    if (netinfo == null) {      return false;    }    if (netinfo.isConnected()) {      return true;    }    return false;  }  /**   * 提示設定網路連接對話方塊   *   * @param context   */  public void showNetDialog(final Context context) {    mMaterialDialog = new MaterialDialog(context)    .setMessage("世界上最遙遠的距離就是沒網")    .setPositiveButton("檢查設定", new View.OnClickListener() {      @Override      public void onClick(View v) {        Intent intent = null;        try {        @SuppressWarnings("deprecation")        String sdkVersion = android.os.Build.VERSION.SDK;        if (Integer.valueOf(sdkVersion) > 10) {           intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);        } else {           intent = new Intent();           ComponentName comp = new               ComponentName("com.android.settings",               "com.android.settings.WirelessSettings");           intent.setComponent(comp);           intent.setAction("android.intent.action.VIEW");        }           context.startActivity(intent);        } catch (Exception e) {           e.printStackTrace();        }           mMaterialDialog.dismiss();      }      }).setNegativeButton("取消", new View.OnClickListener() {        @Override        public void onClick(View v) {           mMaterialDialog.dismiss();      }    });    mMaterialDialog.show();  }}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  xmlns:tools="http://schemas.android.com/tools"  android:layout_width="match_parent"  android:layout_height="match_parent"  android:paddingBottom="@dimen/activity_vertical_margin"  android:paddingLeft="@dimen/activity_horizontal_margin"  android:paddingRight="@dimen/activity_horizontal_margin"  android:paddingTop="@dimen/activity_vertical_margin"  tools:context="com.bzu.gxs.chectnetwork.MainActivity">  <Button    android:id="@+id/btn_check"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:text="測試"/></RelativeLayout>

注意:需要在資訊清單檔AndroidManifest.xml中加入

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

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.