Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android 網絡連接判斷並進行相關處理

Android 網絡連接判斷並進行相關處理

編輯:關於Android編程

獲取網絡信息需要在AndroidManifest.xml文件中加入相應的權限。

 

1)判斷是否有網絡連接,沒有則進入網絡設置

/**
*檢測網絡是否連接
*@return
*/
privatebooleancheckNetworkState(){
booleanflag=false;
//得到網絡連接信息
manager=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
//去進行判斷網絡是否連接
if(manager.getActiveNetworkInfo()!=null){
flag=manager.getActiveNetworkInfo().isAvailable();
}
if(!flag){
setNetwork();
}else{
isNetworkAvailable();
}


returnflag;
}



/**
*網絡未連接時,調用設置方法
*/
privatevoidsetNetwork(){
Toast.makeText(this,"wifiisclosed!",Toast.LENGTH_SHORT).show();


AlertDialog.Builderbuilder=newAlertDialog.Builder(this);
builder.setIcon(R.drawable.ic_launcher);
builder.setTitle("網絡提示信息");
builder.setMessage("網絡不可用,如果繼續,請先設置網絡!");
builder.setPositiveButton("設置",newOnClickListener(){
@Override
publicvoidonClick(DialogInterfacedialog,intwhich){
Intentintent=null;
/**
*判斷手機系統的版本!如果API大於10就是3.0+
*因為3.0以上的版本的設置和3.0以下的設置不一樣,調用的方法不同
*/
if(android.os.Build.VERSION.SDK_INT>10){
intent=newIntent(android.provider.Settings.ACTION_WIFI_SETTINGS);
}else{
intent=newIntent();
ComponentNamecomponent=newComponentName(
"com.android.settings",
"com.android.settings.WirelessSettings");
intent.setComponent(component);
intent.setAction("android.intent.action.VIEW");
}
startActivity(intent);
}
});


builder.setNegativeButton("取消",newOnClickListener(){
@Override
publicvoidonClick(DialogInterfacedialog,intwhich){


}
});
builder.create();
builder.show();
}


/**
*網絡已經連接,然後去判斷是wifi連接還是GPRS連接
*設置一些自己的邏輯調用
*/
privatevoidisNetworkAvailable(){


Stategprs=manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
Statewifi=manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
if(gprs==State.CONNECTED||gprs==State.CONNECTING){
Toast.makeText(this,"wifiisopen!gprs",Toast.LENGTH_SHORT).show();
}
//判斷為wifi狀態下才加載廣告,如果是GPRS手機網絡則不加載!
if(wifi==State.CONNECTED||wifi==State.CONNECTING){
Toast.makeText(this,"wifiisopen!wifi",Toast.LENGTH_SHORT).show();
loadAdmob();
}

}

/**
*在wifi狀態下加載admob廣告
*/
privatevoidloadAdmob(){
ll=(LinearLayout)findViewById(R.id.load_ads);
ll.removeAllViews();
adsView=newAdView(this,AdSize.BANNER,"a15194a1ac9505d");
ll.addView(adsView);


adsView.loadAd(newAdRequest());
}
 

2)判斷WIFI網絡是否可用

 

 1 public boolean isWifiConnected(Context context) {  
 2     if (context != null) {  
 3         ConnectivityManager mConnectivityManager = (ConnectivityManager) context  
 4                 .getSystemService(Context.CONNECTIVITY_SERVICE);  
 5         NetworkInfo mWiFiNetworkInfo = mConnectivityManager  
 6                 .getNetworkInfo(ConnectivityManager.TYPE_WIFI);  
 7         if (mWiFiNetworkInfo != null) {  
 8             return mWiFiNetworkInfo.isAvailable();  
 9         }  
10     }  
11     return false;  
12 }  

 

3)判斷MOBILE網絡是否可用

 

 1 public boolean isMobileConnected(Context context) {  
 2     if (context != null) {  
 3         ConnectivityManager mConnectivityManager = (ConnectivityManager) context  
 4                 .getSystemService(Context.CONNECTIVITY_SERVICE);  
 5         NetworkInfo mMobileNetworkInfo = mConnectivityManager  
 6                 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);  
 7         if (mMobileNetworkInfo != null) {  
 8             return mMobileNetworkInfo.isAvailable();  
 9         }  
10     }  
11     return false;  
12 }  

4)獲取當前網絡連接的類型信息

 

 1 public static int getConnectedType(Context context) {  
 2     if (context != null) {  
 3         ConnectivityManager mConnectivityManager = (ConnectivityManager) context  
 4                 .getSystemService(Context.CONNECTIVITY_SERVICE);  
 5         NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();  
 6         if (mNetworkInfo != null && mNetworkInfo.isAvailable()) {  
 7             return mNetworkInfo.getType();  
 8         }  
 9     }  
10     return -1;  
11 }  

 

