├── .gitignore ├── .idea ├── compiler.xml └── vcs.xml ├── NetMonitor2.gif ├── README.md ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── deng │ │ └── netmonitor │ │ └── ExampleInstrumentedTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ │ │ └── deng │ │ │ └── netmonitor │ │ │ ├── App.java │ │ │ ├── activity │ │ │ └── MainActivity.java │ │ │ └── base │ │ │ └── BaseActivity.java │ └── res │ │ ├── layout │ │ └── activity_main.xml │ │ ├── mipmap-hdpi │ │ └── ic_launcher.png │ │ ├── mipmap-mdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xhdpi │ │ ├── ic_launcher.png │ │ └── ic_net_state.png │ │ ├── mipmap-xxhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxxhdpi │ │ └── ic_launcher.png │ │ ├── values-w820dp │ │ └── dimens.xml │ │ └── values │ │ ├── colors.xml │ │ ├── dimens.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ └── java │ └── com │ └── deng │ └── netmonitor │ └── ExampleUnitTest.java ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── netmonitorlibrary ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── caption │ │ └── netmonitorlibrary │ │ └── ExampleInstrumentedTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ │ │ └── caption │ │ │ └── netmonitorlibrary │ │ │ └── netStateLib │ │ │ ├── NetChangeObserver.java │ │ │ ├── NetStateReceiver.java │ │ │ └── NetUtils.java │ └── res │ │ └── values │ │ └── strings.xml │ └── test │ └── java │ └── com │ └── caption │ └── netmonitorlibrary │ └── ExampleUnitTest.java ├── settings.gradle └── tea.yaml /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/workspace.xml 5 | /.idea/libraries 6 | .DS_Store 7 | /build 8 | /captures 9 | .externalNativeBuild 10 | -------------------------------------------------------------------------------- /.idea/compiler.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /NetMonitor2.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GHdeng/NetMonitor/93823a73bda12fb13f81b369db71568f23d112bd/NetMonitor2.gif -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # NetMonitor 2 | 3 | # 使用广播监听网络变化 4 | 5 | ###需求确认 6 | 7 | * 监听当前网络的状态和类型 8 | * 类似京东客户端,当网络发生变化时相应更新UI界面 9 | 10 | ![image](https://raw.githubusercontent.com/GHdeng/NetMonitor/master/NetMonitor2.gif) 11 | 12 | github地址:https://github.com/GHdeng/NetMonitor 13 | 14 | ###制作流程 15 | 1. 使用广播监听当前网络的状态。 16 | 2. 配合Application周期注册监听,使得每个界面都继续监听 17 | 3. 抽出BaseActivity类实现回调 18 | 19 | #####1.继承BroadcastReceiver实现onReceive方法来判断当前网络是否连接,然后通过更新NetChangeObserver来实现回调。 20 | 加入权限 21 | ```java 22 | < uses-permission android:name="android.permission.INTERNET" /> 23 | < uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> 24 | < uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 25 | ``` 26 | ```java 27 | /** 28 | * 使用广播去监听网络 29 | * Created by deng on 16/9/13. 30 | */ 31 | public class NetStateReceiver extends BroadcastReceiver { 32 | 33 | public final static String CUSTOM_ANDROID_NET_CHANGE_ACTION = "com.zhanyun.api.netstatus.CONNECTIVITY_CHANGE"; 34 | private final static String ANDROID_NET_CHANGE_ACTION = "android.net.conn.CONNECTIVITY_CHANGE"; 35 | private final static String TAG = NetStateReceiver.class.getSimpleName(); 36 | 37 | private static boolean isNetAvailable = false; 38 | private static NetUtils.NetType mNetType; 39 | private static ArrayList mNetChangeObservers = new ArrayList(); 40 | private static BroadcastReceiver mBroadcastReceiver; 41 | 42 | private static BroadcastReceiver getReceiver() { 43 | if (null == mBroadcastReceiver) { 44 | synchronized (NetStateReceiver.class) { 45 | if (null == mBroadcastReceiver) { 46 | mBroadcastReceiver = new NetStateReceiver(); 47 | } 48 | } 49 | } 50 | return mBroadcastReceiver; 51 | } 52 | 53 | @Override 54 | public void onReceive(Context context, Intent intent) { 55 | mBroadcastReceiver = NetStateReceiver.this; 56 | if (intent.getAction().equalsIgnoreCase(ANDROID_NET_CHANGE_ACTION) || intent.getAction().equalsIgnoreCase(CUSTOM_ANDROID_NET_CHANGE_ACTION)) { 57 | if (!NetUtils.isNetworkAvailable(context)) { 58 | LogHelper.e(this.getClass(), "<--- network disconnected --->"); 59 | isNetAvailable = false; 60 | } else { 61 | LogHelper.e(this.getClass(), "<--- network connected --->"); 62 | isNetAvailable = true; 63 | mNetType = NetUtils.getAPNType(context); 64 | } 65 | notifyObserver(); 66 | } 67 | } 68 | 69 | /** 70 | * 注册 71 | * 72 | * @param mContext 73 | */ 74 | public static void registerNetworkStateReceiver(Context mContext) { 75 | IntentFilter filter = new IntentFilter(); 76 | filter.addAction(CUSTOM_ANDROID_NET_CHANGE_ACTION); 77 | filter.addAction(ANDROID_NET_CHANGE_ACTION); 78 | mContext.getApplicationContext().registerReceiver(getReceiver(), filter); 79 | } 80 | 81 | /** 82 | * 清除 83 | * 84 | * @param mContext 85 | */ 86 | public static void checkNetworkState(Context mContext) { 87 | Intent intent = new Intent(); 88 | intent.setAction(CUSTOM_ANDROID_NET_CHANGE_ACTION); 89 | mContext.sendBroadcast(intent); 90 | } 91 | 92 | /** 93 | * 反注册 94 | * 95 | * @param mContext 96 | */ 97 | public static void unRegisterNetworkStateReceiver(Context mContext) { 98 | if (mBroadcastReceiver != null) { 99 | try { 100 | mContext.getApplicationContext().unregisterReceiver(mBroadcastReceiver); 101 | } catch (Exception e) { 102 | 103 | } 104 | } 105 | 106 | } 107 | 108 | public static boolean isNetworkAvailable() { 109 | return isNetAvailable; 110 | } 111 | 112 | public static NetUtils.NetType getAPNType() { 113 | return mNetType; 114 | } 115 | 116 | private void notifyObserver() { 117 | if (!mNetChangeObservers.isEmpty()) { 118 | int size = mNetChangeObservers.size(); 119 | for (int i = 0; i < size; i++) { 120 | NetChangeObserver observer = mNetChangeObservers.get(i); 121 | if (observer != null) { 122 | if (isNetworkAvailable()) { 123 | observer.onNetConnected(mNetType); 124 | } else { 125 | observer.onNetDisConnect(); 126 | } 127 | } 128 | } 129 | } 130 | } 131 | 132 | /** 133 | * 添加网络监听 134 | * 135 | * @param observer 136 | */ 137 | public static void registerObserver(NetChangeObserver observer) { 138 | if (mNetChangeObservers == null) { 139 | mNetChangeObservers = new ArrayList(); 140 | } 141 | mNetChangeObservers.add(observer); 142 | } 143 | 144 | /** 145 | * 移除网络监听 146 | * 147 | * @param observer 148 | */ 149 | public static void removeRegisterObserver(NetChangeObserver observer) { 150 | if (mNetChangeObservers != null) { 151 | if (mNetChangeObservers.contains(observer)) { 152 | mNetChangeObservers.remove(observer); 153 | } 154 | } 155 | } 156 | } 157 | ``` 158 | 159 | #####2.回调接口 160 | ``` java 161 | /** 162 | * 网络改变观察者,观察网络改变后回调的方法 163 | * Created by deng on 16/9/13. 164 | */ 165 | public interface NetChangeObserver { 166 | 167 | /** 168 | * 网络连接回调 type为网络类型 169 | */ 170 | void onNetConnected(NetUtils.NetType type); 171 | 172 | /** 173 | * 没有网络 174 | */ 175 | void onNetDisConnect(); 176 | } 177 | ``` 178 | 179 | #####3.网络状态工具类 180 | ```java 181 | public class NetUtils { 182 | 183 | public static enum NetType { 184 | WIFI, CMNET, CMWAP, NONE 185 | } 186 | 187 | public static boolean isNetworkAvailable(Context context) { 188 | ConnectivityManager mgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 189 | NetworkInfo[] info = mgr.getAllNetworkInfo(); 190 | if (info != null) { 191 | for (int i = 0; i < info.length; i++) { 192 | if (info[i].getState() == NetworkInfo.State.CONNECTED) { 193 | return true; 194 | } 195 | } 196 | } 197 | return false; 198 | } 199 | 200 | public static boolean isNetworkConnected(Context context) { 201 | if (context != null) { 202 | ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 203 | NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo(); 204 | if (mNetworkInfo != null) { 205 | return mNetworkInfo.isAvailable(); 206 | } 207 | } 208 | return false; 209 | } 210 | 211 | public static boolean isWifiConnected(Context context) { 212 | if (context != null) { 213 | ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 214 | NetworkInfo mWiFiNetworkInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); 215 | if (mWiFiNetworkInfo != null) { 216 | return mWiFiNetworkInfo.isAvailable(); 217 | } 218 | } 219 | return false; 220 | } 221 | 222 | public static boolean isMobileConnected(Context context) { 223 | if (context != null) { 224 | ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 225 | NetworkInfo mMobileNetworkInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); 226 | if (mMobileNetworkInfo != null) { 227 | return mMobileNetworkInfo.isAvailable(); 228 | } 229 | } 230 | return false; 231 | } 232 | 233 | public static int getConnectedType(Context context) { 234 | if (context != null) { 235 | ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 236 | NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo(); 237 | if (mNetworkInfo != null && mNetworkInfo.isAvailable()) { 238 | return mNetworkInfo.getType(); 239 | } 240 | } 241 | return -1; 242 | } 243 | 244 | public static NetType getAPNType(Context context) { 245 | ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 246 | NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); 247 | if (networkInfo == null) { 248 | return NetType.NONE; 249 | } 250 | int nType = networkInfo.getType(); 251 | 252 | if (nType == ConnectivityManager.TYPE_MOBILE) { 253 | if (networkInfo.getExtraInfo().toLowerCase(Locale.getDefault()).equals("cmnet")) { 254 | return NetType.CMNET; 255 | } else { 256 | return NetType.CMWAP; 257 | } 258 | } else if (nType == ConnectivityManager.TYPE_WIFI) { 259 | return NetType.WIFI; 260 | } 261 | return NetType.NONE; 262 | } 263 | } 264 | ``` 265 | 266 | #####4.在Application中注册 267 | ```java 268 | @Override 269 | public void onCreate() { 270 | super.onCreate(); 271 | instance = this; 272 | 273 | /*开启网络广播监听*/ 274 | NetStateReceiver.registerNetworkStateReceiver(instance); 275 | } 276 | 277 | @Override 278 | public void onLowMemory() { 279 | if (instance != null) { 280 | NetStateReceiver.unRegisterNetworkStateReceiver(instance); 281 | android.os.Process.killProcess(android.os.Process.myPid()); 282 | exitApp(); 283 | } 284 | super.onLowMemory(); 285 | } 286 | ``` 287 | 288 | #####5.为了监听每一个Activity就抽取出来一个抽象类 289 | 290 | ```java 291 | /** 292 | * 网络观察者 293 | */ 294 | protected NetChangeObserver mNetChangeObserver = null; 295 | 296 | @Override 297 | protected void onCreate(Bundle savedInstanceState) { 298 | // 网络改变的一个回掉类 299 | mNetChangeObserver = new NetChangeObserver() { 300 | @Override 301 | public void onNetConnected(NetUtils.NetType type) { 302 | onNetworkConnected(type); 303 | } 304 | 305 | @Override 306 | public void onNetDisConnect() { 307 | onNetworkDisConnected(); 308 | } 309 | }; 310 | 311 | //开启广播去监听 网络 改变事件 312 | NetStateReceiver.registerObserver(mNetChangeObserver); 313 | } 314 | 315 | /** 316 | * 网络连接状态 317 | * 318 | * @param type 网络状态 319 | */ 320 | protected abstract void onNetworkConnected(NetUtils.NetType type); 321 | 322 | /** 323 | * 网络断开的时候调用 324 | */ 325 | protected abstract void onNetworkDisConnected(); 326 | 327 | @Override 328 | protected void onDestroy() { 329 | super.onDestroy(); 330 | unbinder.unbind(); 331 | NetStateReceiver.removeRegisterObserver(mNetChangeObserver); 332 | } 333 | ``` 334 | 335 | # Use 336 | ##### Maven 337 | ```java 338 | 339 | com.caption 340 | netmonitorlibrary 341 | 1.0.0 342 | pom 343 | 344 | ``` 345 | 346 | ##### Gradle 347 | ```java 348 | compile 'com.caption:netmonitorlibrary:1.0.0' 349 | ``` 350 | 351 | # License 352 | Copyright (c) 2016 GHdeng 353 | Licensed under the Apache License, Version 2.0 (the "License"); 354 | you may not use this file except in compliance with the License. 355 | You may obtain a copy of the License at 356 | 357 | http://www.apache.org/licenses/LICENSE-2.0 358 | 359 | Unless required by applicable law or agreed to in writing, software 360 | distributed under the License is distributed on an "AS IS" BASIS, 361 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 362 | See the License for the specific language governing permissions and 363 | limitations under the License. 364 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 24 5 | buildToolsVersion "24.0.2" 6 | defaultConfig { 7 | applicationId "com.deng.netmonitor" 8 | minSdkVersion 15 9 | targetSdkVersion 24 10 | versionCode 1 11 | versionName "1.0" 12 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 13 | } 14 | buildTypes { 15 | release { 16 | minifyEnabled false 17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 18 | } 19 | } 20 | } 21 | 22 | dependencies { 23 | compile fileTree(include: ['*.jar'], dir: 'libs') 24 | androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { 25 | exclude group: 'com.android.support', module: 'support-annotations' 26 | }) 27 | compile 'com.android.support:appcompat-v7:24.2.1' 28 | testCompile 'junit:junit:4.12' 29 | compile project(':netmonitorlibrary') 30 | } 31 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /Users/deng/Library/Android/sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /app/src/androidTest/java/com/deng/netmonitor/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package com.deng.netmonitor; 2 | 3 | import android.content.Context; 4 | import android.support.test.InstrumentationRegistry; 5 | import android.support.test.runner.AndroidJUnit4; 6 | 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | 10 | import static org.junit.Assert.*; 11 | 12 | /** 13 | * Instrumentation test, which will execute on an Android device. 14 | * 15 | * @see Testing documentation 16 | */ 17 | @RunWith(AndroidJUnit4.class) 18 | public class ExampleInstrumentedTest { 19 | @Test 20 | public void useAppContext() throws Exception { 21 | // Context of the app under test. 22 | Context appContext = InstrumentationRegistry.getTargetContext(); 23 | 24 | assertEquals("com.deng.netmonitor", appContext.getPackageName()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /app/src/main/java/com/deng/netmonitor/App.java: -------------------------------------------------------------------------------- 1 | package com.deng.netmonitor; 2 | 3 | import android.app.Application; 4 | 5 | import com.caption.netmonitorlibrary.netStateLib.NetStateReceiver; 6 | 7 | /** 8 | * Created by deng on 2016/9/30. 9 | */ 10 | 11 | public class App extends Application { 12 | @Override 13 | public void onCreate() { 14 | super.onCreate(); 15 | //动态注册网络变化广播 16 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { 17 | //实例化IntentFilter对象 18 | IntentFilter filter = new IntentFilter(); 19 | filter.addAction("android.net.conn.CONNECTIVITY_CHANGE"); 20 | NetConnectionReceiver netBroadcastReceiver = new NetConnectionReceiver(); 21 | //注册广播接收 22 | registerReceiver(netBroadcastReceiver, filter); 23 | } 24 | /*开启网络广播监听*/ 25 | NetStateReceiver.registerNetworkStateReceiver(this); 26 | } 27 | 28 | @Override 29 | public void onLowMemory() { 30 | super.onLowMemory(); 31 | NetStateReceiver.unRegisterNetworkStateReceiver(this); 32 | android.os.Process.killProcess(android.os.Process.myPid()); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /app/src/main/java/com/deng/netmonitor/activity/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.deng.netmonitor.activity; 2 | 3 | import android.os.Bundle; 4 | import android.view.View; 5 | import android.widget.RelativeLayout; 6 | import android.widget.TextView; 7 | 8 | import com.deng.netmonitor.R; 9 | import com.deng.netmonitor.base.BaseActivity; 10 | import com.caption.netmonitorlibrary.netStateLib.NetUtils; 11 | 12 | public class MainActivity extends BaseActivity { 13 | 14 | private TextView mTvState; 15 | private RelativeLayout mRlContent; 16 | 17 | @Override 18 | protected void onCreate(Bundle savedInstanceState) { 19 | super.onCreate(savedInstanceState); 20 | setContentView(R.layout.activity_main); 21 | 22 | mTvState = (TextView) findViewById(R.id.tv_state); 23 | mRlContent = (RelativeLayout) findViewById(R.id.rl_state_content); 24 | } 25 | 26 | @Override 27 | protected void onNetworkConnected(NetUtils.NetType type) { 28 | mTvState.setText("网络连接正常\n" + type.name()); 29 | mRlContent.setVisibility(View.GONE); 30 | } 31 | 32 | @Override 33 | protected void onNetworkDisConnected() { 34 | mTvState.setText("网络连接断开"); 35 | mRlContent.setVisibility(View.VISIBLE); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /app/src/main/java/com/deng/netmonitor/base/BaseActivity.java: -------------------------------------------------------------------------------- 1 | package com.deng.netmonitor.base; 2 | 3 | import android.os.Bundle; 4 | import android.support.annotation.Nullable; 5 | import android.support.v7.app.AppCompatActivity; 6 | 7 | import com.caption.netmonitorlibrary.netStateLib.NetChangeObserver; 8 | import com.caption.netmonitorlibrary.netStateLib.NetStateReceiver; 9 | import com.caption.netmonitorlibrary.netStateLib.NetUtils; 10 | 11 | /** 12 | * Created by deng on 2016/9/30. 13 | */ 14 | 15 | public abstract class BaseActivity extends AppCompatActivity { 16 | 17 | /** 18 | * 网络观察者 19 | */ 20 | protected NetChangeObserver mNetChangeObserver = null; 21 | 22 | @Override 23 | protected void onCreate(@Nullable Bundle savedInstanceState) { 24 | super.onCreate(savedInstanceState); 25 | 26 | // 网络改变的一个回掉类 27 | mNetChangeObserver = new NetChangeObserver() { 28 | @Override 29 | public void onNetConnected(NetUtils.NetType type) { 30 | onNetworkConnected(type); 31 | } 32 | 33 | @Override 34 | public void onNetDisConnect() { 35 | onNetworkDisConnected(); 36 | } 37 | }; 38 | 39 | //开启广播去监听 网络 改变事件 40 | NetStateReceiver.registerObserver(mNetChangeObserver); 41 | } 42 | 43 | @Override 44 | protected void onDestroy() { 45 | super.onDestroy(); 46 | } 47 | 48 | 49 | /** 50 | * 网络连接状态 51 | * 52 | * @param type 网络状态 53 | */ 54 | protected abstract void onNetworkConnected(NetUtils.NetType type); 55 | 56 | /** 57 | * 网络断开的时候调用 58 | */ 59 | protected abstract void onNetworkDisConnected(); 60 | 61 | } 62 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 15 | 21 | 26 | 27 | 28 | 29 | 35 | 36 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GHdeng/NetMonitor/93823a73bda12fb13f81b369db71568f23d112bd/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GHdeng/NetMonitor/93823a73bda12fb13f81b369db71568f23d112bd/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GHdeng/NetMonitor/93823a73bda12fb13f81b369db71568f23d112bd/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_net_state.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GHdeng/NetMonitor/93823a73bda12fb13f81b369db71568f23d112bd/app/src/main/res/mipmap-xhdpi/ic_net_state.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GHdeng/NetMonitor/93823a73bda12fb13f81b369db71568f23d112bd/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GHdeng/NetMonitor/93823a73bda12fb13f81b369db71568f23d112bd/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/values-w820dp/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 64dp 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #3F51B5 4 | #303F9F 5 | #FF4081 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 16dp 4 | 16dp 5 | 6 | -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | NetMonitor 3 | 4 | -------------------------------------------------------------------------------- /app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /app/src/test/java/com/deng/netmonitor/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package com.deng.netmonitor; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * Example local unit test, which will execute on the development machine (host). 9 | * 10 | * @see Testing documentation 11 | */ 12 | public class ExampleUnitTest { 13 | @Test 14 | public void addition_isCorrect() throws Exception { 15 | assertEquals(4, 2 + 2); 16 | } 17 | } -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | repositories { 5 | jcenter() 6 | } 7 | dependencies { 8 | classpath 'com.android.tools.build:gradle:2.2.1' 9 | classpath 'com.github.dcendents:android-maven-gradle-plugin:1.4.1' 10 | classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.4' 11 | // NOTE: Do not place your application dependencies here; they belong 12 | // in the individual module build.gradle files 13 | } 14 | } 15 | 16 | allprojects { 17 | repositories { 18 | jcenter() 19 | } 20 | } 21 | 22 | task clean(type: Delete) { 23 | delete rootProject.buildDir 24 | } 25 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | org.gradle.jvmargs=-Xmx1536m 13 | 14 | # When configured, Gradle will run in incubating parallel mode. 15 | # This option should only be used with decoupled projects. More details, visit 16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 17 | # org.gradle.parallel=true 18 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GHdeng/NetMonitor/93823a73bda12fb13f81b369db71568f23d112bd/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Mon Dec 28 10:00:20 PST 2015 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # Attempt to set APP_HOME 46 | # Resolve links: $0 may be a link 47 | PRG="$0" 48 | # Need this for relative symlinks. 49 | while [ -h "$PRG" ] ; do 50 | ls=`ls -ld "$PRG"` 51 | link=`expr "$ls" : '.*-> \(.*\)$'` 52 | if expr "$link" : '/.*' > /dev/null; then 53 | PRG="$link" 54 | else 55 | PRG=`dirname "$PRG"`"/$link" 56 | fi 57 | done 58 | SAVED="`pwd`" 59 | cd "`dirname \"$PRG\"`/" >/dev/null 60 | APP_HOME="`pwd -P`" 61 | cd "$SAVED" >/dev/null 62 | 63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 64 | 65 | # Determine the Java command to use to start the JVM. 66 | if [ -n "$JAVA_HOME" ] ; then 67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 68 | # IBM's JDK on AIX uses strange locations for the executables 69 | JAVACMD="$JAVA_HOME/jre/sh/java" 70 | else 71 | JAVACMD="$JAVA_HOME/bin/java" 72 | fi 73 | if [ ! -x "$JAVACMD" ] ; then 74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 75 | 76 | Please set the JAVA_HOME variable in your environment to match the 77 | location of your Java installation." 78 | fi 79 | else 80 | JAVACMD="java" 81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 82 | 83 | Please set the JAVA_HOME variable in your environment to match the 84 | location of your Java installation." 85 | fi 86 | 87 | # Increase the maximum file descriptors if we can. 88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 89 | MAX_FD_LIMIT=`ulimit -H -n` 90 | if [ $? -eq 0 ] ; then 91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 92 | MAX_FD="$MAX_FD_LIMIT" 93 | fi 94 | ulimit -n $MAX_FD 95 | if [ $? -ne 0 ] ; then 96 | warn "Could not set maximum file descriptor limit: $MAX_FD" 97 | fi 98 | else 99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 100 | fi 101 | fi 102 | 103 | # For Darwin, add options to specify how the application appears in the dock 104 | if $darwin; then 105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 106 | fi 107 | 108 | # For Cygwin, switch paths to Windows format before running java 109 | if $cygwin ; then 110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 112 | JAVACMD=`cygpath --unix "$JAVACMD"` 113 | 114 | # We build the pattern for arguments to be converted via cygpath 115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 116 | SEP="" 117 | for dir in $ROOTDIRSRAW ; do 118 | ROOTDIRS="$ROOTDIRS$SEP$dir" 119 | SEP="|" 120 | done 121 | OURCYGPATTERN="(^($ROOTDIRS))" 122 | # Add a user-defined pattern to the cygpath arguments 123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 125 | fi 126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 127 | i=0 128 | for arg in "$@" ; do 129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 131 | 132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 134 | else 135 | eval `echo args$i`="\"$arg\"" 136 | fi 137 | i=$((i+1)) 138 | done 139 | case $i in 140 | (0) set -- ;; 141 | (1) set -- "$args0" ;; 142 | (2) set -- "$args0" "$args1" ;; 143 | (3) set -- "$args0" "$args1" "$args2" ;; 144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 150 | esac 151 | fi 152 | 153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 154 | function splitJvmOpts() { 155 | JVM_OPTS=("$@") 156 | } 157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 159 | 160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 161 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /netmonitorlibrary/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | apply plugin: 'com.github.dcendents.android-maven' 3 | apply plugin: 'com.jfrog.bintray' 4 | 5 | 6 | android { 7 | compileSdkVersion 25 8 | buildToolsVersion "25.0.0" 9 | 10 | defaultConfig { 11 | minSdkVersion 15 12 | targetSdkVersion 25 13 | versionCode 1 14 | versionName "1.0" 15 | } 16 | buildTypes { 17 | release { 18 | minifyEnabled false 19 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 20 | } 21 | } 22 | } 23 | 24 | dependencies { 25 | compile fileTree(dir: 'libs', include: ['*.jar']) 26 | } 27 | 28 | // 项目引用的版本号 29 | version = "1.0.0" 30 | 31 | def siteUrl = 'https://github.com/GHdeng/NetMonitor' // 项目主页。 32 | def gitUrl = 'git@github.com:GHdeng/NetMonitor.git' // Git仓库的url。 33 | 34 | group = "com.caption" 35 | 36 | install { 37 | repositories.mavenInstaller { 38 | // 生成pom.xml和参数 39 | pom { 40 | project { 41 | packaging 'aar' 42 | // 项目描述,复制我的话,这里需要修改。 43 | name 'AndServer For Android'// 可选,项目名称。 44 | description 'The Android build the framework of the Http server.'// 可选,项目描述。 45 | url siteUrl // 项目主页,这里是引用上面定义好。 46 | 47 | // 软件开源协议,现在一般都是Apache License2.0吧,复制我的,这里不需要修改。 48 | licenses { 49 | license { 50 | name 'The Apache Software License, Version 2.0' 51 | url 'http://www.apache.org/licenses/LICENSE-2.0.txt' 52 | } 53 | } 54 | 55 | //填写开发者基本信息,复制我的,这里需要修改。 56 | developers { 57 | developer { 58 | id 'ghdeng' // 开发者的id。 59 | name 'ghdeng' // 开发者名字。 60 | email 'caption.deng@gmail.com' // 开发者邮箱。 61 | } 62 | } 63 | 64 | // SCM,复制我的,这里不需要修改。 65 | scm { 66 | connection gitUrl // Git仓库地址。 67 | developerConnection gitUrl // Git仓库地址。 68 | url siteUrl // 项目主页。 69 | } 70 | } 71 | } 72 | } 73 | } 74 | // 生成jar包的task,不需要修改。 75 | task sourcesJar(type: Jar) { 76 | from android.sourceSets.main.java.srcDirs 77 | classifier = 'sources' 78 | } 79 | // 生成jarDoc的task,不需要修改。 80 | task javadoc(type: Javadoc) { 81 | source = android.sourceSets.main.java.srcDirs 82 | classpath += project.files(android.getBootClasspath().join(File.pathSeparator)) 83 | // destinationDir = file("../javadoc/") 84 | failOnError false // 忽略注释语法错误,如果用jdk1.8你的注释写的不规范就编译不过。 85 | } 86 | // 生成javaDoc的jar,不需要修改。 87 | task javadocJar(type: Jar, dependsOn: javadoc) { 88 | classifier = 'javadoc' 89 | from javadoc.destinationDir 90 | } 91 | artifacts { 92 | archives javadocJar 93 | archives sourcesJar 94 | } 95 | 96 | // 这里是读取Bintray相关的信息,我们上传项目到github上的时候会把gradle文件传上去,所以不要把帐号密码的信息直接写在这里,写在local.properties中,这里动态读取。 97 | Properties properties = new Properties() 98 | properties.load(project.rootProject.file('local.properties').newDataInputStream()) 99 | bintray { 100 | user = properties.getProperty("bintray.user") // Bintray的用户名。 101 | key = properties.getProperty("bintray.apikey") // Bintray刚才保存的ApiKey。 102 | 103 | configurations = ['archives'] 104 | pkg { 105 | repo = "maven" // 上传到maven库。 106 | name = "NetMonitor" // 发布到Bintray上的项目名字,这里的名字不是compile 'com.yanzhenjie:andserver:1.0.1'中的andserver。 107 | userOrg = 'captiondeng' // Bintray的用户名,2016年11月更新。 108 | websiteUrl = siteUrl 109 | vcsUrl = gitUrl 110 | licenses = ["Apache-2.0"] 111 | publish = true // 是否是公开项目。 112 | } 113 | } -------------------------------------------------------------------------------- /netmonitorlibrary/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /Users/deng/Library/Android/sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /netmonitorlibrary/src/androidTest/java/com/caption/netmonitorlibrary/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package com.caption.netmonitorlibrary; 2 | 3 | import android.content.Context; 4 | import android.support.test.InstrumentationRegistry; 5 | import android.support.test.runner.AndroidJUnit4; 6 | 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | 10 | import static org.junit.Assert.*; 11 | 12 | /** 13 | * Instrumentation test, which will execute on an Android device. 14 | * 15 | * @see Testing documentation 16 | */ 17 | @RunWith(AndroidJUnit4.class) 18 | public class ExampleInstrumentedTest { 19 | @Test 20 | public void useAppContext() throws Exception { 21 | // Context of the app under test. 22 | Context appContext = InstrumentationRegistry.getTargetContext(); 23 | 24 | assertEquals("com.caption.netmonitorlibrary.test", appContext.getPackageName()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /netmonitorlibrary/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /netmonitorlibrary/src/main/java/com/caption/netmonitorlibrary/netStateLib/NetChangeObserver.java: -------------------------------------------------------------------------------- 1 | package com.caption.netmonitorlibrary.netStateLib; 2 | 3 | /** 4 | * 网络改变观察者,观察网络改变后回调的方法 5 | * Created by 邓鉴恒 on 16/9/13. 6 | */ 7 | public interface NetChangeObserver { 8 | 9 | /** 10 | * 网络连接回调 type为网络类型 11 | */ 12 | void onNetConnected(NetUtils.NetType type); 13 | 14 | /** 15 | * 没有网络 16 | */ 17 | void onNetDisConnect(); 18 | } 19 | -------------------------------------------------------------------------------- /netmonitorlibrary/src/main/java/com/caption/netmonitorlibrary/netStateLib/NetStateReceiver.java: -------------------------------------------------------------------------------- 1 | package com.caption.netmonitorlibrary.netStateLib; 2 | 3 | import android.content.BroadcastReceiver; 4 | import android.content.Context; 5 | import android.content.Intent; 6 | import android.content.IntentFilter; 7 | import android.util.Log; 8 | 9 | import java.util.ArrayList; 10 | 11 | /** 12 | * 使用广播去监听网络 13 | * Created by 邓鉴恒 on 16/9/13. 14 | */ 15 | public class NetStateReceiver extends BroadcastReceiver { 16 | 17 | public final static String CUSTOM_ANDROID_NET_CHANGE_ACTION = "com.zhanyun.api.netstatus.CONNECTIVITY_CHANGE"; 18 | private final static String ANDROID_NET_CHANGE_ACTION = "android.net.conn.CONNECTIVITY_CHANGE"; 19 | private final static String TAG = NetStateReceiver.class.getSimpleName(); 20 | 21 | private static boolean isNetAvailable = false; 22 | private static NetUtils.NetType mNetType; 23 | private static ArrayList mNetChangeObservers = new ArrayList(); 24 | private static BroadcastReceiver mBroadcastReceiver; 25 | 26 | private static BroadcastReceiver getReceiver() { 27 | if (null == mBroadcastReceiver) { 28 | synchronized (NetStateReceiver.class) { 29 | if (null == mBroadcastReceiver) { 30 | mBroadcastReceiver = new NetStateReceiver(); 31 | } 32 | } 33 | } 34 | return mBroadcastReceiver; 35 | } 36 | 37 | @Override 38 | public void onReceive(Context context, Intent intent) { 39 | mBroadcastReceiver = NetStateReceiver.this; 40 | if (intent.getAction().equalsIgnoreCase(ANDROID_NET_CHANGE_ACTION) || intent.getAction().equalsIgnoreCase(CUSTOM_ANDROID_NET_CHANGE_ACTION)) { 41 | if (!NetUtils.isNetworkAvailable(context)) { 42 | Log.e(this.getClass().getName(), "<--- network disconnected --->"); 43 | isNetAvailable = false; 44 | } else { 45 | Log.e(this.getClass().getName(), "<--- network connected --->"); 46 | isNetAvailable = true; 47 | mNetType = NetUtils.getAPNType(context); 48 | } 49 | notifyObserver(); 50 | } 51 | } 52 | 53 | /** 54 | * 注册 55 | * 56 | * @param mContext 57 | */ 58 | public static void registerNetworkStateReceiver(Context mContext) { 59 | IntentFilter filter = new IntentFilter(); 60 | filter.addAction(CUSTOM_ANDROID_NET_CHANGE_ACTION); 61 | filter.addAction(ANDROID_NET_CHANGE_ACTION); 62 | mContext.getApplicationContext().registerReceiver(getReceiver(), filter); 63 | } 64 | 65 | /** 66 | * 清除 67 | * 68 | * @param mContext 69 | */ 70 | public static void checkNetworkState(Context mContext) { 71 | Intent intent = new Intent(); 72 | intent.setAction(CUSTOM_ANDROID_NET_CHANGE_ACTION); 73 | mContext.sendBroadcast(intent); 74 | } 75 | 76 | /** 77 | * 反注册 78 | * 79 | * @param mContext 80 | */ 81 | public static void unRegisterNetworkStateReceiver(Context mContext) { 82 | if (mBroadcastReceiver != null) { 83 | try { 84 | mContext.getApplicationContext().unregisterReceiver(mBroadcastReceiver); 85 | } catch (Exception e) { 86 | 87 | } 88 | } 89 | 90 | } 91 | 92 | public static boolean isNetworkAvailable() { 93 | return isNetAvailable; 94 | } 95 | 96 | public static NetUtils.NetType getAPNType() { 97 | return mNetType; 98 | } 99 | 100 | private void notifyObserver() { 101 | if (!mNetChangeObservers.isEmpty()) { 102 | int size = mNetChangeObservers.size(); 103 | for (int i = 0; i < size; i++) { 104 | NetChangeObserver observer = mNetChangeObservers.get(i); 105 | if (observer != null) { 106 | if (isNetworkAvailable()) { 107 | observer.onNetConnected(mNetType); 108 | } else { 109 | observer.onNetDisConnect(); 110 | } 111 | } 112 | } 113 | } 114 | } 115 | 116 | /** 117 | * 添加网络监听 118 | * 119 | * @param observer 120 | */ 121 | public static void registerObserver(NetChangeObserver observer) { 122 | if (mNetChangeObservers == null) { 123 | mNetChangeObservers = new ArrayList(); 124 | } 125 | mNetChangeObservers.add(observer); 126 | } 127 | 128 | /** 129 | * 移除网络监听 130 | * 131 | * @param observer 132 | */ 133 | public static void removeRegisterObserver(NetChangeObserver observer) { 134 | if (mNetChangeObservers != null) { 135 | if (mNetChangeObservers.contains(observer)) { 136 | mNetChangeObservers.remove(observer); 137 | } 138 | } 139 | } 140 | } -------------------------------------------------------------------------------- /netmonitorlibrary/src/main/java/com/caption/netmonitorlibrary/netStateLib/NetUtils.java: -------------------------------------------------------------------------------- 1 | package com.caption.netmonitorlibrary.netStateLib; 2 | 3 | import android.content.Context; 4 | import android.net.ConnectivityManager; 5 | import android.net.NetworkInfo; 6 | 7 | import java.util.Locale; 8 | 9 | /** 10 | * 网络状态类型 11 | * Created by 邓鉴恒 on 16/9/13. 12 | */ 13 | public class NetUtils { 14 | 15 | public static enum NetType { 16 | WIFI, CMNET, CMWAP, NONE 17 | } 18 | 19 | public static boolean isNetworkAvailable(Context context) { 20 | ConnectivityManager mgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 21 | NetworkInfo[] info = mgr.getAllNetworkInfo(); 22 | if (info != null) { 23 | for (int i = 0; i < info.length; i++) { 24 | if (info[i].getState() == NetworkInfo.State.CONNECTED) { 25 | return true; 26 | } 27 | } 28 | } 29 | return false; 30 | } 31 | 32 | public static boolean isNetworkConnected(Context context) { 33 | if (context != null) { 34 | ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 35 | NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo(); 36 | if (mNetworkInfo != null) { 37 | return mNetworkInfo.isAvailable(); 38 | } 39 | } 40 | return false; 41 | } 42 | 43 | public static boolean isWifiConnected(Context context) { 44 | if (context != null) { 45 | ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 46 | NetworkInfo mWiFiNetworkInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); 47 | if (mWiFiNetworkInfo != null) { 48 | return mWiFiNetworkInfo.isAvailable(); 49 | } 50 | } 51 | return false; 52 | } 53 | 54 | public static boolean isMobileConnected(Context context) { 55 | if (context != null) { 56 | ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 57 | NetworkInfo mMobileNetworkInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); 58 | if (mMobileNetworkInfo != null) { 59 | return mMobileNetworkInfo.isAvailable(); 60 | } 61 | } 62 | return false; 63 | } 64 | 65 | public static int getConnectedType(Context context) { 66 | if (context != null) { 67 | ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 68 | NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo(); 69 | if (mNetworkInfo != null && mNetworkInfo.isAvailable()) { 70 | return mNetworkInfo.getType(); 71 | } 72 | } 73 | return -1; 74 | } 75 | 76 | public static NetType getAPNType(Context context) { 77 | ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 78 | NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); 79 | if (networkInfo == null) { 80 | return NetType.NONE; 81 | } 82 | int nType = networkInfo.getType(); 83 | 84 | if (nType == ConnectivityManager.TYPE_MOBILE) { 85 | if (networkInfo.getExtraInfo().toLowerCase(Locale.getDefault()).equals("cmnet")) { 86 | return NetType.CMNET; 87 | } else { 88 | return NetType.CMWAP; 89 | } 90 | } else if (nType == ConnectivityManager.TYPE_WIFI) { 91 | return NetType.WIFI; 92 | } 93 | return NetType.NONE; 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /netmonitorlibrary/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | NetMonitorLibrary 3 | 4 | -------------------------------------------------------------------------------- /netmonitorlibrary/src/test/java/com/caption/netmonitorlibrary/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package com.caption.netmonitorlibrary; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * Example local unit test, which will execute on the development machine (host). 9 | * 10 | * @see Testing documentation 11 | */ 12 | public class ExampleUnitTest { 13 | @Test 14 | public void addition_isCorrect() throws Exception { 15 | assertEquals(4, 2 + 2); 16 | } 17 | } -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':app', ':netmonitorlibrary' 2 | -------------------------------------------------------------------------------- /tea.yaml: -------------------------------------------------------------------------------- 1 | # https://tea.xyz/what-is-this-file 2 | --- 3 | version: 1.0.0 4 | codeOwners: 5 | - '0x3d912Ce223a47c8AAE1c6F946366a46fe5A8C691' 6 | quorum: 1 7 | --------------------------------------------------------------------------------