通过广播监听网络状态

主要代码块(Activity):

public class ConnectionChangeReceiver extends
BroadcastReceiver   
{   
@Override  
public void onReceive( Context context, Intent intent )   
{   
ConnectivityManager connectivityManager = 
(ConnectivityManager) context.getSystemService
( Context.CONNECTIVITY_SERVICE );   
NetworkInfo activeNetInfo = connectivityManager.
getActiveNetworkInfo();   
NetworkInfo mobNetInfo = connectivityManager.getNetworkInfo
( ConnectivityManager.TYPE_MOBILE );   
if ( activeNetInfo != null )   
{   
Toast.makeText( context, "Active Network Type : " + 
activeNetInfo.getTypeName(), Toast.LENGTH_SHORT ).show();   
}   
if( mobNetInfo != null )   
{   
Toast.makeText( context, "Mobile Network Type : " + 
mobNetInfo.getTypeName(), Toast.LENGTH_SHORT ).show();   
}   
}   
}

android manifest.xml

  
< uses-permission android:name="android.permission.
ACCESS_NETWORK_STATE"/>   
< receiver android:name="com.receiver.ConnectionChangeReceiver"   
android:label="NetworkConnection">   
< intent-filter>   
< action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>   
< /intent-filter>   
< /receiver>


你可能感兴趣的:(有线/无线网络应用)