在開發android應用時,涉及到要進行網絡訪問,時常需要進行網絡狀態的檢查,以提供給用戶必要的提醒。一般可以通過ConnectivityManager來完成該工作。

ConnectivityManager有四個主要任務:

1、監聽手機網絡狀態(包括GPRS,WIFI,UMTS等)

2、手機狀態發生改變時,發送廣播

3、當一個網絡連接失敗時進行故障切換

4、為應用程序提供可以獲取可用網絡的高精度和粗糙的狀態

當我們要在程序中監聽網絡狀態時,只要一下幾個步驟即可:

1、定義一個Receiver重載其中的onReceive函數,在其中完成所需要的功能,如根據WIFI和GPRS是否斷開來改變空間的外觀

 

 

connectionReceiver = new BroadcastReceiver() {
   
   @Override
   public void onReceive(Context context, Intent intent) {
    ConnectivityManager connectMgr = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
    NetworkInfo mobNetInfo = connectMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    NetworkInfo wifiNetInfo = connectMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    if (!mobNetInfo.isConnected() && !wifiNetInfo.isConnected()) {
     Log.i(TAG, "unconnect");
     // unconnect network
     }else {

    // connect network
     }
   }
  };

 

 

2、在適當的地方注冊Receiver,可以在程序中注冊,在onCreate中調用如下函數即可:

 

IntentFilter intentFilter = new IntentFilter();
  intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
  registerReceiver(connectionReceiver, intentFilter);

 

 

3、在適當時取消注冊Receiver,可以在程序中取消,在onDestroye中調用如下函數即可:

 

if (connectionReceiver != null) {
   unregisterReceiver(connectionReceiver);
  }

很多朋友在android開發中,都會遇到手機網絡類型判斷,因為就目前的android平台手機來說:可能會存在4中狀態

1.無網絡(這種狀態可能是因為手機停機,網絡沒有開啟,信號不好等原因)

2.使用WIFI上網

3.CMWAP(中國移動代理)

4.CMNET上網

這四種狀態,如果沒有網絡,肯定是無法請求Internet了,如果是wap就需要為手機添加中國移動代理,關於為手機添加中國移動的代理,請到

/kf/201111/112100.html 這裡寫有關於添加中國移動代理的例子!

下面是網絡判斷的方法:

 1 /**
 2 
 3      * @author sky
 4 
 5      * Email [email protected]
 6 
 7      * QQ:840950105
 8 
 9      * 獲取當前的網絡狀態  -1:沒有網絡  1:WIFI網絡2:wap網絡3:net網絡
10 
11      * @param context
12 
13      * @return
14 
15      */ 
16 
17     public static int getAPNType(Context context){ 
18 
19         int netType = -1;  
20 
21         ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 
22 
23         NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); 
24 
25          
26 
27         if(networkInfo==null){ 
28 
29             return netType; 
30 
31         } 
32 
33         int nType = networkInfo.getType(); 
34 
35         if(nType==ConnectivityManager.TYPE_MOBILE){ 
36 
37             Log.e("networkInfo.getExtraInfo()", "networkInfo.getExtraInfo() is "+networkInfo.getExtraInfo()); 
38 
39             if(networkInfo.getExtraInfo().toLowerCase().equals("cmnet")){ 
40 
41                 netType = CMNET; 
42 
43             } 
44 
45             else{ 
46 
47                 netType = CMWAP; 
48 
49             } 
50 
51         } 
52 
53         else if(nType==ConnectivityManager.TYPE_WIFI){ 
54 
55             netType = WIFI; 
56 
57         } 
58 
59         return netType; 
60 
61     } 

因為獲取的是服務對象,所以這個網絡狀態都是時時刷新的,所以我們只需要得到網絡狀態就可以了!

 

當然也可以用啟動service來判斷網絡狀態,將BroadcastReceiver 加入service即可。下面是具體實現:

 

首先新建個service

package servicetest.zkk.com.myapplication;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.IBinder;
import android.text.TextUtils;


/**
 * 網絡發生變化時的service
 */
public class MyNetworkStateService extends Service {

    private ConnectivityManager connectivityManager;
    private NetworkInfo info;
    public static final String ACTION_NO_CONNECTION = "ACTION_NO_CONNECTION"; //網絡沒有連接
    public static final String ACTION_CONNECTIONED = "ACTION_CONNECTIONED";   //網絡連接

