当启用 Wifi 连接或移动数据连接时,我在我的应用程序中通知。但我的 onReciever 方法多次调用并且它给出“找不到源异常”。但在我的 logcat 中它没有打印任何异常。只有调试时间时我发现了那个异常.在调试时 onReciever 方法结束 tat 调试器返回“未找到源异常”。
@Override
public void onReceive(final Context context, final Intent intent) {
System.out.println("Network change reciever started");
String status = NetworkUtil.getConnectivityStatusString(context);
Toast.makeText(context, status, Toast.LENGTH_LONG).show();
}
当 onReciever 调用我的 syso 在 logcat 和 toas cams 中打印 4 次 2,3 次时。为什么?
我的代码有什么问题?
显现 :
<receiver
android:name="com.electrical.coc.nz.automaticserversync.NetworkChangeReceiver"
android:enabled="true"
android:label="NetworkChangeReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
</intent-filter>
</receiver>
更新1#
public class NetworkUtil {
public static int TYPE_WIFI = 1;
public static int TYPE_MOBILE = 2;
public static int TYPE_NOT_CONNECTED = 0;
public static int getConnectivityStatus(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (null != activeNetwork) {
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
return TYPE_WIFI;
if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
return TYPE_MOBILE;
}
return TYPE_NOT_CONNECTED;
}
public static String getConnectivityStatusString(Context context) {
int conn = NetworkUtil.getConnectivityStatus(context);
String status = null;
if (conn == NetworkUtil.TYPE_WIFI) {
status = "Internet connection enabled";
} else if (conn == NetworkUtil.TYPE_MOBILE) {
status = "Internet connection enabled";
} else if (conn == NetworkUtil.TYPE_NOT_CONNECTED) {
status = "Internet connection disabled";
}
return status;
}
}