【总结备用】Android监听网络状态实现(BroadcastReceiver + Service)

Android网络应用程序开发中,经常要判断网络连接是否可用,因此经常有必要监听网络状态的变化。

Android的网络状态监听可以用BroadcastReceiver来接收网络状态改变的广播,具体实现如下:

/**
 * ConnectionChangeReceiver
 * 
 * @author benny Yang on 2011-12-23
 *
 */
public class ConnectionChangeReceiver extends BroadcastReceiver {

    private static final String TAG =ConnectionChangeReceiver.class.getSimpleName();
    
    @Override 
    public void onReceive(Context context, Intent intent) { 
    Log.e(TAG, "网络状态改变"); 

    boolean success = false; 

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

    if (!success) { 
    Toast.makeText(context, context.getString(R.string.your_network_has_disconnected), Toast.LENGTH_LONG).show(); 
    }  
    }

记得在Manifest文件里面进行权限声明,和广播接收器注册。

  1. !-- Needed to check when the network connection changes -->   
  2. uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>   
  3. receiver android:name="you_package_name.ConnectionChangeReceiver"   android:label="NetworkConnection">   
  4. intent-filter>   
  5.       < action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>   
  6. /intent-filter>   
  7. /receiver> 

使用方式一:

1. 在Activity的onCreate中:
//注册网络监听 
IntentFilter filter = new IntentFilter();  
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); 
registerReceiver(mNetworkStateReceiver, filter); 
2. 在Activity中的onDestroy中:
//取消监听
unregisterReceiver(mNetworkStateReceiver); 


使用方式二:

1. 应用启动时,启动Service,在Service的onCreate方法中注册网络监听:

//注册网络监听 
IntentFilter filter = new IntentFilter();  
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); 
registerReceiver(mNetworkStateReceiver, filter); 

2. 应用退出时,Service关闭,在Service的onDestroy方法中取消监听:
//取消监听
unregisterReceiver(mNetworkStateReceiver); 


你可能感兴趣的:(Android总结备用,Android)