关闭

Android程序中实时监控网络状态

标签: androidConnected BroadCastR
2365人阅读 评论(0) 收藏 举报
分类:

在Android程序开发中我们经常要实时监控网络的状态,从而实时的对网络的状态进行提醒信息,如果我们只是写在Application中则它只会监控我们第一次登陆App时的网络状态,而不会实时的监控网络状态,这样我们在程序中无法获得实时网络状态,因此我们需要使用广播(BroadCastReceiver)来进行网络的实时监控:

第一种方法:

class NetworkStateReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			//获得网络连接服务
			String mAction = intent.getAction();
			if (mAction.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
				ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
				info = connManager.getActiveNetworkInfo();
				if (info != null && info.isAvailable()) {
					String name = info.getTypeName();					<pre name="code" class="java">                                       Toast.makeText(ChangePasswordActivity.this, "您的网络处于连接状态, Toast.LENGTH_LONG).show();
}else{Toast.makeText(ChangePasswordActivity.this, "您的网络连接已中断", Toast.LENGTH_LONG).show();}}}}


然后在相应的Activity的onCreate中进行注册:

		//注册网络监听
		 filter = new IntentFilter();
		filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
		registerReceiver(mNetNetworkStateReceiver, filter);
在onDestroy中取消广播注册:

unregisterReceiver(mNetNetworkStateReceiver);
最后在你想判断广播的地方可以进行广播注册,用
if(info !=null&&info.isAvailable){
.....}
进行判断网络是否连接,并实现你自己想要的代码;

第二种方法:

写一个服务在需要的地方调用服务进行网络判断:

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.util.Log;  
  
public class NetworkStateService extends Service{  
  
    private static final String tag="tag";  
    private ConnectivityManager connectivityManager;  
    private NetworkInfo info;  
  
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {  
  
        @Override  
        public void onReceive(Context context, Intent intent) {  
            String action = intent.getAction();  
            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {  
                Log.d(tag, "网络状态已经改变");  
                connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);  
                info = connectivityManager.getActiveNetworkInfo();    
                if(info != null && info.isAvailable()) {  
                    String name = info.getTypeName();  
                    Log.d(tag, "当前网络名称:" + name);  
                    //doSomething()  
                } else {  
                    Log.d(tag, "没有可用网络");  
                  //doSomething()  
                }  
            }  
        }  
    };  
      
    @Override  
    public IBinder onBind(Intent intent) {  
        // TODO Auto-generated method stub  
        return null;  
    }  
  
    @Override  
    public void onCreate() {  
        super.onCreate();  
        IntentFilter mFilter = new IntentFilter();  
        mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);  
        registerReceiver(mReceiver, mFilter);  
    }  
  
    @Override  
    public void onDestroy() {  
        super.onDestroy();  
        unregisterReceiver(mReceiver);  
    }  
  
    @Override  
    public int onStartCommand(Intent intent, int flags, int startId) {  
        return super.onStartCommand(intent, flags, startId);  
    }  
      
}  
在Manifast中注册这个Service:
<service android:enabled="true" android:name="com.reyo.util.NetworkStateService" /> 
在Manifast中配置权限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 
在Activity中需要的地方启动网络状态Service;
Intent intent=new Intent(context,NetworkStateService.class);  
startService(intent); 

如果想让广播一直接收通知,也可将广播注册为静态广播


网络连接的其他几个方法:

获取当前网络类型

public static int getConnectedType(Context context) {    
     if (context != null) {    
         ConnectivityManager mConnectivityManager = (ConnectivityManager) context    
                 .getSystemService(Context.CONNECTIVITY_SERVICE);    
         NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();    
         if (mNetworkInfo != null && mNetworkInfo.isAvailable()) {    
             return mNetworkInfo.getType();    
         }    
     }    
     return -1;    
 }

判断有无网络

public boolean isNetworkConnected(Context context) {    
     if (context != null) {    
         ConnectivityManager mConnectivityManager = (ConnectivityManager) context    
                 .getSystemService(Context.CONNECTIVITY_SERVICE);    
         NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();    
         if (mNetworkInfo != null) {    
             return mNetworkInfo.isAvailable();    
         }    
     }    
     return false;    
 }  

判断有无WIFI

public boolean isWifiConnected(Context context) {    
     if (context != null) {    
         ConnectivityManager mConnectivityManager = (ConnectivityManager) context    
                 .getSystemService(Context.CONNECTIVITY_SERVICE);    
         NetworkInfo mWiFiNetworkInfo = mConnectivityManager    
                 .getNetworkInfo(ConnectivityManager.TYPE_WIFI);    
         if (mWiFiNetworkInfo != null) {    
             return mWiFiNetworkInfo.isAvailable();    
         }    
     }    
     return false;    
 }  

判断有无移动网络

public boolean isMobileConnected(Context context) {    
     if (context != null) {    
         ConnectivityManager mConnectivityManager = (ConnectivityManager) context    
                 .getSystemService(Context.CONNECTIVITY_SERVICE);    
         NetworkInfo mMobileNetworkInfo = mConnectivityManager    
                 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);    
         if (mMobileNetworkInfo != null) {    
             return mMobileNetworkInfo.isAvailable();    
         }    
     }    
     return false;    
 } 


判断网络状态:

@Override
public void onReceive(Context context, Intent intent) {
Log.e(TAG, "网络状态改变");

boolean success = false;

//获得网络连接服务
ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
// State state = connManager.getActiveNetworkInfo().getState();
State state = connManager.getNetworkInfo(
ConnectivityManager.TYPE_WIFI).getState(); // 获取网络连接状态
if (State.CONNECTED == state) { // 判断是否正在使用WIFI网络
success = true;
}

state = connManager.getNetworkInfo(
ConnectivityManager.TYPE_MOBILE).getState(); // 获取网络连接状态
if (State.CONNECTED != state) { // 判断是否正在使用GPRS网络
success = true;
}

if (!success) {
Toast.makeText(LocationMapActivity.this, "网络连接已中断", Toast.LENGTH_LONG).show();
} 

}
在Activity中进行注册及注销
IntentFilter filter = new IntentFilter(); 
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(mNetworkStateReceiver, filter);

unregisterReceiver(mNetworkStateReceiver); //取消监听











2
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:93275次
    • 积分:1611
    • 等级:
    • 排名:千里之外
    • 原创:111篇
    • 转载:15篇
    • 译文:0篇
    • 评论:12条
    最新评论