Android 檢測網路是否串連,android檢測

來源:互聯網
上載者:User

Android 檢測網路是否串連,android檢測

許可權:

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

代碼如下:

package com.example.nettest;

import android.net.ConnectivityManager;
import android.net.NetworkInfo.State;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends Activity {


private ConnectivityManager manager;
private TextView tv;
StringBuffer sb = new StringBuffer(256);


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);


tv = (TextView) findViewById(R.id.textView1);
checkNetworkState();
}


/**
* 檢測網路是否串連
* 
* @return
*/
private boolean checkNetworkState() {
boolean flag = false;
// 得到網路連接資訊
manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
// 去進行判斷網路是否串連
if (manager.getActiveNetworkInfo() != null) {
flag = manager.getActiveNetworkInfo().isAvailable();
}
if (!flag) {
setNetwork();
} else {
isNetworkAvailable();
}
tv.setText(sb.toString());
return flag;
}


/**
* 網路未串連時,調用設定方法
*/
private void setNetwork() {
Toast.makeText(this, "wifi is closed!", Toast.LENGTH_SHORT).show();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setIcon(R.drawable.ic_launcher);
builder.setTitle("網路提示資訊");
builder.setMessage("網路不可用,如果繼續,請先設定網路!");
builder.setPositiveButton("設定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = null;
/**
* 判斷手機系統的版本!如果API大於10 就是3.0+ 因為3.0以上的版本的設定和3.0以下的設定不一樣,調用的方法不同
*/
if (android.os.Build.VERSION.SDK_INT > 10) {
intent = new Intent(
android.provider.Settings.ACTION_SETTINGS);
} else {
intent = new Intent();
ComponentName component = new ComponentName(
"com.android.settings",
"com.android.settings.WirelessSettings");
intent.setComponent(component);
intent.setAction("android.intent.action.VIEW");
}
startActivity(intent);
}
});


builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.create();
builder.show();
}


/**
* 網路已經串連,然後去判斷是wifi串連還是GPRS串連 設定一些自己的邏輯調用
*/
private void isNetworkAvailable() {


State gprs = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
.getState();
State wifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
.getState();
if (gprs == State.CONNECTED || gprs == State.CONNECTING) {
Toast.makeText(this, "gprs is open! ", Toast.LENGTH_SHORT).show();
sb.append("\ngprs is open! ");
} else {
sb.append("\ngprs is closed! ");
}


// 判斷為wifi狀態下才載入廣告,如果是GPRS行動電話通訊則不載入!
if (wifi == State.CONNECTED || wifi == State.CONNECTING) {
Toast.makeText(this, "wifi is open! ", Toast.LENGTH_SHORT).show();
loadAdmob();
sb.append("\nwifi is open! ");
} else {
sb.append("\nwifi is closed! ");
}


}


/**
* 在wifi狀態下 載入admob廣告
*/
private void loadAdmob() {
Toast.makeText(getApplicationContext(), "ad is loding..", 1).show();
sb.append("\nad is loding...");
}
}


Android系列之怎判斷網路連結狀態

  下面咱們討論下Android手機判斷網路連結狀態的技術實現吧
  目前Android作業系統的手機大部分支援WIFI,
GSM,3G網路通訊
,但是每次連結到網路時只能選擇一種連結方式,
  比如電訊廠商定製的,還必須要求特定的網路環境(CMWAP,CTWAP等)如果要切換網路還需要先關閉現有的網路,
  然後再啟動新的網路,這個轉換過程還需要一定的時間,
  可能程式這時還需要知道心的網路是否連結成功後自動登入到新的網路伺服器中,
  也許用一個線程去監聽網路狀態是否連結成功;
  我們可以用另外一種方法,PhoneStateListener
  沒錯,你沒看錯,就是用PhoneStateListener。
  很多應用PhoneStateListener都是監聽來電去電,PhoneStateListener還可以監聽網路斷開、
  正在串連和串連成功。
 1 final TelephonyManager mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); 
 2 mTelephonyMgr.listen(new PhoneStateListener(){
 3           
 4   @Override
 5   public void onDataConnectionStateChanged(int state) {
 6     switch(state){
 7       case TelephonyManager.DATA_DISCONNECTED://網路斷開
 8          break;
 9       case TelephonyManager.DATA_CONNECTING://網路正在串連
10          break;
11       case TelephonyManager.DATA_CONNECTED://網路連接上
12          break;
13     }14   }15             16   }  PhoneStateListener.LISTEN_DATA_CONNECTION_STATE); 
  我們只要重載onDataConnectionStateChanged方法,根據state判斷做相應的處理。
 
android 怎判斷網路是否串連

public static boolean networkStatusOK(Context mContext) {
boolean netStatus = false;
try{
ConnectivityManager connectManager = (ConnectivityManager) Context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectManager.getActiveNetworkInfo();
if (activeNetworkInfo != null) {
if (activeNetworkInfo.isAvailable() && activeNetworkInfo.isConnected()) {
netStatus = true;
}
}
} catch (Exception e) {e.printStackTrace();}
return netStatus;
}
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.