baidu_35123975
baidu_35123975
2016-05-26 02:41

android 网络动态监听

这是Activity类:

public class MainActivity extends Activity {
private Utils utils;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = new Intent();
setContentView(R.layout.linearlayout_activity_main);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION );
utils = new Utils();
intent = registerReceiver(utils, intentFilter);

}

这是Utils类:

public class Utils extends BroadcastReceiver {

private NetworkInfo isNetWorkConnected(Context context){
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
    if(networkInfo!= null){
        return networkInfo;
    }
    return null; 
}

@Override
public void onReceive(Context context, Intent intent) {
    NetworkInfo networkInfo = this.isNetWorkConnected(context);
    if(networkInfo != null && networkInfo.isAvailable()){
        System.out.println("有网络");
    }
}

}

问:

我现在想在MainActivity里获取到动态监听网络的状态,也就是要获取networkInfo,请教下,如何做?

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

2条回答

为你推荐

换一换