    private BroadcastReceiver broadcastReceiver=new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
              //當網絡發生變化時
            String action = intent.getAction();
            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
                info = connectivityManager.getActiveNetworkInfo();
                if(info != null && info.isAvailable()) {
                    String name = info.getTypeName();
                    if(TextUtils.equals("WIFI", name)) {
                    } else {
                    }
                    sendNetworkStateBroadCast(ACTION_CONNECTIONED);
                } else {
                    sendNetworkStateBroadCast(ACTION_NO_CONNECTION);
                }
            }
        }
    };

    /**
     * 發送本地廣播通知網絡狀態
     * @param action
     */
    private void sendNetworkStateBroadCast(String action) {
        if (TextUtils.equals(ACTION_CONNECTIONED, action) ||
                TextUtils.equals(ACTION_NO_CONNECTION, action)) {
            Intent intent = new Intent(action);
            LocalBroadcastUtils.send(getApplication(), intent);
        }
    }


    public MyNetworkStateService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        IntentFilter intentFilter=new IntentFilter();
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(broadcastReceiver,intentFilter);
    }

    @Override
    public void onDestroy() {
        unregisterReceiver(broadcastReceiver);
        super.onDestroy();
    }
}

再 AndroidManifest.xml中注冊這個service

<service
            android:name=".MyNetworkStateService"
            android:enabled="true"
            android:exported="true" />

注意在service中得代碼

 @Override
    public void onCreate() {
        super.onCreate();
        IntentFilter intentFilter=new IntentFilter();
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(broadcastReceiver,intentFilter);
    }

意思就是說在service啟動的時候注冊了一個廣播,ConnectivityManager.CONNECTIVITY_ACTION這個就是系統在網絡發生變化時候得action,比如wifi關閉、wifi重新連接等。

利用LocalBroadcastManager管理廣播

package servicetest.zkk.com.myapplication;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;

/**
 * 利用LocalBroadcastManager管理廣播
 */
public class LocalBroadcastUtils {
    /**
     * 注冊廣播
     *
     * @param context
     * @param broadcastReceiver
     * @param intentFilter
     */
    public static void register(Context context, BroadcastReceiver broadcastReceiver, IntentFilter intentFilter) {
        LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(context);
        localBroadcastManager.registerReceiver(broadcastReceiver, intentFilter);
    }

    /**
     * 注銷廣播
     *
     * @param context
     * @param broadcastReceiver
     */
    public static void unregister(Context context, BroadcastReceiver broadcastReceiver) {
        LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(context);
        localBroadcastManager.unregisterReceiver(broadcastReceiver);
    }

    /**
     * 發送廣播
     *
     * @param context
     * @param intent
     */
    public static void send(Context context, Intent intent) {
        LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(context);
        localBroadcastManager.sendBroadcast(intent);
    }
}

``

這是一個管理類,對廣播進行管理。

下面就來看看在activity中如何操作`

private void registerBroadcast() {
    mNetworkBroadcastReceiverHelper = new NetworkBroadcastReceiverHelper(ctx,
            new NetworkBroadcastReceiverHelper.OnNetworkStateChangedListener(){
                @Override
                public void onConnected() {
                    //連接時的事件
                }
                @Override
                public void onDisConnected() {
                    //沒有連接時的事件
                }
            });
    mNetworkBroadcastReceiverHelper.register();
}

/**
 * 注銷廣播
 */
private void unregisterBroadcast() {
    mNetworkBroadcastReceiverHelper.unregister();
}


這其實就是一個網絡狀態廣播接受者幫助類,在其中定義了接口,這樣在activity中就有了回調。繼續在actiivty中操作。


@Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       ctx=this;
       setContentView(R.layout.activity_main);
       mViewNoNetwork=(View)findViewById(R.id.include_home_fragment_network);
       registerBroadcast();
       Intent intents=new Intent(this, MyNetworkStateService.class);
       startService(intents);
   }

@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    Intent intents=new Intent(this, MyNetworkStateService.class);
    stopService(intents);
}

/**
     *注冊廣播
     */
    private void registerBroadcast() {
        mNetworkBroadcastReceiverHelper = new NetworkBroadcastReceiverHelper(ctx,
                new NetworkBroadcastReceiverHelper.OnNetworkStateChangedListener(){
                    @Override
                    public void onConnected() {
                        //連接時的事件
                        mViewNoNetwork.setVisibility(View.GONE);
                    }
                    @Override
                    public void onDisConnected() {
                        //沒有連接時的事件
                        mViewNoNetwork.setVisibility(View.VISIBLE);
                    }
                });
        mNetworkBroadcastReceiverHelper.register();
    }

“`
在onConnected和onDisConnected方法中就可以進行處理了,分別為網絡連接成功、連接失敗。

\

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved