如何计算 android 应用程序中互联网连接变化的次数

How to count the number of times internet connectivity change in a android application

我能够检测应用程序是连接到 WiFi 还是移动网络network.But我无法记录互联网连接从 Wifi 切换到移动网络的次数,或者反之versa.To记录网络变化我是否需要检查它是否连接到 WiFi 或 mobile.Then 稍后我需要如何检查应用程序从 WiFi 连接到移动设备,反之亦然?

我想计算 android 应用程序中 Internet 连接发生变化的次数。

我写的代码片段是 { public void onReceive(final Context context, final Intent 意图) {

    final ConnectivityManager connMgr = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);

    final android.net.NetworkInfo wifi = connMgr .getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    final android.net.NetworkInfo mobile = connMgr .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

    SharedPreferences pref =this.getApplicationContext.getSharedPreferences("network_change_count", Context.MODE_PRIVATE);
    int count = pref.getInt("networkchange", 0);
    pref.edit().putInt("networkchange", ++count).apply();
       // return pref.getInt("networkchange", count);
    }

} }

我已经在清单文件中注册了接收器。 但是现在当我尝试调用获取共享首选项值时出现 nullPointerexception。

SharedPreferences pref =this.getApplicationContext.getSharedPreferences("network_change_count", Context.MODE_PRIVATE); int connectivitychange=pref.getInt("networkchange", 0);

我可以知道我在这段代码中犯了什么错误吗?

请多多指教:)

试试这个方法。

registerReceiver(networkBroadcastReceiver, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"));

一旦连接发生变化,您将在此处接到电话。

BroadcastReceiver networkBroadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

        count++;
    }
};