android - 通知网络变化的 Activity - Android

标签 android design-patterns notifications observer-pattern android-networking

我有一个 Activity 需要在建立网络连接后执行操作。我尝试实现 Observer 模式,但在尝试将 Observer Activity 注册到主题时收到 NullPointerException。有什么想法吗?

网络状态

public class NetworkStatus implements NetworkStatusSubject, Runnable {

    List<NetworkObserver> observerList;
    Context context;
    public NetworkStatus(Context context) {
        this.context = context;
    }

    public static boolean isConnectedToInternet(Context context) {

        boolean haveConnectedWifi = false;
        boolean haveConnectedMobile = false;

        ConnectivityManager cm = (ConnectivityManager)context.getSystemService(context.CONNECTIVITY_SERVICE);
        NetworkInfo[] netInfo = cm.getAllNetworkInfo();
        for (NetworkInfo ni : netInfo) {
            if (ni.getTypeName().equalsIgnoreCase("WIFI"))
                if (ni.isConnected())
                    haveConnectedWifi = true;
            if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
                if (ni.isConnected())
                    haveConnectedMobile = true;
        }
        return haveConnectedWifi || haveConnectedMobile;
    }

    /**
     * Add observer to list
     */
    @Override
    public void addObserver(NetworkObserver o) {
        observerList.add(o);

    }

    /**
     * Remove Observer from list
     */
    @Override
    public void removeObserver(NetworkObserver o) {
        observerList.remove(o);
    }

    @Override
    public void notifyObservers() {
        for(NetworkObserver networkObserver :  observerList) {
            networkObserver.updateStatus();
        }
    }

    @Override
    public void run() {

        while(true) {
            Log.d("NetworkStatus", "Checking Network Status");
            if(isConnectedToInternet(context)){
                notifyObservers();
                Log.d("NetworkStatus", "Network Connection is established");
            }
            else {
                Log.d("NetworkStatus", "Not connected to network");
            }
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }
}

需要通知的 Activity

public class OfflineActivity extends Activity implements NetworkObserver {

    public GeoPoint ourLocationGeoPoint;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.offline_mode_layout);

        //Register for network status updates
        NetworkStatus networkStatus = new NetworkStatus(this);
        networkStatus.addObserver(new OfflineActivity());
        networkStatus.run();

        // Acquire a reference to the system Location Manager
        LocationManager locationManager = (LocationManager) this
                .getSystemService(Context.LOCATION_SERVICE);

        // Define a listener that responds to location updates
        LocationListener locationListener = new LocationListener() {

            public void onLocationChanged(Location location) {
                // Called when a new location is found by the network location
                // provider.
                /**
                 * Save Location to geopoint
                 */
                int lat = (int) (location.getLatitude() * 1E6);
                int lng = (int) (location.getLongitude() * 1E6);
                ourLocationGeoPoint = new GeoPoint(lat, lng);
            }

            public void onStatusChanged(String provider, int status,
                    Bundle extras) {
            }

            public void onProviderEnabled(String provider) {
            }

            public void onProviderDisabled(String provider) {
            }
        };
        for (String provider : locationManager.getAllProviders()) {
            // Register the listener with the Location Manager to receive
            // location updates
            locationManager.requestLocationUpdates(provider, 0, 0,
                    locationListener);
        }
    }
    @Override
    public void updateStatus() {

        Log.d("OfflineActivity", "Connection Established, Uploading Points!");

    }
}

最佳答案

observerList 被声明为实例变量但从未实例化。

实例化它,构造函数是一个很好的地方:

public NetworkStatus(Context context) {
        this.context = context;
        observerList = new List <NetworkObserver> ();
    }

关于android - 通知网络变化的 Activity - Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14634074/

相关文章:

android - PagerTabStrip 和 TabLayout 的区别

android - java.lang.UnsatisfiedLinkError : dalvik. system.PathClassLoader

java - Android Icon/Image设置模式多种选择

powershell - 如何在操作中心保留PowerShell通知

android - 收到推送通知时添加新通知(不替换以前的)

Android - 存储下次启动时保留和使用的游戏状态信息

java - 如何检查图像大小小于 100kb android

node.js - Node 中许多异步任务的设计模式

Android 应用程序编程和能源效率

actionscript-3 - Adobe Air (AS3) 可以直接使用 socket.io 吗?