问题描述
- 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,请教下,如何做?
解决方案
MainActivity.java:
package com.example.netlistener2;
import android.support.v7.app.ActionBarActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.......
答案就在这里:android网络监听
解决方案二:
直接在oncreate里写,
NetworkInfo networkInfo = utils.isNetWorkConnected(context);
试下这样写行不行。