├── .gitignore
├── .travis.yml
├── CHANGELOG.md
├── LICENSE
├── Readme.md
├── build.gradle
├── config
├── checkstyle.xml
├── findbugs-filter.xml
├── pmd-ruleset.xml
└── quality.gradle
├── connectionbuddy
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ └── main
│ ├── AndroidManifest.xml
│ └── java
│ └── com
│ └── zplesac
│ └── connectionbuddy
│ ├── ConnectionBuddy.java
│ ├── ConnectionBuddyCache.java
│ ├── ConnectionBuddyConfiguration.java
│ ├── LruConnectionBuddyCache.java
│ ├── NetworkChangeReceiver.java
│ ├── activities
│ └── ConnectionBuddyActivity.java
│ ├── interfaces
│ ├── ConnectivityChangeListener.java
│ ├── NetworkRequestCheckListener.java
│ └── WifiConnectivityListener.java
│ ├── models
│ ├── ConnectivityEvent.java
│ ├── ConnectivityState.java
│ ├── ConnectivityStrength.java
│ └── ConnectivityType.java
│ └── presenters
│ └── ConnectivityPresenter.java
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── sampleapp
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ └── main
│ ├── AndroidManifest.xml
│ ├── java
│ └── com
│ │ └── zplesac
│ │ └── connectionbuddy
│ │ └── sampleapp
│ │ ├── SampleApp.java
│ │ ├── activities
│ │ ├── MVPActivity.java
│ │ ├── MainActivity.java
│ │ ├── ManualConfigurationActivity.java
│ │ ├── SimpleActivity.java
│ │ └── WiFiActivity.java
│ │ ├── dagger
│ │ ├── components
│ │ │ └── MVPComponent.java
│ │ └── modules
│ │ │ ├── ContextModule.java
│ │ │ └── MVPModule.java
│ │ └── mvp
│ │ ├── presenters
│ │ ├── MVPPresenter.java
│ │ └── impl
│ │ │ └── MVPPresenterImpl.java
│ │ └── views
│ │ └── MVPView.java
│ └── res
│ ├── layout
│ ├── activity_main.xml
│ ├── activity_mvp.xml
│ └── activity_wi_fi.xml
│ ├── mipmap-hdpi
│ └── ic_launcher.png
│ ├── mipmap-mdpi
│ └── ic_launcher.png
│ ├── mipmap-xhdpi
│ └── ic_launcher.png
│ ├── mipmap-xxhdpi
│ └── ic_launcher.png
│ └── values
│ ├── strings.xml
│ └── styles.xml
└── settings.gradle
/.gitignore:
--------------------------------------------------------------------------------
1 | # Created by https://www.gitignore.io
2 |
3 | ### OSX ###
4 | .DS_Store
5 | .AppleDouble
6 | .LSOverride
7 |
8 | # Icon must end with two \r
9 | Icon
10 |
11 |
12 | # Thumbnails
13 | ._*
14 |
15 | # Files that might appear in the root of a volume
16 | .DocumentRevisions-V100
17 | .fseventsd
18 | .Spotlight-V100
19 | .TemporaryItems
20 | .Trashes
21 | .VolumeIcon.icns
22 |
23 | # Directories potentially created on remote AFP share
24 | .AppleDB
25 | .AppleDesktop
26 | Network Trash Folder
27 | Temporary Items
28 | .apdisk
29 |
30 |
31 | ### Android ###
32 | # Built application files
33 | *.apk
34 | *.ap_
35 |
36 | # Files for the Dalvik VM
37 | *.dex
38 |
39 | # Java class files
40 | *.class
41 |
42 | # Generated files
43 | bin/
44 | gen/
45 |
46 | # Gradle files
47 | .gradle/
48 | build/
49 | /*/build/
50 |
51 | # Local configuration file (sdk path, etc)
52 | local.properties
53 |
54 | # Proguard folder generated by Eclipse
55 | proguard/
56 |
57 | # Log Files
58 | *.log
59 |
60 | ### Android Patch ###
61 | gen-external-apklibs
62 |
63 |
64 | ### Intellij ###
65 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm
66 |
67 | *.iml
68 |
69 | ## Directory-based project format:
70 | .idea/
71 | # if you remove the above rule, at least ignore the following:
72 |
73 | # User-specific stuff:
74 | # .idea/workspace.xml
75 | # .idea/tasks.xml
76 | # .idea/dictionaries
77 |
78 | # Sensitive or high-churn files:
79 | # .idea/dataSources.ids
80 | # .idea/dataSources.xml
81 | # .idea/sqlDataSources.xml
82 | # .idea/dynamic.xml
83 | # .idea/uiDesigner.xml
84 |
85 | # Gradle:
86 | # .idea/gradle.xml
87 | # .idea/libraries
88 |
89 | # Mongo Explorer plugin:
90 | # .idea/mongoSettings.xml
91 |
92 | ## File-based project format:
93 | *.ipr
94 | *.iws
95 |
96 | ## Plugin-specific files:
97 |
98 | # IntelliJ
99 | /out/
100 |
101 | # mpeltonen/sbt-idea plugin
102 | .idea_modules/
103 |
104 | # JIRA plugin
105 | atlassian-ide-plugin.xml
106 |
107 | # Crashlytics plugin (for Android Studio and IntelliJ)
108 | com_crashlytics_export_strings.xml
109 | crashlytics.properties
110 | crashlytics-build.properties
111 |
112 | # Proguard
113 | app/class_files.txt
114 | app/mapping.txt
115 | app/seeds.txt
116 | app/unused.txt%
117 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: android
2 |
3 | # use container based build infrastructure
4 | sudo: false
5 |
6 | jdk:
7 | - oraclejdk8
8 |
9 | android:
10 | components:
11 | - platform-tools
12 | - tools
13 | - build-tools-28.0.3
14 | - android-28
15 | - extra-google-google_play_services
16 | - extra-google-m2repository
17 | - extra-android-m2repository
18 | licenses:
19 | - '.+'
20 | script:
21 | - ./gradlew assembleDebug -PdisablePreDex
22 | - ./gradlew checkstyle findbugs pmd -PdisablePreDex
23 |
24 | cache:
25 | directories:
26 | - $HOME/.gradle
27 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | Changelog
2 | =========
3 |
4 | ## Version 1.4.0
5 | _2016-12_07_
6 |
7 | * Update: compileSdkVersion to API version 25
8 | * New: connect to WiFi signal by providing network SSID and network password
9 |
10 | ## Version 1.3.0
11 | _2016-10_13_
12 |
13 | * Update: compileSdkVersion to API version 24
14 | * Update: minSdkVersion is now API version 9 (min supported version of Android Support Library)
15 |
16 | ## Version 1.2.0
17 |
18 | _2016-09-30_
19 |
20 | * Update: Library is now backported to API level 8.
21 |
22 | ## Version 1.1.2
23 |
24 | _2016-07-19_
25 |
26 | * Fixes: fixed null pointer exceptions in getting signal strength
27 |
28 | ## Version 1.1.1
29 |
30 | _2016-07-14_
31 |
32 | * Update: bumped SDK version to 23
33 | * Update: removed ConnectivityType.BOTH, as device can have only one ConnectivityType at the moment
34 | * Update: code hygiene and refactor
35 |
36 | ## Version 1.1.0
37 |
38 | _2016-03-17_
39 |
40 | * New: introduced ConnectionBuddyActivity for simpler configuration
41 | * New: added option to be notified only about reliable events
42 | * Update: code hygiene and refactor
43 |
44 | ## Version 1.0.6
45 |
46 | _2015-12-01_
47 |
48 | * New: library has undergone rebranding process and the name has changed - it's ConnectionBuddy now. This also means that library has
49 | migrated to a new jCenter repository, and the old one has been deleted.
50 |
51 | ## Version 1.0.5
52 |
53 | _2015-12-01_
54 |
55 | * New: added new configuration options - you can now decide do you want to be notified about current network connection state
56 | immediately after the listener has been registered
57 |
58 | ## Version 1.0.4
59 |
60 | _2015-11-15_
61 |
62 | * Update: refactored caching mechanism to use LruCache instead of SharedPreferences
63 |
64 | ## Version 1.0.3.
65 |
66 | _2015-10-11_
67 |
68 | * Bug fixes - fixed bug with signal strength
69 |
70 | ## Version 1.0.2.
71 | _2015-10-31_
72 |
73 | * New: added information about signal strength to ConnectivityEvent object
74 | * Update: events can now also be filtered by signal strength
75 |
76 | ## Version 1.0.1.
77 |
78 | _2015-10-19_
79 |
80 | * New: added information about network connection type to network change receiver
81 | * New: library behaviour can now be customized - we can decide for which network connection event type we want to register for
82 | * Update: unified all names of properties
83 | * Bug fixes
84 |
85 | ## Version 1.0.0
86 |
87 | _2015-09-21_
88 |
89 | Initial release.
90 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright 2015 Željko Plesac
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/Readme.md:
--------------------------------------------------------------------------------
1 | # Deprecated
2 | This library is no longer supported and will not receive any more updates.
3 |
4 | [](https://travis-ci.org/zplesac/android_connectionbuddy)
5 | [](https://www.apache.org/licenses/LICENSE-2.0)
6 | [](https://bintray.com/zplesac/maven/android-connectionbuddy/view)
7 | [](https://android-arsenal.com/details/1/2788)
8 |
9 |
10 | # Android ConnectionBuddy
11 |
12 | Provides a simple way of handling connectivity change events.
13 |
14 | # Usage
15 |
16 | 1) Add the library as a dependency to your ```build.gradle```
17 |
18 | ```groovy
19 | compile 'com.zplesac:connectionbuddy:version@aar'
20 | ```
21 |
22 | Check the latest version [here](https://bintray.com/search?query=connectionbuddy).
23 |
24 | Versions prior to 1.0.5 were hosted on an older jCenter repository and aren't available anymore due to trademark issues.
25 |
26 | 2) Initialize a [ConnectionBuddy](https://github.com/zplesac/android_connectionbuddy/blob/master/connectionbuddy/src/main/java/com/zplesac/connectionbuddy/ConnectionBuddy.java) instance in your Application class. You'll also need to provide a global configuration by defining [ConnectionBuddyConfiguration](https://github.com/zplesac/android_connectionbuddy/blob/master/connectionbuddy/src/main/java/com/zplesac/connectionbuddy/ConnectionBuddyConfiguration.java) object.
27 |
28 | ```java
29 | public class SampleApp extends Application {
30 |
31 | @Override
32 | public void onCreate() {
33 | super.onCreate();
34 | ConnectionBuddyConfiguration networkInspectorConfiguration = new ConnectionBuddyConfiguration.Builder(this).build();
35 | ConnectionBuddy.getInstance().init(networkInspectorConfiguration);
36 | }
37 | }
38 | ```
39 |
40 | All options in [ConnectionBuddyConfiguration.Builder](https://github.com/zplesac/android_connectionbuddy/blob/master/connectionbuddy/src/main/java/com/zplesac/connectionbuddy/ConnectionBuddyConfiguration.java) are optional. Use only those you really want to customize.
41 |
42 | 3) Make your activites (or BaseActivity) extend [ConnectionBuddyActivity](https://github.com/zplesac/android_connectionbuddy/blob/development/connectionbuddy/src/main/java/com/zplesac/connectionbuddy/activities/ConnectionBuddyActivity.java), and react to connectivity change events in onConnectionChange(ConnectivityEvent event) callback method:
43 |
44 | ```java
45 | @Override
46 | public void onConnectionChange(ConnectivityEvent event) {
47 | if(event.getState() == ConnectivityState.CONNECTED){
48 | // device has active internet connection
49 | }
50 | else{
51 | // there is no active internet connection on this device
52 | }
53 | }
54 | ```
55 |
56 | If you don't want to extend [ConnectionBuddyActivity](https://github.com/zplesac/android_connectionbuddy/blob/development/connectionbuddy/src/main/java/com/zplesac/connectionbuddy/activities/ConnectionBuddyActivity.java), you can use manual configuration:
57 |
58 | * Register to connectivity change events in the onStart() method of your activity:
59 |
60 | ```java
61 |
62 | @Override
63 | protected void onStart() {
64 | super.onStart();
65 | ConnectionBuddy.getInstance().registerForConnectivityEvents(this, this);
66 | }
67 |
68 | ```
69 |
70 | * Unregister from connectivity change events in the onStop() method of your activity:
71 |
72 | ```java
73 |
74 | @Override
75 | protected void onStop() {
76 | super.onStop();
77 | ConnectionBuddy.getInstance().unregisterFromConnectivityEvents(this);
78 | }
79 |
80 | ```
81 |
82 | * Clear the stored connectivity state for your activity/fragment if it was restored from a saved instance state (in order to always have the latest connectivity state). Add to your onCreate() method the following line of code:
83 |
84 | ```java
85 | @Override
86 | protected void onCreate(Bundle savedInstanceState) {
87 | super.onCreate(savedInstanceState);
88 |
89 | ...
90 |
91 | if(savedInstanceState != null){
92 | ConnectionBuddyCache.clearInternetConnection(this);
93 | }
94 | }
95 | ```
96 |
97 | * Implement a [ConnectivityChangeListener](https://github.com/zplesac/android_connectionbuddy/blob/master/connectionbuddy/src/main/java/com/zplesac/connectionbuddy/interfaces/ConnectivityChangeListener.java) interface and react to connectivity change events.
98 |
99 | ConnectivityEvent also holds some additional information:
100 | * [ConnectivityType](https://github.com/zplesac/android_connectionbuddy/blob/master/connectionbuddy/src/main/java/com/zplesac/connectionbuddy/models/ConnectivityType.java) enum, which defines the network connection type currently available on the user's device
101 | * [ConnectivityStrength](https://github.com/zplesac/android_connectionbuddy/blob/master/connectionbuddy/src/main/java/com/zplesac/connectionbuddy/models/ConnectivityStrength.java) enum, which describes signal strength of the network connection.
102 |
103 |
104 | ## ConnectionBuddy configuration
105 |
106 | You can customize the default ConnectionBuddy configuration by providing your own configuration. Following values can be changed:
107 |
108 | #### 1. registerForWiFiChanges(boolean shouldRegister)
109 |
110 | A Boolean value which defines whether we should register for WiFi network changes. The default value is set to true.
111 |
112 | #### 2. registerForMobileNetworkChanges(boolean shouldRegister)
113 |
114 | A Boolean value which defines whether we should register for mobile network changes. The default value is set to true.
115 |
116 | #### 3. setMinimumSignalStrength(ConnectivityStrength minimumSignalStrength)
117 |
118 | Defines the minimum signal strength for which the callback listener should be notified. The default value is set to ConnectivityStrength.POOR.
119 |
120 | #### 4. setNotifyImmediately(boolean shouldNotify)
121 |
122 | A Boolean value which defines whether we want to notify the listener about the current network connection state immediately after the listener has been registered. The default value is set to true.
123 |
124 | #### 5. notifyOnlyReliableEvents(boolean shouldNotify)
125 |
126 | A Boolean value which defines whether we want to use reliable network events. If we have an active internet connection, it will try to execute a test network request to determine whether a user is capable of any network operation. The default value is set to false.
127 |
128 | ## Advanced usage with MVP pattern
129 |
130 | ConnectionBuddy also provides [ConnectivityPresenter](https://github.com/zplesac/android_connectionbuddy/blob/master/connectionbuddy/src/main/java/com/zplesac/connectionbuddy/presenters/ConnectivityPresenter.java)
131 | which can be used as a base presenter for registering to connectivity change events.
132 | A more detailed example can be found [here](https://github.com/zplesac/android_connectionbuddy/blob/master/sampleapp/src/main/java/com/zplesac/connectionbuddy/sampleapp/activities/MVPActivity.java).
133 |
134 | ## Backward compatibility
135 |
136 | As of version 1.2.0, ConnectionBuddy can be used with your apps on devices all the way back to Android 2.3 (API 10). It should also work on devices with API 8-9, but that's not tested.
137 |
138 | ## Changelog
139 |
140 | Changelog is available in the [releases tab](https://github.com/zplesac/android_connectionbuddy/releases).
141 |
142 | For versions prior to 2.0.0, [here.](https://github.com/zplesac/android_connectionbuddy/blob/master/CHANGELOG.md)
143 |
144 | ## Contributing
145 |
146 | Feedback and code contributions are very much welcome. Just make a pull request with a short description of your changes. By making contributions to this project you give permission for your code to be used under the same [license](LICENSE).
147 |
--------------------------------------------------------------------------------
/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 | google()
6 | jcenter()
7 | }
8 | dependencies {
9 | classpath 'com.android.tools.build:gradle:3.3.0'
10 | classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.2'
11 | classpath 'com.github.dcendents:android-maven-gradle-plugin:1.4.1'
12 |
13 | // NOTE: Do not place your application dependencies here; they belong
14 | // in the individual module build.gradle files
15 | }
16 | }
17 |
18 | allprojects {
19 | repositories {
20 | google()
21 | jcenter()
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/config/checkstyle.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 |
116 |
117 |
118 |
119 |
120 |
121 |
122 |
123 |
124 |
125 |
126 |
127 |
--------------------------------------------------------------------------------
/config/findbugs-filter.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/config/pmd-ruleset.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 | This ruleset checks my code for bad stuff
8 |
9 |
--------------------------------------------------------------------------------
/config/quality.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'checkstyle'
2 | apply plugin: 'findbugs'
3 | apply plugin: 'pmd'
4 |
5 | check.dependsOn 'findbugs', 'checkstyle', 'pmd'
6 |
7 | task checkstyle(type: Checkstyle) {
8 | configFile file("${project.rootDir}/config/checkstyle.xml")
9 | configProperties = [
10 | 'checkstyle.cache.file': rootProject.file('build/checkstyle.cache'),
11 | ]
12 | source 'src'
13 | include '**/*.java'
14 | exclude '**/gen/**'
15 |
16 | classpath = files()
17 | }
18 |
19 | task findbugs(type: FindBugs) {
20 | ignoreFailures = false
21 | effort = "max"
22 | reportLevel = "high"
23 | excludeFilter = new File("${project.rootDir}/config/findbugs-filter.xml")
24 | classes = files("$project.buildDir/intermediates/javac/")
25 |
26 | source 'src'
27 | include '**/*.java'
28 | exclude '**/gen/**'
29 |
30 | reports {
31 | xml.enabled = false
32 | html.enabled = true
33 | html {
34 | destination "$project.buildDir/reports/findbugs/findbugs.html"
35 | }
36 | }
37 |
38 | classpath = files()
39 | }
40 |
41 | task pmd(type: Pmd) {
42 | ruleSetFiles = files("${project.rootDir}/config/pmd-ruleset.xml")
43 | ignoreFailures = false
44 |
45 | ruleSets = [
46 | 'java-android',
47 | 'java-basic',
48 | 'java-braces',
49 | 'java-clone',
50 | 'java-finalizers',
51 | 'java-unnecessary'
52 | ]
53 |
54 | source 'src'
55 | include '**/*.java'
56 | exclude '**/gen/**'
57 |
58 | reports {
59 | xml.enabled = false
60 | html.enabled = true
61 | }
62 | }
63 |
64 |
--------------------------------------------------------------------------------
/connectionbuddy/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/connectionbuddy/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 | apply plugin: 'maven'
3 | apply from: '../config/quality.gradle'
4 | apply plugin: 'com.github.dcendents.android-maven'
5 | apply plugin: 'com.jfrog.bintray'
6 | android {
7 | compileSdkVersion 28
8 | buildToolsVersion "28.0.3"
9 |
10 | defaultConfig {
11 | minSdkVersion 19
12 | targetSdkVersion 28
13 | versionCode 16
14 | versionName "2.0.1"
15 | }
16 | buildTypes {
17 | release {
18 | minifyEnabled false
19 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
20 | }
21 | }
22 |
23 | dependencies {
24 | implementation "com.android.support:support-v4:28.0.0"
25 | implementation 'com.android.support:support-annotations:28.0.0'
26 | }
27 |
28 | lintOptions {
29 | // if true, stop the gradle build if errors are found
30 | abortOnError true
31 | // if true, don't include source code lines in the error output
32 | noLines false
33 | // if true, show all locations for an error, do not truncate lists, etc.
34 | showAll true
35 | }
36 | }
37 | repositories {
38 | mavenCentral()
39 | }
40 |
41 | ext {
42 | bintrayRepo = 'maven'
43 | bintrayName = 'android-connectionbuddy'
44 |
45 | publishedGroupId = 'com.zplesac'
46 | libraryName = 'android-connectionbuddy'
47 | artifact = 'connectionbuddy' // Has to be same as your library module name
48 |
49 | libraryDescription = 'Utility library for handling connectivity change events.'
50 |
51 | // Your github repo link
52 | siteUrl = 'https://github.com/zplesac/android_connectionbuddy'
53 | gitUrl = 'https://github.com/zplesac/android_connectionbuddy.git'
54 |
55 | libraryVersion = '2.0.1'
56 |
57 | developerId = 'zplesac'
58 | developerName = 'Zeljko Plesac'
59 | developerEmail = 'zeljko.plesac@gmail.com'
60 |
61 | licenseName = 'Apache-2.0'
62 | licenseUrl = 'http://www.apache.org/licenses/LICENSE-2.0'
63 | allLicenses = ["Apache-2.0"]
64 | }
65 |
66 | group = publishedGroupId
67 | version = libraryVersion
68 |
69 | bintray {
70 |
71 | if (project.rootProject.file('local.properties').exists()) {
72 |
73 | Properties properties = new Properties()
74 | properties.load(project.rootProject.file('local.properties').newDataInputStream())
75 |
76 | user = properties.getProperty("bintray.user")
77 | key = properties.getProperty("bintray.apikey")
78 |
79 | configurations = ['archives']
80 | pkg {
81 | repo = bintrayRepo
82 | name = bintrayName
83 | desc = libraryDescription
84 | websiteUrl = siteUrl
85 | vcsUrl = gitUrl
86 | licenses = ["Apache-2.0"]
87 | publish = true
88 | publicDownloadNumbers = true
89 | dryRun = false
90 | version {
91 | name = libraryVersion
92 | desc = libraryDescription
93 | released = new Date()
94 | gpg {
95 | sign = true //Determines whether to GPG sign the files. The default is false
96 | passphrase = properties.getProperty("bintray.gpg.password")
97 | //Optional. The passphrase for GPG signing'
98 | }
99 | }
100 | }
101 | }
102 |
103 | }
104 |
105 | install {
106 | repositories.mavenInstaller {
107 | // This generates POM.xml with proper parameters
108 | pom {
109 | project {
110 | packaging 'aar'
111 | groupId publishedGroupId
112 | artifactId artifact
113 |
114 | // Add your description here
115 | name libraryName
116 | description libraryDescription
117 | url siteUrl
118 |
119 | // Set your license
120 | licenses {
121 | license {
122 | name licenseName
123 | url licenseUrl
124 | }
125 | }
126 | developers {
127 | developer {
128 | id developerId
129 | name developerName
130 | email developerEmail
131 | }
132 | }
133 | scm {
134 | connection gitUrl
135 | developerConnection gitUrl
136 | url siteUrl
137 |
138 | }
139 | }
140 | }
141 | }
142 | }
143 |
144 | task sourcesJar(type: Jar) {
145 | from android.sourceSets.main.java.srcDirs
146 | classifier = 'sources'
147 | }
148 |
149 | artifacts {
150 | archives sourcesJar
151 | }
152 |
--------------------------------------------------------------------------------
/connectionbuddy/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/zeljkoplesac/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 |
--------------------------------------------------------------------------------
/connectionbuddy/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/connectionbuddy/src/main/java/com/zplesac/connectionbuddy/ConnectionBuddy.java:
--------------------------------------------------------------------------------
1 | package com.zplesac.connectionbuddy;
2 |
3 | import android.content.BroadcastReceiver;
4 | import android.content.Context;
5 | import android.content.Intent;
6 | import android.content.IntentFilter;
7 | import android.content.pm.PackageManager;
8 | import android.net.ConnectivityManager;
9 | import android.net.NetworkInfo;
10 | import android.net.wifi.ScanResult;
11 | import android.net.wifi.WifiConfiguration;
12 | import android.net.wifi.WifiInfo;
13 | import android.net.wifi.WifiManager;
14 | import android.os.Bundle;
15 | import android.os.Handler;
16 | import android.os.Looper;
17 | import android.support.annotation.NonNull;
18 | import android.support.annotation.Nullable;
19 | import android.support.annotation.RequiresPermission;
20 | import android.support.v4.app.ActivityCompat;
21 | import android.support.v4.content.ContextCompat;
22 | import android.telephony.TelephonyManager;
23 |
24 | import com.zplesac.connectionbuddy.interfaces.ConnectivityChangeListener;
25 | import com.zplesac.connectionbuddy.interfaces.NetworkRequestCheckListener;
26 | import com.zplesac.connectionbuddy.interfaces.WifiConnectivityListener;
27 | import com.zplesac.connectionbuddy.models.ConnectivityEvent;
28 | import com.zplesac.connectionbuddy.models.ConnectivityState;
29 | import com.zplesac.connectionbuddy.models.ConnectivityStrength;
30 | import com.zplesac.connectionbuddy.models.ConnectivityType;
31 |
32 | import java.io.IOException;
33 | import java.net.HttpURLConnection;
34 | import java.net.URL;
35 | import java.util.HashMap;
36 | import java.util.List;
37 | import java.util.Map;
38 | import java.util.concurrent.Executor;
39 | import java.util.concurrent.ExecutorService;
40 | import java.util.concurrent.Executors;
41 |
42 | import static android.Manifest.permission.ACCESS_COARSE_LOCATION;
43 | import static android.Manifest.permission.ACCESS_FINE_LOCATION;
44 |
45 | /**
46 | * Created by Željko Plesac on 06/10/14.
47 | */
48 | public class ConnectionBuddy {
49 |
50 | private static final String HEADER_KEY_USER_AGENT = "User-Agent";
51 |
52 | private static final String HEADER_VALUE_USER_AGENT = "Android";
53 |
54 | private static final String HEADER_KEY_CONNECTION = "Connection";
55 |
56 | private static final String HEADER_VALUE_CONNECTION = "close";
57 |
58 | private static final String NETWORK_CHECK_URL = "http://clients3.google.com/generate_204";
59 |
60 | private static final int CONNECTION_TIMEOUT = 1500;
61 |
62 | private static volatile ConnectionBuddy instance;
63 |
64 | private Map networkReceiversHashMap = new HashMap<>();
65 |
66 | private WifiScanResultReceiver wifiScanResultReceiver;
67 |
68 | private WifiConnectionStateChangedReceiver wifiConnectionStateChangedReceiver;
69 |
70 | private ConnectionBuddyConfiguration configuration;
71 |
72 | private ExecutorService executor;
73 |
74 | protected ConnectionBuddy() {
75 | // empty constructor
76 | }
77 |
78 | /**
79 | * Get current library instance.
80 | *
81 | * @return Current library instance.
82 | */
83 | public static ConnectionBuddy getInstance() {
84 | if (instance == null) {
85 | synchronized (ConnectionBuddy.class) {
86 | if (instance == null) {
87 | instance = new ConnectionBuddy();
88 | }
89 | }
90 | }
91 | return instance;
92 | }
93 |
94 | /**
95 | * Initialize this instance with provided configuration.
96 | *
97 | * @param configuration ConnectionBuddy configuration which is used in instance.
98 | */
99 | public synchronized void init(ConnectionBuddyConfiguration configuration) {
100 | if (configuration == null) {
101 | throw new IllegalArgumentException();
102 | }
103 | if (this.configuration == null) {
104 | this.configuration = configuration;
105 | }
106 | }
107 |
108 | public ConnectionBuddyConfiguration getConfiguration() {
109 | return configuration;
110 | }
111 |
112 | /**
113 | * Register for network connectivity events. Must be called separately for each activity/context, and will use
114 | * global configuration to determine if we should notify the callback immediately about current network connection
115 | * state.
116 | *
117 | * @param object Object which is registered to network change receiver.
118 | * @param listener Callback listener.
119 | */
120 | public void registerForConnectivityEvents(Object object, ConnectivityChangeListener listener) {
121 | registerForConnectivityEvents(object, configuration.isNotifyImmediately(), listener);
122 | }
123 |
124 | /**
125 | * Register for network connectivity events. Must be called separately for each activity/context.
126 | *
127 | * @param object Object which is registered to network change receiver.
128 | * @param notifyImmediately Indicates should we immediately notify the callback about current network connection state.
129 | * @param listener Callback listener.
130 | */
131 | public void registerForConnectivityEvents(Object object, boolean notifyImmediately, ConnectivityChangeListener listener) {
132 | if (!isAlreadyRegistered(object)) {
133 |
134 | boolean hasConnection = hasNetworkConnection();
135 | ConnectionBuddyCache cache = configuration.getNetworkEventsCache();
136 |
137 | if (cache.isLastNetworkStateStored(object)
138 | && cache.getLastNetworkState(object) != hasConnection) {
139 | cache.setLastNetworkState(object, hasConnection);
140 |
141 | if (notifyImmediately) {
142 | notifyConnectionChange(hasConnection, listener);
143 | }
144 | } else if (!cache.isLastNetworkStateStored(object)) {
145 | cache.setLastNetworkState(object, hasConnection);
146 | if (notifyImmediately) {
147 | notifyConnectionChange(hasConnection, listener);
148 | }
149 | }
150 |
151 | IntentFilter filter = new IntentFilter();
152 | filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
153 | filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
154 |
155 | NetworkChangeReceiver receiver = new NetworkChangeReceiver(object, listener);
156 |
157 | networkReceiversHashMap.put(object.toString(), receiver);
158 | configuration.getContext().registerReceiver(receiver, filter);
159 | }
160 | }
161 |
162 | /**
163 | * @param object Activity or fragment, which is registered for connectivity state changes.
164 | * @return true if the object is already registered to a network change receiver
165 | */
166 | private boolean isAlreadyRegistered(Object object) {
167 | return networkReceiversHashMap.containsKey(object.toString());
168 | }
169 |
170 | /**
171 | * Clears network events cache. Has to be called in onCreate() lifecycle methods for activities and fragments, so that we always reset
172 | * the previous connection state.
173 | *
174 | * @param object Activity or fragment, which is registered for connectivity state changes.
175 | */
176 | public void clearNetworkCache(Object object) {
177 | configuration.getNetworkEventsCache().clearLastNetworkState(object);
178 | }
179 |
180 | /**
181 | * Clears network events cache. Has to be called in onCreate() lifecycle methods for activities and fragments, so that we always reset
182 | * the previous connection state.
183 | *
184 | * @param object Activity or fragment, which is registered for connectivity state changes.
185 | * @param savedInstanceState Activity or fragments bundle.
186 | */
187 | public void clearNetworkCache(Object object, @Nullable Bundle savedInstanceState) {
188 | if (savedInstanceState != null) {
189 | configuration.getNetworkEventsCache().clearLastNetworkState(object);
190 | }
191 | }
192 |
193 | /**
194 | * Notify the current state of connection to provided interface listener.
195 | *
196 | * @param hasConnection Current state of internet connection.
197 | * @param listener Interface listener which has to be notified about current internet connection state.
198 | */
199 | public void notifyConnectionChange(boolean hasConnection, final ConnectivityChangeListener listener) {
200 | if (hasConnection) {
201 | final ConnectivityEvent event = new ConnectivityEvent(new ConnectivityState(ConnectivityState.CONNECTED), getNetworkType(),
202 | getSignalStrength());
203 |
204 | if (configuration.isNotifyOnlyReliableEvents()) {
205 | testNetworkRequest(new NetworkRequestCheckListener() {
206 | @Override
207 | public void onResponseObtained() {
208 | handleActiveInternetConnection(event, listener);
209 | }
210 |
211 | @Override
212 | public void onNoResponse() {
213 | // No response was obtained from test network request, which means that we have active internet connection,
214 | // but user can't perform network requests (I.E. he uses mobile network and doesn't have enough credit.
215 | // Don't notify about this connection event.
216 | }
217 | });
218 | } else {
219 | handleActiveInternetConnection(event, listener);
220 | }
221 | } else {
222 | listener.onConnectionChange(new ConnectivityEvent(
223 | new ConnectivityState(ConnectivityState.DISCONNECTED),
224 | new ConnectivityType(ConnectivityType.NONE),
225 | new ConnectivityStrength(ConnectivityStrength.UNDEFINED)));
226 | }
227 | }
228 |
229 | /**
230 | * Determine if we should notify the listener about active internet connection, based on configuration values.
231 | *
232 | * @param event ConnectivityEvent which will be posted to listener.
233 | * @param listener ConnectivityChangeListener which will receive ConnectivityEvent.
234 | */
235 | private void handleActiveInternetConnection(ConnectivityEvent event, ConnectivityChangeListener listener) {
236 | // handle only if signal strength is above or equal minimum defined strength
237 | if (event.getStrength().getValue() >= configuration.getMinimumSignalStrength().getValue()) {
238 | if (event.getType().getValue() == ConnectivityType.MOBILE && configuration.isRegisteredForMobileNetworkChanges()) {
239 | listener.onConnectionChange(event);
240 | } else if (event.getType().getValue() == ConnectivityType.WIFI && configuration.isRegisteredForWiFiChanges()) {
241 | listener.onConnectionChange(event);
242 | }
243 | }
244 | }
245 |
246 | /**
247 | * Unregister from network connectivity events.
248 | *
249 | * @param object Object which we want to unregister from connectivity changes.
250 | */
251 | public void unregisterFromConnectivityEvents(Object object) {
252 | NetworkChangeReceiver networkChangeReceiver = networkReceiversHashMap.get(object.toString());
253 | configuration.getContext().unregisterReceiver(networkChangeReceiver);
254 | networkReceiversHashMap.remove(object.toString());
255 |
256 | if (wifiScanResultReceiver != null) {
257 | configuration.getContext().unregisterReceiver(wifiScanResultReceiver);
258 | wifiScanResultReceiver = null;
259 | }
260 |
261 | if (wifiConnectionStateChangedReceiver != null) {
262 | configuration.getContext().unregisterReceiver(wifiConnectionStateChangedReceiver);
263 | wifiConnectionStateChangedReceiver = null;
264 | }
265 |
266 | networkChangeReceiver = null;
267 | }
268 |
269 | /**
270 | * Utility method which checks current network connection state.
271 | *
272 | * @return True if we have active network connection, false otherwise.
273 | */
274 | public boolean hasNetworkConnection() {
275 | if (configuration.getConnectivityManager() == null) {
276 | throw new IllegalStateException("Connectivity manager is null, library was not properly initialized!");
277 | }
278 |
279 | NetworkInfo networkInfo = configuration.getConnectivityManager().getActiveNetworkInfo();
280 |
281 | return networkInfo != null && networkInfo.isConnected();
282 | }
283 |
284 | /**
285 | * Utility method which checks current network connection state, but will also try to perform test network request, in order
286 | * to determine if user can actually perform any network operation.
287 | *
288 | * @param listener Callback listener.
289 | */
290 | public void hasNetworkConnection(NetworkRequestCheckListener listener) {
291 | if (hasNetworkConnection()) {
292 | testNetworkRequest(listener);
293 | } else {
294 | listener.onNoResponse();
295 | }
296 | }
297 |
298 | /**
299 | * Try to perform test network request to NETWORK_CHECK_URL. This way, we can determine if use is in fact capable of performing
300 | * any network operations when he has active internet connection.
301 | *
302 | * @param listener Callback listener.
303 | */
304 | private void testNetworkRequest(final NetworkRequestCheckListener listener) {
305 | if (executor == null) {
306 | executor = Executors.newFixedThreadPool(getConfiguration().getTestNetworkRequestExecutorSize());
307 | }
308 |
309 | executor.execute(new Runnable() {
310 | @Override
311 | public void run() {
312 | try {
313 | HttpURLConnection httpURLConnection = (HttpURLConnection)
314 | (new URL(NETWORK_CHECK_URL).openConnection());
315 | httpURLConnection.setRequestProperty(HEADER_KEY_USER_AGENT, HEADER_VALUE_USER_AGENT);
316 | httpURLConnection.setRequestProperty(HEADER_KEY_CONNECTION, HEADER_VALUE_CONNECTION);
317 | httpURLConnection.setConnectTimeout(CONNECTION_TIMEOUT);
318 | httpURLConnection.connect();
319 |
320 | if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT
321 | && httpURLConnection.getContentLength() == 0) {
322 | callbackExecutor.execute(new Runnable() {
323 | @Override
324 | public void run() {
325 | listener.onResponseObtained();
326 | }
327 | });
328 | } else {
329 | callbackExecutor.execute(new Runnable() {
330 | @Override
331 | public void run() {
332 | listener.onNoResponse();
333 | }
334 | });
335 | }
336 | } catch (IOException e) {
337 | callbackExecutor.execute(new Runnable() {
338 | @Override
339 | public void run() {
340 | listener.onNoResponse();
341 | }
342 | });
343 | }
344 | }
345 | });
346 | }
347 |
348 | /**
349 | * Get network connection type from ConnectivityManager.
350 | *
351 | * @return ConnectivityType which is available on current device.
352 | */
353 | public ConnectivityType getNetworkType() {
354 | if (configuration.getConnectivityManager() == null) {
355 | throw new IllegalStateException("Connectivity manager is null, library was not properly initialized!");
356 | }
357 |
358 | NetworkInfo networkInfo = configuration.getConnectivityManager().getActiveNetworkInfo();
359 |
360 | if (networkInfo != null && networkInfo.isConnected()) {
361 | switch (networkInfo.getType()) {
362 | case ConnectivityManager.TYPE_WIFI:
363 | return new ConnectivityType(ConnectivityType.WIFI);
364 | case ConnectivityManager.TYPE_MOBILE:
365 | return new ConnectivityType(ConnectivityType.MOBILE);
366 | default:
367 | return new ConnectivityType(ConnectivityType.UNDEFINED);
368 | }
369 | } else {
370 | return new ConnectivityType(ConnectivityType.NONE);
371 | }
372 | }
373 |
374 | /**
375 | * Get signal strength of current network connection.
376 | *
377 | * @return ConnectivityStrength object for current network connection.
378 | */
379 | public ConnectivityStrength getSignalStrength() {
380 | if (configuration.getConnectivityManager() == null) {
381 | throw new IllegalStateException("Connectivity manager is null, library was not properly initialized!");
382 | }
383 |
384 | NetworkInfo networkInfo = configuration.getConnectivityManager().getActiveNetworkInfo();
385 |
386 | if (networkInfo != null && networkInfo.isConnected()) {
387 | if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
388 | return getWifiStrength();
389 | } else {
390 | return getMobileConnectionStrength(networkInfo);
391 | }
392 | } else {
393 | return new ConnectivityStrength(ConnectivityStrength.UNDEFINED);
394 | }
395 | }
396 |
397 | /**
398 | * Get WiFi signal strength.
399 | */
400 | private ConnectivityStrength getWifiStrength() {
401 | WifiManager wifiManager = (WifiManager) configuration.getContext().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
402 | WifiInfo wifiInfo = wifiManager.getConnectionInfo();
403 |
404 | if (wifiInfo != null) {
405 | int level = WifiManager.calculateSignalLevel(wifiInfo.getRssi(),
406 | ConnectionBuddyConfiguration.SIGNAL_STRENGTH_NUMBER_OF_LEVELS);
407 |
408 | switch (level) {
409 | case 0:
410 | return new ConnectivityStrength(ConnectivityStrength.POOR);
411 | case 1:
412 | return new ConnectivityStrength(ConnectivityStrength.GOOD);
413 | case 2:
414 | return new ConnectivityStrength(ConnectivityStrength.EXCELLENT);
415 | default:
416 | return new ConnectivityStrength(ConnectivityStrength.UNDEFINED);
417 | }
418 | } else {
419 | return new ConnectivityStrength(ConnectivityStrength.UNDEFINED);
420 | }
421 | }
422 |
423 | /**
424 | * Get mobile network signal strength.
425 | */
426 | private ConnectivityStrength getMobileConnectionStrength(NetworkInfo info) {
427 | if (info != null && info.getType() == ConnectivityManager.TYPE_MOBILE) {
428 | switch (info.getSubtype()) {
429 | case TelephonyManager.NETWORK_TYPE_1xRTT:
430 | return new ConnectivityStrength(ConnectivityStrength.POOR);
431 | case TelephonyManager.NETWORK_TYPE_CDMA:
432 | return new ConnectivityStrength(ConnectivityStrength.POOR);
433 | case TelephonyManager.NETWORK_TYPE_EDGE:
434 | return new ConnectivityStrength(ConnectivityStrength.POOR);
435 | case TelephonyManager.NETWORK_TYPE_EVDO_0:
436 | return new ConnectivityStrength(ConnectivityStrength.GOOD);
437 | case TelephonyManager.NETWORK_TYPE_EVDO_A:
438 | return new ConnectivityStrength(ConnectivityStrength.GOOD);
439 | case TelephonyManager.NETWORK_TYPE_GPRS:
440 | return new ConnectivityStrength(ConnectivityStrength.EXCELLENT);
441 | case TelephonyManager.NETWORK_TYPE_HSDPA:
442 | return new ConnectivityStrength(ConnectivityStrength.EXCELLENT);
443 | case TelephonyManager.NETWORK_TYPE_HSPA:
444 | return new ConnectivityStrength(ConnectivityStrength.EXCELLENT);
445 | case TelephonyManager.NETWORK_TYPE_HSUPA:
446 | return new ConnectivityStrength(ConnectivityStrength.EXCELLENT);
447 | case TelephonyManager.NETWORK_TYPE_UMTS:
448 | return new ConnectivityStrength(ConnectivityStrength.EXCELLENT);
449 | case TelephonyManager.NETWORK_TYPE_EHRPD:
450 | return new ConnectivityStrength(ConnectivityStrength.EXCELLENT);
451 | case TelephonyManager.NETWORK_TYPE_EVDO_B:
452 | return new ConnectivityStrength(ConnectivityStrength.EXCELLENT);
453 | case TelephonyManager.NETWORK_TYPE_HSPAP:
454 | return new ConnectivityStrength(ConnectivityStrength.EXCELLENT);
455 | case TelephonyManager.NETWORK_TYPE_IDEN:
456 | return new ConnectivityStrength(ConnectivityStrength.EXCELLENT);
457 | case TelephonyManager.NETWORK_TYPE_LTE:
458 | return new ConnectivityStrength(ConnectivityStrength.EXCELLENT);
459 | default:
460 | return new ConnectivityStrength(ConnectivityStrength.UNDEFINED);
461 | }
462 | } else {
463 | return new ConnectivityStrength(ConnectivityStrength.UNDEFINED);
464 | }
465 | }
466 |
467 | /**
468 | * Checks if user is on is in roaming.
469 | *
470 | * @return boolean variable, which describes if user is in roaming.
471 | */
472 | public boolean isOnRoaming() {
473 | NetworkInfo networkInfo = getConfiguration().getConnectivityManager().getActiveNetworkInfo();
474 | return networkInfo != null && networkInfo.isRoaming();
475 | }
476 |
477 | /**
478 | * Connects to the WiFi configuration with given {@param networkSsid} as network configuration's SSID and {@param networkPassword} as
479 | * network configurations's password.
480 | * {@link android.Manifest.permission#ACCESS_COARSE_LOCATION} and {@link android.Manifest.permission#ACCESS_FINE_LOCATION} permissions
481 | * are required in order to initiate new access point scan.
482 | *
483 | * @param networkSsid WifiConfiguration network SSID.
484 | * @param networkPassword WifiConfiguration network password.
485 | */
486 | @RequiresPermission(allOf = {ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION})
487 | public void connectToWifiConfiguration(Context context, String networkSsid, String networkPassword, boolean disconnectIfNotFound)
488 | throws SecurityException {
489 | connectToWifiConfiguration(context, networkSsid, networkPassword, disconnectIfNotFound, null);
490 | }
491 |
492 | /**
493 | * Connects to the WiFi configuration with given {@param networkSsid} as network configuration's SSID and {@param networkPassword} as
494 | * network configurations's password and optionaly notifies about the result if {@param listener} has defined value.
495 | * {@link android.Manifest.permission#ACCESS_COARSE_LOCATION} and {@link android.Manifest.permission#ACCESS_FINE_LOCATION} permissions
496 | * are required in order to initiate new access point scan.
497 | *
498 | * @param networkSsid WifiConfiguration network SSID.
499 | * @param networkPassword WifiConfiguration network password.
500 | * @param listener Callback listener.
501 | */
502 | @RequiresPermission(allOf = {ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION})
503 | public void connectToWifiConfiguration(Context context, String networkSsid, String networkPassword, boolean disconnectIfNotFound,
504 | WifiConnectivityListener listener) throws SecurityException {
505 | // Check if permissions have been granted
506 | if (ContextCompat.checkSelfPermission(context, ACCESS_COARSE_LOCATION)
507 | != PackageManager.PERMISSION_GRANTED
508 | || ActivityCompat.checkSelfPermission(context, ACCESS_FINE_LOCATION)
509 | != PackageManager.PERMISSION_GRANTED) {
510 | throw new SecurityException("ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION permissions have not been granted by the user.");
511 | } else {
512 | WifiManager wifiManager = (WifiManager) getConfiguration().getContext().getApplicationContext()
513 | .getSystemService(Context.WIFI_SERVICE);
514 | if (!wifiManager.isWifiEnabled()) {
515 | wifiManager.setWifiEnabled(true);
516 | }
517 |
518 | // there is no wifi configuration with given data in list of configured networks. Initialize scan for access points.
519 | wifiScanResultReceiver = new WifiScanResultReceiver(wifiManager, networkSsid, networkPassword, disconnectIfNotFound, listener);
520 | configuration.getContext()
521 | .registerReceiver(wifiScanResultReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
522 | wifiManager.startScan();
523 | }
524 | }
525 |
526 | /**
527 | * Called from WifiScanResultReceiver, when WiFiManager has finished scanning for active access points. Note that SSIDs of the
528 | * configured networks are enclosed in double quotes, whilst the SSIDs returned in ScanResults are not.
529 | */
530 | private class WifiScanResultReceiver extends BroadcastReceiver {
531 |
532 | private WifiManager wifiManager;
533 |
534 | private WifiConnectivityListener listener;
535 |
536 | private String networkSsid;
537 |
538 | private String networkPassword;
539 |
540 | private boolean disconnectIfNotFound;
541 |
542 | WifiScanResultReceiver(WifiManager wifiManager, String networkSsid,
543 | String networkPassword, boolean disconnectIfNotFound, WifiConnectivityListener listener) {
544 | this.wifiManager = wifiManager;
545 | this.listener = listener;
546 | this.networkSsid = networkSsid;
547 | this.networkPassword = networkPassword;
548 | this.disconnectIfNotFound = disconnectIfNotFound;
549 | }
550 |
551 | @Override
552 | public void onReceive(Context context, Intent intent) {
553 | // unregister receiver, so that we are only notified once about the results
554 | context.unregisterReceiver(this);
555 |
556 | if (wifiManager != null && wifiManager.getScanResults() != null && wifiManager.getScanResults().size() > 0) {
557 | for (ScanResult scanResult : wifiManager.getScanResults()) {
558 | if (scanResult.SSID != null && scanResult.SSID.equals(networkSsid)) {
559 |
560 | int networkId;
561 | WifiConfiguration wifiConfiguration = checkIfWifiAlreadyConfigured(wifiManager.getConfiguredNetworks());
562 |
563 | if (wifiConfiguration == null) {
564 | wifiConfiguration = new WifiConfiguration();
565 | wifiConfiguration.SSID = "\"" + networkSsid + "\"";
566 | wifiConfiguration.preSharedKey = "\"" + networkPassword + "\"";
567 | networkId = wifiManager.addNetwork(wifiConfiguration);
568 | } else {
569 | // Set new password
570 | wifiConfiguration.preSharedKey = "\"" + networkPassword + "\"";
571 | networkId = wifiConfiguration.networkId;
572 | }
573 |
574 | // there is no wifi configuration with given data in list of configured networks. Initialize scan for access points.
575 | wifiConnectionStateChangedReceiver = new WifiConnectionStateChangedReceiver(networkSsid, wifiManager,
576 | disconnectIfNotFound, listener);
577 | configuration.getContext()
578 | .registerReceiver(wifiConnectionStateChangedReceiver,
579 | new IntentFilter(WifiManager.NETWORK_STATE_CHANGED_ACTION));
580 | wifiManager.enableNetwork(networkId, true);
581 | return;
582 | }
583 | }
584 | }
585 |
586 | if (listener != null) {
587 | listener.onNotFound();
588 | }
589 | }
590 |
591 | private WifiConfiguration checkIfWifiAlreadyConfigured(List wifiConfigurationList) {
592 | if (wifiConfigurationList != null && !wifiConfigurationList.isEmpty()) {
593 | for (WifiConfiguration configuration : wifiConfigurationList) {
594 | if (configuration.SSID != null && configuration.SSID.equals("\"" + networkSsid + "\"")) {
595 | return configuration;
596 | }
597 | }
598 | }
599 | return null;
600 | }
601 | }
602 |
603 | private class WifiConnectionStateChangedReceiver extends BroadcastReceiver {
604 |
605 | private WifiConnectivityListener listener;
606 |
607 | private String networkSsid;
608 |
609 | private WifiManager wifiManager;
610 |
611 | private boolean disconnectIfNotFound;
612 |
613 | WifiConnectionStateChangedReceiver(String networkSsid, @NonNull WifiManager wifiManager, boolean disconnectIfNotFound,
614 | WifiConnectivityListener listener) {
615 | this.listener = listener;
616 | this.networkSsid = networkSsid;
617 | this.wifiManager = wifiManager;
618 | this.disconnectIfNotFound = disconnectIfNotFound;
619 | }
620 |
621 | @Override
622 | public void onReceive(Context context, Intent intent) {
623 | // unregister receiver, so that we are only notified once about the results
624 | context.unregisterReceiver(this);
625 |
626 | NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
627 |
628 | if (listener != null) {
629 | if (networkInfo.isConnected() && wifiManager.getConnectionInfo().getSSID().replace("\"", "").equals(networkSsid)) {
630 | listener.onConnected();
631 | } else {
632 | if (disconnectIfNotFound) {
633 | wifiManager.disconnect();
634 | }
635 |
636 | listener.onNotFound();
637 | }
638 | }
639 | }
640 | }
641 |
642 | /**
643 | * Callback executor, which will post the runnable on main thread.
644 | */
645 | private Executor callbackExecutor = new Executor() {
646 |
647 | Handler mainHandler = new Handler(Looper.getMainLooper());
648 |
649 | @Override
650 | public void execute(Runnable command) {
651 | mainHandler.post(command);
652 | }
653 | };
654 | }
655 |
--------------------------------------------------------------------------------
/connectionbuddy/src/main/java/com/zplesac/connectionbuddy/ConnectionBuddyCache.java:
--------------------------------------------------------------------------------
1 | package com.zplesac.connectionbuddy;
2 |
3 | public interface ConnectionBuddyCache {
4 |
5 | /**
6 | * Fetches last stored network connection state for provided object.
7 | * @param object Activity or fragment for which we want to fetch last network connection state.
8 | * @return Boolean property which indicates whether provided object had network connection when
9 | * it was stored in cache.
10 | */
11 | boolean getLastNetworkState(Object object);
12 |
13 | /**
14 | * Store last network connection state for provided object.
15 | * @param object Activity or fragment for which we want to cache network connectivity state.
16 | * @param isActive Does provided object has active network connection.
17 | */
18 | void setLastNetworkState(Object object, boolean isActive);
19 |
20 | /**
21 | * Clear stored network connectivity state for provided object.
22 | * @param object Activity or fragment for which we want to delete last stored state.
23 | */
24 | void clearLastNetworkState(Object object);
25 |
26 | /**
27 | * Check whether we have stored network connectivity state for provided object.
28 | * @param object Activity or fragment for which we want to check if we have stored last network connectivity state.
29 | * @return Boolean property which indicates do we have stored last network state for provided object.
30 | */
31 | boolean isLastNetworkStateStored(Object object);
32 | }
33 |
--------------------------------------------------------------------------------
/connectionbuddy/src/main/java/com/zplesac/connectionbuddy/ConnectionBuddyConfiguration.java:
--------------------------------------------------------------------------------
1 | package com.zplesac.connectionbuddy;
2 |
3 | import com.zplesac.connectionbuddy.models.ConnectivityStrength;
4 |
5 | import android.content.Context;
6 | import android.net.ConnectivityManager;
7 |
8 | /**
9 | * Created by Željko Plesac on 09/10/15.
10 | * Configuration class for ConnectionBuddy instance. Use this to customize the library behaviour.
11 | */
12 | public class ConnectionBuddyConfiguration {
13 |
14 | public static final int SIGNAL_STRENGTH_NUMBER_OF_LEVELS = 3;
15 |
16 | public static final int DEFAULT_NETWORK_EXECUTOR_THREAD_SIZE = 4;
17 |
18 | private Context context;
19 |
20 | private boolean registeredForWiFiChanges;
21 |
22 | private boolean registeredForMobileNetworkChanges;
23 |
24 | private ConnectivityStrength minimumSignalStrength;
25 |
26 | private ConnectionBuddyCache networkEventsCache;
27 |
28 | private boolean notifyImmediately;
29 |
30 | private ConnectivityManager connectivityManager;
31 |
32 | private boolean notifyOnlyReliableEvents;
33 |
34 | private int testNetworkRequestExecutorSize;
35 |
36 | private ConnectionBuddyConfiguration(Builder builder) {
37 | this.context = builder.context;
38 | this.registeredForMobileNetworkChanges = builder.registerForMobileNetworkChanges;
39 | this.registeredForWiFiChanges = builder.registerForWiFiChanges;
40 | this.minimumSignalStrength = builder.minimumSignalStrength;
41 | this.notifyImmediately = builder.notifyImmediately;
42 | this.notifyOnlyReliableEvents = builder.notifyOnlyReliableEvents;
43 | this.connectivityManager = (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
44 | this.testNetworkRequestExecutorSize = builder.testNetworkRequestExecutorSize;
45 |
46 | if (builder.cache != null) {
47 | this.networkEventsCache = builder.cache;
48 | } else {
49 | this.networkEventsCache = new LruConnectionBuddyCache();
50 | }
51 | }
52 |
53 | public Context getContext() {
54 | return context;
55 | }
56 |
57 | public boolean isRegisteredForWiFiChanges() {
58 | return registeredForWiFiChanges;
59 | }
60 |
61 | public boolean isRegisteredForMobileNetworkChanges() {
62 | return registeredForMobileNetworkChanges;
63 | }
64 |
65 | public ConnectivityStrength getMinimumSignalStrength() {
66 | return minimumSignalStrength;
67 | }
68 |
69 | public ConnectionBuddyCache getNetworkEventsCache() {
70 | return networkEventsCache;
71 | }
72 |
73 | public boolean isNotifyImmediately() {
74 | return notifyImmediately;
75 | }
76 |
77 | public ConnectivityManager getConnectivityManager() {
78 | return connectivityManager;
79 | }
80 |
81 | public boolean isNotifyOnlyReliableEvents() {
82 | return notifyOnlyReliableEvents;
83 | }
84 |
85 | public int getTestNetworkRequestExecutorSize() {
86 | return testNetworkRequestExecutorSize;
87 | }
88 |
89 | public static class Builder {
90 |
91 | private Context context;
92 |
93 | /**
94 | * Boolean value which defines should we register for WiFi network changes.
95 | * Default value is set to true.
96 | */
97 | private boolean registerForWiFiChanges = true;
98 |
99 | /**
100 | * Boolean value which defines should we register for mobile network changes.
101 | * Default value is set to true.
102 | */
103 | private boolean registerForMobileNetworkChanges = true;
104 |
105 | /**
106 | * Define minimum signal strength for which we should call callback listener.
107 | * Default is set to ConnectivityStrength.UNDEFINED.
108 | */
109 | private ConnectivityStrength minimumSignalStrength = new ConnectivityStrength(ConnectivityStrength.UNDEFINED);
110 |
111 | /**
112 | * Boolean value which defines do we want to notify the listener about current network connection state
113 | * immediately after the listener has been registered.
114 | * Default is set to true.
115 | */
116 | private boolean notifyImmediately = true;
117 |
118 | /**
119 | * Cache which is used for storing network events.
120 | */
121 | private ConnectionBuddyCache cache;
122 |
123 | /**
124 | * Boolean value which defines do we want to use reliable network events. This means that if we have active internet connection,
125 | * it will try to execute test network request to determine if user is capable of any network operation.
126 | * Default is set to false.
127 | */
128 | private boolean notifyOnlyReliableEvents = false;
129 |
130 | /**
131 | * Default network request executor service size.
132 | */
133 | private int testNetworkRequestExecutorSize = DEFAULT_NETWORK_EXECUTOR_THREAD_SIZE;
134 |
135 | public Builder(Context context) {
136 | this.context = context.getApplicationContext();
137 | }
138 |
139 | public Builder registerForWiFiChanges(boolean shouldRegister) {
140 | this.registerForWiFiChanges = shouldRegister;
141 | return this;
142 | }
143 |
144 | public Builder registerForMobileNetworkChanges(boolean shouldRegister) {
145 | this.registerForMobileNetworkChanges = shouldRegister;
146 | return this;
147 | }
148 |
149 | public Builder setMinimumSignalStrength(ConnectivityStrength minimumSignalStrength) {
150 | this.minimumSignalStrength = minimumSignalStrength;
151 | return this;
152 | }
153 |
154 | public Builder setNotifyImmediately(boolean shouldNotify) {
155 | this.notifyImmediately = shouldNotify;
156 | return this;
157 | }
158 |
159 | public Builder notifyOnlyReliableEvents(boolean shouldNotify) {
160 | this.notifyOnlyReliableEvents = shouldNotify;
161 | return this;
162 | }
163 |
164 | public Builder setNetworkEventsCache(ConnectionBuddyCache cache) {
165 | this.cache = cache;
166 | return this;
167 | }
168 |
169 | public Builder setTestNetworkRequestExecutorSize(int testNetworkRequestExecutorSize) {
170 | this.testNetworkRequestExecutorSize = testNetworkRequestExecutorSize;
171 | return this;
172 | }
173 |
174 | public ConnectionBuddyConfiguration build() {
175 | return new ConnectionBuddyConfiguration(this);
176 | }
177 | }
178 | }
179 |
--------------------------------------------------------------------------------
/connectionbuddy/src/main/java/com/zplesac/connectionbuddy/LruConnectionBuddyCache.java:
--------------------------------------------------------------------------------
1 | package com.zplesac.connectionbuddy;
2 |
3 | import android.support.v4.util.LruCache;
4 |
5 | class LruConnectionBuddyCache implements ConnectionBuddyCache {
6 |
7 | private final int kbSize = 1024;
8 |
9 | private final int memoryPart = 10;
10 |
11 | /**
12 | * Get max available VM memory, exceeding this amount will throw an
13 | * OutOfMemory exception. Stored in kilobytes as LruCache takes an
14 | * int in its constructor.
15 | */
16 | private final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / kbSize);
17 |
18 | private LruCache cache;
19 |
20 | LruConnectionBuddyCache() {
21 | // Use 1/10th of the available memory for this memory cache.
22 | this.cache = new LruCache<>(maxMemory / memoryPart);
23 | }
24 |
25 | @Override
26 | public boolean getLastNetworkState(Object object) {
27 | if (isLastNetworkStateStored(object)) {
28 | return cache.get(object.toString());
29 | }
30 |
31 | return true;
32 | }
33 |
34 | @Override
35 | public void setLastNetworkState(Object object, boolean isActive) {
36 | cache.put(object.toString(), isActive);
37 | }
38 |
39 | @Override
40 | public void clearLastNetworkState(Object object) {
41 | cache.remove(object.toString());
42 | }
43 |
44 | @Override
45 | public boolean isLastNetworkStateStored(Object object) {
46 | return cache.snapshot().containsKey(object.toString());
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/connectionbuddy/src/main/java/com/zplesac/connectionbuddy/NetworkChangeReceiver.java:
--------------------------------------------------------------------------------
1 | package com.zplesac.connectionbuddy;
2 |
3 | import com.zplesac.connectionbuddy.interfaces.ConnectivityChangeListener;
4 |
5 | import android.content.BroadcastReceiver;
6 | import android.content.Context;
7 | import android.content.Intent;
8 |
9 |
10 | /**
11 | * Broadcast receiver that listens to network connectivity changes.
12 | */
13 | class NetworkChangeReceiver extends BroadcastReceiver {
14 |
15 | private Object object;
16 |
17 | private ConnectivityChangeListener mCallback;
18 |
19 | NetworkChangeReceiver(Object object, ConnectivityChangeListener mCallback) {
20 | this.object = object;
21 | this.mCallback = mCallback;
22 | }
23 |
24 | /**
25 | * Receive network connectivity change event.
26 | */
27 | @Override
28 | public void onReceive(Context context, Intent intent) {
29 | boolean hasConnectivity = ConnectionBuddy.getInstance().hasNetworkConnection();
30 | ConnectionBuddyCache cache = ConnectionBuddy.getInstance().getConfiguration().getNetworkEventsCache();
31 |
32 | if (hasConnectivity && cache.getLastNetworkState(object) != hasConnectivity) {
33 | cache.setLastNetworkState(object, hasConnectivity);
34 | ConnectionBuddy.getInstance().notifyConnectionChange(hasConnectivity, mCallback);
35 | } else if (!hasConnectivity && cache.getLastNetworkState(object) != hasConnectivity) {
36 | cache.setLastNetworkState(object, hasConnectivity);
37 | ConnectionBuddy.getInstance().notifyConnectionChange(hasConnectivity, mCallback);
38 | }
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/connectionbuddy/src/main/java/com/zplesac/connectionbuddy/activities/ConnectionBuddyActivity.java:
--------------------------------------------------------------------------------
1 | package com.zplesac.connectionbuddy.activities;
2 |
3 | import com.zplesac.connectionbuddy.ConnectionBuddy;
4 | import com.zplesac.connectionbuddy.interfaces.ConnectivityChangeListener;
5 | import com.zplesac.connectionbuddy.models.ConnectivityEvent;
6 |
7 | import android.app.Activity;
8 | import android.os.Bundle;
9 |
10 | /**
11 | * Created by Željko Plesac on 21/02/16.
12 | * Base activity for handling connectivity change events.
13 | */
14 | public class ConnectionBuddyActivity extends Activity implements ConnectivityChangeListener {
15 |
16 | @Override
17 | protected void onCreate(Bundle savedInstanceState) {
18 | super.onCreate(savedInstanceState);
19 | ConnectionBuddy.getInstance().clearNetworkCache(this, savedInstanceState);
20 | }
21 |
22 | @Override
23 | protected void onStart() {
24 | super.onStart();
25 |
26 | // Register for connectivity changes
27 | ConnectionBuddy.getInstance().registerForConnectivityEvents(this, this);
28 | }
29 |
30 | @Override
31 | protected void onStop() {
32 | // Unregister from connectivity events
33 | ConnectionBuddy.getInstance().unregisterFromConnectivityEvents(this);
34 |
35 | super.onStop();
36 | }
37 |
38 | /**
39 | * Override this method if you want to manually handle connectivity change events.
40 | *
41 | * @param event ConnectivityEvent which holds all data about network connection state.
42 | */
43 | @Override
44 | public void onConnectionChange(ConnectivityEvent event) {
45 |
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/connectionbuddy/src/main/java/com/zplesac/connectionbuddy/interfaces/ConnectivityChangeListener.java:
--------------------------------------------------------------------------------
1 | package com.zplesac.connectionbuddy.interfaces;
2 |
3 |
4 | import com.zplesac.connectionbuddy.models.ConnectivityEvent;
5 |
6 | /**
7 | * Created by Željko Plesac on 01/09/15.
8 | */
9 | public interface ConnectivityChangeListener {
10 |
11 | /**
12 | * Interface method which is called when there is change in internet connection state.
13 | *
14 | * @param event ConnectivityEvent which holds all data about network connection state.
15 | */
16 | void onConnectionChange(ConnectivityEvent event);
17 | }
18 |
--------------------------------------------------------------------------------
/connectionbuddy/src/main/java/com/zplesac/connectionbuddy/interfaces/NetworkRequestCheckListener.java:
--------------------------------------------------------------------------------
1 | package com.zplesac.connectionbuddy.interfaces;
2 |
3 | /**
4 | * Created by Željko Plesac on 09/03/16.
5 | */
6 | public interface NetworkRequestCheckListener {
7 |
8 | void onResponseObtained();
9 |
10 | void onNoResponse();
11 |
12 | }
13 |
--------------------------------------------------------------------------------
/connectionbuddy/src/main/java/com/zplesac/connectionbuddy/interfaces/WifiConnectivityListener.java:
--------------------------------------------------------------------------------
1 | package com.zplesac.connectionbuddy.interfaces;
2 |
3 | /**
4 | * Created by Željko Plesac on 14/11/16.
5 | */
6 | public interface WifiConnectivityListener {
7 |
8 | void onConnected();
9 |
10 | void onNotFound();
11 | }
12 |
--------------------------------------------------------------------------------
/connectionbuddy/src/main/java/com/zplesac/connectionbuddy/models/ConnectivityEvent.java:
--------------------------------------------------------------------------------
1 | package com.zplesac.connectionbuddy.models;
2 |
3 | import android.os.Parcel;
4 | import android.os.Parcelable;
5 |
6 | /**
7 | * Created by Željko Plesac on 23/09/15.
8 | * Connectivity event which holds all the necessary data about network connection.
9 | */
10 | public class ConnectivityEvent implements Parcelable {
11 |
12 | private ConnectivityState state;
13 |
14 | private ConnectivityType type;
15 |
16 | private ConnectivityStrength strength;
17 |
18 | public ConnectivityEvent() {
19 | }
20 |
21 | public ConnectivityEvent(ConnectivityState state, ConnectivityType type, ConnectivityStrength strength) {
22 | this.state = state;
23 | this.type = type;
24 | this.strength = strength;
25 | }
26 |
27 | public ConnectivityState getState() {
28 | return state;
29 | }
30 |
31 | public void setState(ConnectivityState state) {
32 | this.state = state;
33 | }
34 |
35 | public ConnectivityType getType() {
36 | return type;
37 | }
38 |
39 | public void setType(ConnectivityType type) {
40 | this.type = type;
41 | }
42 |
43 | public ConnectivityStrength getStrength() {
44 | return strength;
45 | }
46 |
47 | public void setStrength(ConnectivityStrength strength) {
48 | this.strength = strength;
49 | }
50 |
51 | @Override
52 | public int describeContents() {
53 | return 0;
54 | }
55 |
56 | @Override
57 | public void writeToParcel(Parcel dest, int flags) {
58 | dest.writeParcelable(this.state, flags);
59 | dest.writeParcelable(this.type, flags);
60 | dest.writeParcelable(this.strength, flags);
61 | }
62 |
63 | protected ConnectivityEvent(Parcel in) {
64 | this.state = in.readParcelable(ConnectivityState.class.getClassLoader());
65 | this.type = in.readParcelable(ConnectivityType.class.getClassLoader());
66 | this.strength = in.readParcelable(ConnectivityStrength.class.getClassLoader());
67 | }
68 |
69 | public static final Creator CREATOR = new Creator() {
70 | @Override
71 | public ConnectivityEvent createFromParcel(Parcel source) {
72 | return new ConnectivityEvent(source);
73 | }
74 |
75 | @Override
76 | public ConnectivityEvent[] newArray(int size) {
77 | return new ConnectivityEvent[size];
78 | }
79 | };
80 | }
--------------------------------------------------------------------------------
/connectionbuddy/src/main/java/com/zplesac/connectionbuddy/models/ConnectivityState.java:
--------------------------------------------------------------------------------
1 | package com.zplesac.connectionbuddy.models;
2 |
3 | import android.os.Parcel;
4 | import android.os.Parcelable;
5 | import android.support.annotation.IntDef;
6 |
7 | import java.lang.annotation.Retention;
8 | import java.lang.annotation.RetentionPolicy;
9 |
10 | /**
11 | * Created by Željko Plesac on 23/09/15.
12 | * Magic constant which defines network connection states.
13 | */
14 | public class ConnectivityState implements Parcelable {
15 |
16 | public static final int DISCONNECTED = 0;
17 |
18 | public static final int CONNECTED = 1;
19 |
20 | private final int value;
21 |
22 | public ConnectivityState(int value) {
23 | this.value = value;
24 | }
25 |
26 | @ConnectivityStateDef
27 | public int getValue() {
28 | return value;
29 | }
30 |
31 | @Retention(RetentionPolicy.SOURCE)
32 | @IntDef({
33 | DISCONNECTED,
34 | CONNECTED
35 | })
36 | public @interface ConnectivityStateDef {
37 |
38 | }
39 |
40 | @Override
41 | public int describeContents() {
42 | return 0;
43 | }
44 |
45 | @Override
46 | public void writeToParcel(Parcel dest, int flags) {
47 | dest.writeInt(this.value);
48 | }
49 |
50 | protected ConnectivityState(Parcel in) {
51 | this.value = in.readInt();
52 | }
53 |
54 | public static final Creator CREATOR = new Creator() {
55 | @Override
56 | public ConnectivityState createFromParcel(Parcel source) {
57 | return new ConnectivityState(source);
58 | }
59 |
60 | @Override
61 | public ConnectivityState[] newArray(int size) {
62 | return new ConnectivityState[size];
63 | }
64 | };
65 | }
66 |
--------------------------------------------------------------------------------
/connectionbuddy/src/main/java/com/zplesac/connectionbuddy/models/ConnectivityStrength.java:
--------------------------------------------------------------------------------
1 | package com.zplesac.connectionbuddy.models;
2 |
3 | import android.os.Parcel;
4 | import android.os.Parcelable;
5 | import android.support.annotation.IntDef;
6 |
7 | import java.lang.annotation.Retention;
8 | import java.lang.annotation.RetentionPolicy;
9 |
10 | /**
11 | * Created by Željko Plesac on 25/10/15.
12 | * Magic constant which defines signal strength of current network connection.
13 | */
14 | public class ConnectivityStrength implements Parcelable {
15 |
16 | public static final int UNDEFINED = -1;
17 |
18 | public static final int POOR = 0;
19 |
20 | public static final int GOOD = 1;
21 |
22 | public static final int EXCELLENT = 2;
23 |
24 | private final int value;
25 |
26 | public ConnectivityStrength(int value) {
27 | this.value = value;
28 | }
29 |
30 | @ConnectivityStrengthDef
31 | public int getValue() {
32 | return value;
33 | }
34 |
35 | @Retention(RetentionPolicy.SOURCE)
36 | @IntDef({
37 | UNDEFINED,
38 | POOR,
39 | GOOD,
40 | EXCELLENT
41 | })
42 | public @interface ConnectivityStrengthDef {
43 |
44 | }
45 |
46 | @Override
47 | public int describeContents() {
48 | return 0;
49 | }
50 |
51 | @Override
52 | public void writeToParcel(Parcel dest, int flags) {
53 | dest.writeInt(this.value);
54 | }
55 |
56 | protected ConnectivityStrength(Parcel in) {
57 | this.value = in.readInt();
58 | }
59 |
60 | public static final Creator CREATOR = new Creator() {
61 | @Override
62 | public ConnectivityStrength createFromParcel(Parcel source) {
63 | return new ConnectivityStrength(source);
64 | }
65 |
66 | @Override
67 | public ConnectivityStrength[] newArray(int size) {
68 | return new ConnectivityStrength[size];
69 | }
70 | };
71 | }
72 |
--------------------------------------------------------------------------------
/connectionbuddy/src/main/java/com/zplesac/connectionbuddy/models/ConnectivityType.java:
--------------------------------------------------------------------------------
1 | package com.zplesac.connectionbuddy.models;
2 |
3 | import android.os.Parcel;
4 | import android.os.Parcelable;
5 | import android.support.annotation.IntDef;
6 |
7 | import java.lang.annotation.Retention;
8 | import java.lang.annotation.RetentionPolicy;
9 |
10 | /**
11 | * Created by Željko Plesac on 23/09/15.
12 | * Magic constant which defines different network connection type. Device can only have one ConnectivityType at a time.
13 | */
14 | public class ConnectivityType implements Parcelable {
15 |
16 | public static final int UNDEFINED = -1;
17 |
18 | public static final int WIFI = 0;
19 |
20 | public static final int MOBILE = 1;
21 |
22 | public static final int NONE = 2;
23 |
24 | private final int value;
25 |
26 | public ConnectivityType(@ConnectivityTypeDef int value) {
27 | this.value = value;
28 | }
29 |
30 | @ConnectivityTypeDef
31 | public int getValue() {
32 | return value;
33 | }
34 |
35 | @Retention(RetentionPolicy.SOURCE)
36 | @IntDef({
37 | UNDEFINED,
38 | WIFI,
39 | MOBILE,
40 | NONE
41 | })
42 | public @interface ConnectivityTypeDef {
43 | }
44 |
45 | @Override
46 | public int describeContents() {
47 | return 0;
48 | }
49 |
50 | @Override
51 | public void writeToParcel(Parcel dest, int flags) {
52 | dest.writeInt(this.value);
53 | }
54 |
55 | protected ConnectivityType(Parcel in) {
56 | this.value = in.readInt();
57 | }
58 |
59 | public static final Creator CREATOR = new Creator() {
60 | @Override
61 | public ConnectivityType createFromParcel(Parcel source) {
62 | return new ConnectivityType(source);
63 | }
64 |
65 | @Override
66 | public ConnectivityType[] newArray(int size) {
67 | return new ConnectivityType[size];
68 | }
69 | };
70 | }
71 |
--------------------------------------------------------------------------------
/connectionbuddy/src/main/java/com/zplesac/connectionbuddy/presenters/ConnectivityPresenter.java:
--------------------------------------------------------------------------------
1 | package com.zplesac.connectionbuddy.presenters;
2 |
3 | /**
4 | * Created by Željko Plesac on 06/01/15.
5 | *
6 | * Default ConnectivityPresenter, which must be extended by our application BasePresenter
7 | */
8 | public interface ConnectivityPresenter {
9 |
10 | /**
11 | * Activity or fragment should register for network updates on its onStart() method.
12 | */
13 | void registerForNetworkUpdates();
14 |
15 | /**
16 | * Activity or fragment should unregister for network updates on its onStop() method.
17 | */
18 | void unregisterFromNetworkUpdates();
19 | }
20 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Settings specified in this file will override any Gradle settings
5 | # configured through the IDE.
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 | # Default value: -Xmx10248m -XX:MaxPermSize=256m
13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
14 |
15 | # When configured, Gradle will run in incubating parallel mode.
16 | # This option should only be used with decoupled projects. More details, visit
17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
18 | # org.gradle.parallel=true
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/infinum/android_connectionbuddy/17858378a6aa2efd62d02a368a3feb4fad9a0363/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Sun Jan 20 13:04:38 CET 2019
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-4.10.1-all.zip
--------------------------------------------------------------------------------
/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 | # For Cygwin, ensure paths are in UNIX format before anything is touched.
46 | if $cygwin ; then
47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
48 | fi
49 |
50 | # Attempt to set APP_HOME
51 | # Resolve links: $0 may be a link
52 | PRG="$0"
53 | # Need this for relative symlinks.
54 | while [ -h "$PRG" ] ; do
55 | ls=`ls -ld "$PRG"`
56 | link=`expr "$ls" : '.*-> \(.*\)$'`
57 | if expr "$link" : '/.*' > /dev/null; then
58 | PRG="$link"
59 | else
60 | PRG=`dirname "$PRG"`"/$link"
61 | fi
62 | done
63 | SAVED="`pwd`"
64 | cd "`dirname \"$PRG\"`/" >&-
65 | APP_HOME="`pwd -P`"
66 | cd "$SAVED" >&-
67 |
68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
69 |
70 | # Determine the Java command to use to start the JVM.
71 | if [ -n "$JAVA_HOME" ] ; then
72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
73 | # IBM's JDK on AIX uses strange locations for the executables
74 | JAVACMD="$JAVA_HOME/jre/sh/java"
75 | else
76 | JAVACMD="$JAVA_HOME/bin/java"
77 | fi
78 | if [ ! -x "$JAVACMD" ] ; then
79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
80 |
81 | Please set the JAVA_HOME variable in your environment to match the
82 | location of your Java installation."
83 | fi
84 | else
85 | JAVACMD="java"
86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
87 |
88 | Please set the JAVA_HOME variable in your environment to match the
89 | location of your Java installation."
90 | fi
91 |
92 | # Increase the maximum file descriptors if we can.
93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
94 | MAX_FD_LIMIT=`ulimit -H -n`
95 | if [ $? -eq 0 ] ; then
96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
97 | MAX_FD="$MAX_FD_LIMIT"
98 | fi
99 | ulimit -n $MAX_FD
100 | if [ $? -ne 0 ] ; then
101 | warn "Could not set maximum file descriptor limit: $MAX_FD"
102 | fi
103 | else
104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
105 | fi
106 | fi
107 |
108 | # For Darwin, add options to specify how the application appears in the dock
109 | if $darwin; then
110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
111 | fi
112 |
113 | # For Cygwin, switch paths to Windows format before running java
114 | if $cygwin ; then
115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
158 | function splitJvmOpts() {
159 | JVM_OPTS=("$@")
160 | }
161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
163 |
164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
165 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/sampleapp/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/sampleapp/build.gradle:
--------------------------------------------------------------------------------
1 | buildscript {
2 | repositories {
3 | google()
4 | jcenter()
5 |
6 | }
7 | dependencies {
8 | classpath 'com.android.tools.build:gradle:3.3.0'
9 |
10 | // NOTE: Do not place your application dependencies here; they belong
11 | // in the individual module build.gradle files
12 | }
13 | }
14 |
15 | apply plugin: 'com.android.application'
16 |
17 | android {
18 | compileSdkVersion 28
19 | buildToolsVersion "28.0.3"
20 |
21 | defaultConfig {
22 | applicationId "com.zplesac.connectionbuddy.sampleapp"
23 | minSdkVersion 19
24 | targetSdkVersion 28
25 | versionCode 1
26 | versionName "1.0"
27 | }
28 | buildTypes {
29 | release {
30 | minifyEnabled false
31 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
32 | }
33 | }
34 |
35 | lintOptions {
36 | // if true, stop the gradle build if errors are found
37 | abortOnError true
38 | // if true, don't include source code lines in the error output
39 | noLines false
40 | // if true, show all locations for an error, do not truncate lists, etc.
41 | showAll true
42 | }
43 | }
44 |
45 | dependencies {
46 | implementation fileTree(dir: 'libs', include: ['*.jar'])
47 | implementation 'com.android.support:support-annotations:28.0.0'
48 | implementation 'com.android.support:appcompat-v7:28.0.0'
49 | implementation "com.android.support:support-v4:28.0.0"
50 | implementation 'com.google.dagger:dagger:2.0'
51 | implementation 'pub.devrel:easypermissions:0.2.1'
52 | annotationProcessor 'com.google.dagger:dagger-compiler:2.0'
53 | implementation 'org.glassfish:javax.annotation:10.0-b28'
54 | implementation project(':connectionbuddy')
55 | }
56 |
--------------------------------------------------------------------------------
/sampleapp/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/zeljkoplesac/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 |
--------------------------------------------------------------------------------
/sampleapp/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
5 |
6 |
7 |
12 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
25 |
26 |
29 |
30 |
33 |
34 |
37 |
38 |
39 |
40 |
41 |
--------------------------------------------------------------------------------
/sampleapp/src/main/java/com/zplesac/connectionbuddy/sampleapp/SampleApp.java:
--------------------------------------------------------------------------------
1 | package com.zplesac.connectionbuddy.sampleapp;
2 |
3 | import com.zplesac.connectionbuddy.ConnectionBuddy;
4 | import com.zplesac.connectionbuddy.ConnectionBuddyConfiguration;
5 | import android.app.Application;
6 |
7 | /**
8 | * Created by Željko Plesac on 09/10/15.
9 | */
10 | public class SampleApp extends Application {
11 |
12 | @Override
13 | public void onCreate() {
14 | super.onCreate();
15 |
16 | // Define global configuration. We'll customize the default behaviour by defining
17 | // that we don't want to be notified about current network connection state after
18 | // we register for network connectivity events.
19 | ConnectionBuddyConfiguration configuration = new ConnectionBuddyConfiguration.Builder(this)
20 | .setNotifyImmediately(false)
21 | .build();
22 | ConnectionBuddy.getInstance().init(configuration);
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/sampleapp/src/main/java/com/zplesac/connectionbuddy/sampleapp/activities/MVPActivity.java:
--------------------------------------------------------------------------------
1 | package com.zplesac.connectionbuddy.sampleapp.activities;
2 |
3 | import com.zplesac.connectionbuddy.models.ConnectivityEvent;
4 | import com.zplesac.connectionbuddy.sampleapp.R;
5 | import com.zplesac.connectionbuddy.sampleapp.dagger.components.DaggerMVPComponent;
6 | import com.zplesac.connectionbuddy.sampleapp.dagger.modules.ContextModule;
7 | import com.zplesac.connectionbuddy.sampleapp.dagger.modules.MVPModule;
8 | import com.zplesac.connectionbuddy.sampleapp.mvp.presenters.MVPPresenter;
9 | import com.zplesac.connectionbuddy.sampleapp.mvp.views.MVPView;
10 |
11 | import android.app.Activity;
12 | import android.os.Bundle;
13 | import android.widget.TextView;
14 |
15 | import javax.inject.Inject;
16 |
17 | /**
18 | * Created by Željko Plesac on 02/09/15.
19 | */
20 | public class MVPActivity extends Activity implements MVPView {
21 |
22 | private TextView tvTitle;
23 |
24 | private TextView tvConnectionType;
25 |
26 | @Inject
27 | MVPPresenter presenter;
28 |
29 | @Override
30 | protected void onCreate(Bundle savedInstanceState) {
31 | super.onCreate(savedInstanceState);
32 | setContentView(R.layout.activity_mvp);
33 |
34 | DaggerMVPComponent.builder().mVPModule(new MVPModule(this)).contextModule(new ContextModule(this)).build().init(this);
35 |
36 | presenter.init(savedInstanceState != null);
37 | }
38 |
39 | @Override
40 | public void initUI() {
41 | tvTitle = (TextView) findViewById(R.id.tv_title);
42 | tvConnectionType = (TextView) findViewById(R.id.tv_connection_type);
43 | }
44 |
45 | @Override
46 | protected void onStart() {
47 | super.onStart();
48 | presenter.registerForNetworkUpdates();
49 | }
50 |
51 | @Override
52 | protected void onStop() {
53 | super.onStop();
54 | presenter.unregisterFromNetworkUpdates();
55 | }
56 |
57 | @Override
58 | public void onConnectionChangeEvent(ConnectivityEvent event) {
59 | tvTitle.setText("Connection status: " + event.getState());
60 | tvConnectionType.setText("Connection type: " + event.getType());
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/sampleapp/src/main/java/com/zplesac/connectionbuddy/sampleapp/activities/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.zplesac.connectionbuddy.sampleapp.activities;
2 |
3 | import com.zplesac.connectionbuddy.sampleapp.R;
4 |
5 | import android.app.Activity;
6 | import android.content.Intent;
7 | import android.os.Bundle;
8 | import android.view.View;
9 | import android.widget.Button;
10 |
11 |
12 | /**
13 | * Created by Željko Plesac on 08/09/15.
14 | */
15 | public class MainActivity extends Activity {
16 |
17 | private Button buttonSimpleExample;
18 |
19 | private Button buttonMVPExample;
20 |
21 | private Button buttonManualConfiguration;
22 |
23 | private Button buttonWifiExample;
24 |
25 | @Override
26 | protected void onCreate(Bundle savedInstanceState) {
27 | super.onCreate(savedInstanceState);
28 | setContentView(R.layout.activity_main);
29 |
30 | buttonMVPExample = (Button) findViewById(R.id.button_mvp);
31 | buttonSimpleExample = (Button) findViewById(R.id.button_simple);
32 | buttonManualConfiguration = (Button) findViewById(R.id.button_manual_configuration);
33 | buttonWifiExample = (Button) findViewById(R.id.button_wifi);
34 |
35 | buttonManualConfiguration.setOnClickListener(new View.OnClickListener() {
36 | @Override
37 | public void onClick(View v) {
38 | Intent intent = new Intent(MainActivity.this, ManualConfigurationActivity.class);
39 | startActivity(intent);
40 | }
41 | });
42 |
43 | buttonMVPExample.setOnClickListener(new View.OnClickListener() {
44 | @Override
45 | public void onClick(View v) {
46 | Intent intent = new Intent(MainActivity.this, MVPActivity.class);
47 | startActivity(intent);
48 | }
49 | });
50 |
51 | buttonSimpleExample.setOnClickListener(new View.OnClickListener() {
52 | @Override
53 | public void onClick(View v) {
54 | Intent intent = new Intent(MainActivity.this, SimpleActivity.class);
55 | startActivity(intent);
56 | }
57 | });
58 |
59 | buttonWifiExample.setOnClickListener(new View.OnClickListener() {
60 | @Override
61 | public void onClick(View v) {
62 | Intent intent = new Intent(MainActivity.this, WiFiActivity.class);
63 | startActivity(intent);
64 | }
65 | });
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/sampleapp/src/main/java/com/zplesac/connectionbuddy/sampleapp/activities/ManualConfigurationActivity.java:
--------------------------------------------------------------------------------
1 | package com.zplesac.connectionbuddy.sampleapp.activities;
2 |
3 | import com.zplesac.connectionbuddy.ConnectionBuddy;
4 | import com.zplesac.connectionbuddy.interfaces.ConnectivityChangeListener;
5 | import com.zplesac.connectionbuddy.interfaces.NetworkRequestCheckListener;
6 | import com.zplesac.connectionbuddy.models.ConnectivityEvent;
7 | import com.zplesac.connectionbuddy.sampleapp.R;
8 |
9 | import android.app.Activity;
10 | import android.os.Bundle;
11 | import android.view.View;
12 | import android.widget.Button;
13 | import android.widget.TextView;
14 | import android.widget.Toast;
15 |
16 | /**
17 | * Created by Željko Plesac on 08/09/15.
18 | */
19 | public class ManualConfigurationActivity extends Activity implements ConnectivityChangeListener {
20 |
21 | private TextView tvTitle;
22 |
23 | private TextView tvConnectionType;
24 |
25 | private Button buttonTestNetworkRequest;
26 |
27 | @Override
28 | protected void onCreate(Bundle savedInstanceState) {
29 | super.onCreate(savedInstanceState);
30 | setContentView(R.layout.activity_mvp);
31 |
32 | if (savedInstanceState != null) {
33 | ConnectionBuddy.getInstance().getConfiguration().getNetworkEventsCache().clearLastNetworkState(this);
34 | }
35 |
36 | tvTitle = (TextView) findViewById(R.id.tv_title);
37 | tvConnectionType = (TextView) findViewById(R.id.tv_connection_type);
38 | buttonTestNetworkRequest = (Button) findViewById(R.id.button_test_network_request);
39 |
40 | buttonTestNetworkRequest.setVisibility(View.VISIBLE);
41 | buttonTestNetworkRequest.setOnClickListener(testNetworkRequestButtonClickListener);
42 | }
43 |
44 | @Override
45 | protected void onStart() {
46 | super.onStart();
47 | // Omit the default configuration - we want to obtain the current network connection state
48 | // after we register for network connectivity events.
49 | ConnectionBuddy.getInstance().registerForConnectivityEvents(this, true, this);
50 | }
51 |
52 | @Override
53 | protected void onStop() {
54 | super.onStop();
55 | ConnectionBuddy.getInstance().unregisterFromConnectivityEvents(this);
56 | }
57 |
58 | @Override
59 | public void onConnectionChange(ConnectivityEvent event) {
60 | tvTitle.setText("Connection status: " + event.getState());
61 | tvConnectionType.setText("Connection type: " + event.getType());
62 | }
63 |
64 | private View.OnClickListener testNetworkRequestButtonClickListener = new View.OnClickListener() {
65 | @Override
66 | public void onClick(View v) {
67 | ConnectionBuddy.getInstance().hasNetworkConnection(new NetworkRequestCheckListener() {
68 | @Override
69 | public void onResponseObtained() {
70 | Toast.makeText(ManualConfigurationActivity.this, "Response obtained!", Toast.LENGTH_LONG).show();
71 | }
72 |
73 | @Override
74 | public void onNoResponse() {
75 | Toast.makeText(ManualConfigurationActivity.this, "No response obtained!", Toast.LENGTH_LONG).show();
76 | }
77 | });
78 | }
79 | };
80 | }
81 |
--------------------------------------------------------------------------------
/sampleapp/src/main/java/com/zplesac/connectionbuddy/sampleapp/activities/SimpleActivity.java:
--------------------------------------------------------------------------------
1 | package com.zplesac.connectionbuddy.sampleapp.activities;
2 |
3 | import com.zplesac.connectionbuddy.activities.ConnectionBuddyActivity;
4 | import com.zplesac.connectionbuddy.models.ConnectivityEvent;
5 | import com.zplesac.connectionbuddy.sampleapp.R;
6 |
7 | import android.os.Bundle;
8 | import android.widget.TextView;
9 |
10 | /**
11 | * Created by Željko Plesac on 21/02/16.
12 | */
13 | public class SimpleActivity extends ConnectionBuddyActivity{
14 |
15 | private TextView tvTitle;
16 |
17 | private TextView tvConnectionType;
18 |
19 | @Override
20 | protected void onCreate(Bundle savedInstanceState) {
21 | super.onCreate(savedInstanceState);
22 | setContentView(R.layout.activity_mvp);
23 |
24 | tvTitle = (TextView) findViewById(R.id.tv_title);
25 | tvConnectionType = (TextView) findViewById(R.id.tv_connection_type);
26 | }
27 |
28 | @Override
29 | public void onConnectionChange(ConnectivityEvent event) {
30 | tvTitle.setText("Connection status: " + event.getState());
31 | tvConnectionType.setText("Connection type: " + event.getType());
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/sampleapp/src/main/java/com/zplesac/connectionbuddy/sampleapp/activities/WiFiActivity.java:
--------------------------------------------------------------------------------
1 | package com.zplesac.connectionbuddy.sampleapp.activities;
2 |
3 | import com.zplesac.connectionbuddy.ConnectionBuddy;
4 | import com.zplesac.connectionbuddy.interfaces.WifiConnectivityListener;
5 | import com.zplesac.connectionbuddy.sampleapp.R;
6 |
7 | import android.Manifest;
8 | import android.os.Bundle;
9 | import android.support.annotation.Nullable;
10 | import android.support.v7.app.AppCompatActivity;
11 | import android.util.Log;
12 | import android.view.View;
13 | import android.widget.Button;
14 | import android.widget.EditText;
15 | import android.widget.Toast;
16 |
17 | import pub.devrel.easypermissions.AfterPermissionGranted;
18 | import pub.devrel.easypermissions.EasyPermissions;
19 |
20 | /**
21 | * Created by Željko Plesac on 15/11/16.
22 | */
23 | public class WiFiActivity extends AppCompatActivity implements WifiConnectivityListener {
24 |
25 | private static final String TAG = "WiFiActivity";
26 |
27 | private static final int RC_LOCATION = 147;
28 |
29 | private EditText etSsid;
30 |
31 | private EditText etPassword;
32 |
33 | private Button buttonConnect;
34 |
35 | @Override
36 | protected void onCreate(@Nullable Bundle savedInstanceState) {
37 | super.onCreate(savedInstanceState);
38 | setContentView(R.layout.activity_wi_fi);
39 |
40 | etSsid = (EditText) findViewById(R.id.et_ssid);
41 | etPassword = (EditText) findViewById(R.id.et_password);
42 | buttonConnect = (Button) findViewById(R.id.button_connect);
43 |
44 | buttonConnect.setOnClickListener(new View.OnClickListener() {
45 | @Override
46 | public void onClick(View view) {
47 | connectToWifi();
48 | }
49 | });
50 | }
51 |
52 | @Override
53 | public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
54 | super.onRequestPermissionsResult(requestCode, permissions, grantResults);
55 |
56 | // Forward results to EasyPermissions
57 | EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
58 | }
59 |
60 | @AfterPermissionGranted(RC_LOCATION)
61 | private void connectToWifi() {
62 | String[] perms = {Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION};
63 | if (EasyPermissions.hasPermissions(this, perms)) {
64 | try {
65 | ConnectionBuddy.getInstance()
66 | .connectToWifiConfiguration(this, etSsid.getText().toString(), etPassword.getText().toString(), true,
67 | WiFiActivity.this);
68 | } catch (SecurityException e) {
69 | e.printStackTrace();
70 | }
71 | } else {
72 | // Do not have permissions, request them now
73 | EasyPermissions.requestPermissions(this, getString(R.string.change_wifi_state_rationale),
74 | RC_LOCATION, perms);
75 | }
76 | }
77 |
78 | @Override
79 | public void onConnected() {
80 | Toast.makeText(this, getString(R.string.connected_to_wifi), Toast.LENGTH_LONG).show();
81 | }
82 |
83 | @Override
84 | public void onNotFound() {
85 | Toast.makeText(this, getString(R.string.wifi_not_found), Toast.LENGTH_LONG).show();
86 | }
87 | }
88 |
--------------------------------------------------------------------------------
/sampleapp/src/main/java/com/zplesac/connectionbuddy/sampleapp/dagger/components/MVPComponent.java:
--------------------------------------------------------------------------------
1 | package com.zplesac.connectionbuddy.sampleapp.dagger.components;
2 |
3 | import com.zplesac.connectionbuddy.sampleapp.activities.MVPActivity;
4 | import com.zplesac.connectionbuddy.sampleapp.dagger.modules.ContextModule;
5 | import com.zplesac.connectionbuddy.sampleapp.dagger.modules.MVPModule;
6 |
7 | import dagger.Component;
8 |
9 | /**
10 | * Created by Željko Plesac on 02/09/15.
11 | */
12 | @Component(modules = {MVPModule.class, ContextModule.class})
13 | public interface MVPComponent {
14 |
15 | void init(MVPActivity activity);
16 | }
17 |
--------------------------------------------------------------------------------
/sampleapp/src/main/java/com/zplesac/connectionbuddy/sampleapp/dagger/modules/ContextModule.java:
--------------------------------------------------------------------------------
1 | package com.zplesac.connectionbuddy.sampleapp.dagger.modules;
2 |
3 | import android.content.Context;
4 | import android.content.res.Resources;
5 |
6 | import dagger.Module;
7 | import dagger.Provides;
8 |
9 | /**
10 | * Created by Željko Plesac on 02/09/15.
11 | */
12 | @Module
13 | public class ContextModule {
14 |
15 | private Context context;
16 |
17 | public ContextModule(Context context) {
18 | this.context = context;
19 | }
20 |
21 | @Provides
22 | public Context provideContext() {
23 | return context;
24 | }
25 |
26 | @Provides
27 | public Resources provideResources(Context context) {
28 | return context.getResources();
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/sampleapp/src/main/java/com/zplesac/connectionbuddy/sampleapp/dagger/modules/MVPModule.java:
--------------------------------------------------------------------------------
1 | package com.zplesac.connectionbuddy.sampleapp.dagger.modules;
2 |
3 | import com.zplesac.connectionbuddy.sampleapp.mvp.presenters.MVPPresenter;
4 | import com.zplesac.connectionbuddy.sampleapp.mvp.presenters.impl.MVPPresenterImpl;
5 | import com.zplesac.connectionbuddy.sampleapp.mvp.views.MVPView;
6 |
7 | import dagger.Module;
8 | import dagger.Provides;
9 |
10 | /**
11 | * Created by Željko Plesac on 02/09/15.
12 | */
13 | @Module
14 | public class MVPModule {
15 |
16 | private MVPView view;
17 |
18 | public MVPModule(MVPView view) {
19 | this.view = view;
20 | }
21 |
22 | @Provides
23 | public MVPView provideView(){
24 | return view;
25 | }
26 |
27 | @Provides
28 | public MVPPresenter providePresenter(MVPPresenterImpl presenter){
29 | return presenter;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/sampleapp/src/main/java/com/zplesac/connectionbuddy/sampleapp/mvp/presenters/MVPPresenter.java:
--------------------------------------------------------------------------------
1 | package com.zplesac.connectionbuddy.sampleapp.mvp.presenters;
2 |
3 | import com.zplesac.connectionbuddy.presenters.ConnectivityPresenter;
4 |
5 | /**
6 | * Created by Željko Plesac on 02/09/15.
7 | */
8 | public interface MVPPresenter extends ConnectivityPresenter {
9 |
10 | void init(boolean hasSavedInstanceState);
11 | }
12 |
--------------------------------------------------------------------------------
/sampleapp/src/main/java/com/zplesac/connectionbuddy/sampleapp/mvp/presenters/impl/MVPPresenterImpl.java:
--------------------------------------------------------------------------------
1 | package com.zplesac.connectionbuddy.sampleapp.mvp.presenters.impl;
2 |
3 | import com.zplesac.connectionbuddy.ConnectionBuddy;
4 | import com.zplesac.connectionbuddy.interfaces.ConnectivityChangeListener;
5 | import com.zplesac.connectionbuddy.models.ConnectivityEvent;
6 | import com.zplesac.connectionbuddy.sampleapp.mvp.presenters.MVPPresenter;
7 | import com.zplesac.connectionbuddy.sampleapp.mvp.views.MVPView;
8 |
9 | import javax.inject.Inject;
10 |
11 | public class MVPPresenterImpl implements MVPPresenter, ConnectivityChangeListener {
12 |
13 | private MVPView view;
14 |
15 | @Inject
16 | public MVPPresenterImpl(MVPView view) {
17 | this.view = view;
18 | }
19 |
20 | @Override
21 | public void init(boolean hasSavedInstanceState) {
22 |
23 | if (!hasSavedInstanceState) {
24 | ConnectionBuddy.getInstance().clearNetworkCache(this);
25 | }
26 |
27 | view.initUI();
28 | }
29 |
30 | @Override
31 | public void registerForNetworkUpdates() {
32 | ConnectionBuddy.getInstance().registerForConnectivityEvents(this, this);
33 | }
34 |
35 | @Override
36 | public void unregisterFromNetworkUpdates() {
37 | ConnectionBuddy.getInstance().unregisterFromConnectivityEvents(this);
38 | }
39 |
40 | @Override
41 | public void onConnectionChange(ConnectivityEvent event) {
42 | view.onConnectionChangeEvent(event);
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/sampleapp/src/main/java/com/zplesac/connectionbuddy/sampleapp/mvp/views/MVPView.java:
--------------------------------------------------------------------------------
1 | package com.zplesac.connectionbuddy.sampleapp.mvp.views;
2 |
3 |
4 | import com.zplesac.connectionbuddy.models.ConnectivityEvent;
5 |
6 | /**
7 | * Created by Željko Plesac on 02/09/15.
8 | */
9 | public interface MVPView {
10 |
11 | void initUI();
12 |
13 | void onConnectionChangeEvent(ConnectivityEvent event);
14 | }
15 |
--------------------------------------------------------------------------------
/sampleapp/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
11 |
12 |
16 |
17 |
21 |
22 |
26 |
--------------------------------------------------------------------------------
/sampleapp/src/main/res/layout/activity_mvp.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
11 |
12 |
16 |
17 |
22 |
23 |
--------------------------------------------------------------------------------
/sampleapp/src/main/res/layout/activity_wi_fi.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
12 |
13 |
18 |
19 |
25 |
--------------------------------------------------------------------------------
/sampleapp/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/infinum/android_connectionbuddy/17858378a6aa2efd62d02a368a3feb4fad9a0363/sampleapp/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sampleapp/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/infinum/android_connectionbuddy/17858378a6aa2efd62d02a368a3feb4fad9a0363/sampleapp/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sampleapp/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/infinum/android_connectionbuddy/17858378a6aa2efd62d02a368a3feb4fad9a0363/sampleapp/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sampleapp/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/infinum/android_connectionbuddy/17858378a6aa2efd62d02a368a3feb4fad9a0363/sampleapp/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sampleapp/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | SampleApp
3 | Simple example
4 | Manual configuration
5 | MVP example
6 | WiFi connectivity example
7 | Test network request
8 | Network SSID
9 | Network password
10 | Connect
11 | We need Locations permission in order to connect to given network ssid.
12 | Connected to WiFi!
13 | WiFi connection error!
14 | WiFi with given network SSID and password was not found!
15 |
16 |
--------------------------------------------------------------------------------
/sampleapp/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':sampleapp', ':connectionbuddy'
2 |
--------------------------------------------------------------------------------