Wifi Connectivity and loading View

geofencing_wifi
Zohaib Kambrani 6 years ago
parent 69d1e4bb0b
commit 8e554970f3

@ -85,6 +85,7 @@ dependencies {
implementation 'com.github.kittinunf.fuel:fuel:2.3.0' //for JVM implementation 'com.github.kittinunf.fuel:fuel:2.3.0' //for JVM
implementation 'com.github.kittinunf.fuel:fuel-android:2.3.0' //for Android implementation 'com.github.kittinunf.fuel:fuel-android:2.3.0' //for Android
implementation 'com.wang.avi:library:2.1.3'
// Dependency on a remote binary // Dependency on a remote binary
// implementation 'com.example.android:app-magic:12.3' // implementation 'com.example.android:app-magic:12.3'

@ -0,0 +1,51 @@
package com.cloud.diplomaticquarterapp
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.RelativeLayout
import android.widget.TextView
import com.cloud.diplomaticquarterapp.utils.PlatformBridge
import com.wang.avi.AVLoadingIndicatorView
import io.flutter.embedding.android.FlutterView
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.embedding.engine.dart.DartExecutor
import io.flutter.plugin.common.MethodChannel
import io.flutter.view.FlutterMain
import org.jetbrains.anko.find
import java.util.ArrayList
open class BaseActivity : AppCompatActivity() {
lateinit var loadingView:RelativeLayout
lateinit var lblLoadingView:TextView
lateinit var avLoadingView:AVLoadingIndicatorView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun setContentView(layoutResID: Int) {
super.setContentView(layoutResID)
loadingView = find(R.id.loadingView)
lblLoadingView = find(R.id.lblLoadingView)
avLoadingView = find(R.id.avLoadingView)
}
override fun onResume() {
super.onResume()
}
override fun onPause() {
super.onPause()
}
override fun onStop() {
super.onStop()
}
override fun onDestroy() {
super.onDestroy()
}
}

@ -11,16 +11,17 @@ import io.flutter.plugin.common.MethodChannel
import io.flutter.view.FlutterMain import io.flutter.view.FlutterMain
import java.util.ArrayList import java.util.ArrayList
class FlutterMainActivity : AppCompatActivity() { class FlutterMainActivity : BaseActivity() {
private lateinit var channel: MethodChannel
private var flutterView: FlutterView? = null private var flutterView: FlutterView? = null
companion object { companion object {
private var flutterEngine: FlutterEngine? = null private var flutterEngine: FlutterEngine? = null
private const val CHANNEL = "HMG-Platform-Bridge"
private const val METHOD_CONNECT_WIFI = "connectHMGGuestWifi" private lateinit var instance:FlutterMainActivity
private const val METHOD_SHOW_LOADING = "loading" fun getInstance() : FlutterMainActivity{
return instance
}
} }
@ -72,6 +73,7 @@ class FlutterMainActivity : AppCompatActivity() {
override fun onResume() { override fun onResume() {
super.onResume() super.onResume()
flutterEngine!!.lifecycleChannel.appIsResumed() flutterEngine!!.lifecycleChannel.appIsResumed()
instance = this
} }
override fun onPause() { override fun onPause() {

@ -0,0 +1,99 @@
package com.cloud.diplomaticquarterapp.hmgwifi
import android.annotation.SuppressLint
import android.util.Log
import com.cloud.diplomaticquarterapp.API
import com.cloud.diplomaticquarterapp.FlutterMainActivity
import com.github.kittinunf.fuel.Fuel
import com.github.kittinunf.fuel.core.extensions.jsonBody
import com.github.kittinunf.fuel.httpGet
import com.github.kittinunf.fuel.httpPost
import org.jetbrains.anko.doAsync
import org.json.JSONObject
@SuppressLint("MissingPermission")
class HMG_Wifi(flutterMainActivity: FlutterMainActivity) {
private val TAG = "HMG_Wifi"
private val TEST = true
private var context = flutterMainActivity;
private lateinit var completionListener: ((status: Boolean, message: String) -> Unit)
private var SSID = "GUEST-POC"
private var USER_NAME = ""
private var PASSWORD = ""
fun completionOnUiThread(status: Boolean, message: String){
context.runOnUiThread {
completionListener(status, message)
}
}
/*
* Helpful:
* http://stackoverflow.com/questions/8818290/how-to-connect-to-a-specific-wifi-network-in-android-programmatically
*/
fun connectToHMGGuestNetwork(patientId: String, completion: (status: Boolean, message: String) -> Unit): HMG_Wifi {
completionListener = completion
getWifiCredentials(patientId) {
WPA(context,SSID).connect(USER_NAME,PASSWORD) { status, message ->
completionOnUiThread(status,message)
}
}
return this
}
private fun haveInternet(completion: ((status: Boolean) -> Unit)){
if (TEST)
completion(true)
"https://captive.apple.com".httpGet().response { request, response, result ->
val have = response.statusCode == 200 && String(response.data).contains("<TITLE>Success</TITLE>", true)
completion(have)
}
}
private fun getWifiCredentials(patientId:String, completion: (() -> Unit)){
// if (TEST){
// SSID = "GUEST-POC"
// USER_NAME = "0696"
// PASSWORD = "0000"
// completion()
// return
// }
val jsonBody = """{"PatientID":$patientId}"""
API.WIFI_CREDENTIALS.
httpPost()
.jsonBody(jsonBody, Charsets.UTF_8)
.response { request, response, result ->
result.fold(success = { data ->
val jsonString = String(data)
val jsonObject = JSONObject(jsonString)
if(!jsonObject.getString("ErrorMessage").equals("null")){
val errorMsg = jsonObject.getString("ErrorMessage")
completionOnUiThread(false, errorMsg)
}else{
jsonObject.getJSONArray("Hmg_SMS_Get_By_ProjectID_And_PatientIDList").let { array ->
array.getJSONObject(0).let { object_ ->
if (object_.has("UserName") && object_.has("UserName")){
USER_NAME = object_.getString("UserName")
PASSWORD = object_.getString("Password")
completion()
}else{
completionOnUiThread(false, "Failed to get your internet credentials")
}
}
}
}
},failure = { error ->
completionOnUiThread(false, error.localizedMessage )
})
}
}
}

@ -0,0 +1,98 @@
package com.cloud.diplomaticquarterapp.hmgwifi
import android.content.Context
import android.net.ConnectivityManager
import android.net.wifi.*
import android.util.Log
import com.cloud.diplomaticquarterapp.FlutterMainActivity
import com.cloud.diplomaticquarterapp.utils.HMGUtils
class WPA(mainActivity: FlutterMainActivity, SSID:String) {
private var TAG = "WPA"
private var SSID = "GUEST-POC"
private var wifiManager_: WifiManager? = null
private var connectivityManager_: ConnectivityManager? = null
init {
wifiManager_ = mainActivity.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager?
connectivityManager_ = mainActivity.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
}
fun connect(identity:String, password:String, completion: (status: Boolean, message: String) -> Unit) {
if(wifiManager_ == null || connectivityManager_ == null){
completion(false, "Failed to access system connectivity services")
return
}
val wifiManager = wifiManager_!!
val connectivityManager = connectivityManager_!!
// Initialize the WifiConfiguration object
val enterpriseConfig = WifiEnterpriseConfig()
val wifi = WifiConfiguration()
wifi.SSID = """"$SSID""""
wifi.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP)
wifi.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.IEEE8021X)
enterpriseConfig.eapMethod = WifiEnterpriseConfig.Eap.PEAP
enterpriseConfig.identity = identity
enterpriseConfig.password = password
wifi.enterpriseConfig = enterpriseConfig
wifi.networkId = ssidToNetworkId(wifi.SSID)
if (wifi.networkId == -1) {
wifiManager.addNetwork(wifi)
} else {
Log.v(TAG, "WiFi found - updating it.\n")
wifiManager.updateNetwork(wifi)
}
Log.v(TAG, "saving config.\n")
wifiManager.saveConfiguration()
wifi.networkId = ssidToNetworkId(wifi.SSID)
Log.v(TAG, "wifi ID in device = " + wifi.networkId)
var supState: SupplicantState
val networkIdToConnect = wifi.networkId
if (networkIdToConnect >= 0) {
Log.v(TAG, "Start connecting...\n")
// We disable the network before connecting, because if this was the last connection before
// a disconnect(), this will not reconnect.
wifiManager.disableNetwork(networkIdToConnect)
wifiManager.enableNetwork(networkIdToConnect, true)
val wifiInfo: WifiInfo = wifiManager.connectionInfo
HMGUtils.timer(5000,false){
supState = wifiInfo.supplicantState
Log.i(TAG, "WifiWizard: Done connect to network : status = $supState")
if (supState == SupplicantState.COMPLETED)
completion(true,"Connected to Wifi")
else
completion(false,"Failed to connect with HMG network")
}
} else {
Log.v(TAG, "WifiWizard: cannot connect to network")
completion(false,"Failed to connect to Wifi")
}
}
/**
* This method takes a given String, searches the current list of configured WiFi
* networks, and returns the networkId for the network if the SSID matches. If not,
* it returns -1.
*/
private fun ssidToNetworkId(ssid: String): Int {
val currentNetworks = wifiManager_!!.configuredNetworks
var networkId = -1
// For each network in the list, compare the SSID with the given one
for (test in currentNetworks) {
if (test.SSID == ssid) {
networkId = test.networkId
break
}
}
return networkId
}
}

@ -0,0 +1,51 @@
package com.cloud.diplomaticquarterapp.utils
import android.opengl.Visibility
import android.view.View
import android.widget.Toast
import com.cloud.diplomaticquarterapp.BaseActivity
import java.util.*
import kotlin.concurrent.timerTask
class HMGUtils {
companion object{
fun timer(delay:Long, repeat:Boolean, tick:(Timer)->Unit) : Timer{
val timer = Timer()
if(repeat)
timer.schedule(timerTask {
tick(timer)
},delay,delay)
else
timer.schedule(timerTask {
tick(timer)
},delay)
return timer
}
fun showLoading(context: BaseActivity, show:Boolean = true, message:String = "Please wait"){
if(show){
context.loadingView.visibility = View.VISIBLE
context.avLoadingView.smoothToShow()
context.lblLoadingView.text = message
}else{
context.loadingView.visibility = View.GONE
context.avLoadingView.smoothToHide()
context.lblLoadingView.text = ""
}
}
fun showMessage(context:BaseActivity, title:String = "", message:String){
Toast.makeText(context,message,Toast.LENGTH_LONG).show()
}
}
}
private fun Timer.schedule(timerTask: TimerTask) {
}

@ -3,6 +3,9 @@ package com.cloud.diplomaticquarterapp.utils
import android.annotation.SuppressLint import android.annotation.SuppressLint
import android.content.Context import android.content.Context
import android.net.ConnectivityManager import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import android.net.wifi.ScanResult import android.net.wifi.ScanResult
import android.net.wifi.WifiConfiguration import android.net.wifi.WifiConfiguration
import android.net.wifi.WifiManager import android.net.wifi.WifiManager
@ -17,8 +20,9 @@ import java.util.*
@SuppressLint("MissingPermission") @SuppressLint("MissingPermission")
class HMG_Wifi(flutterMainActivity: FlutterMainActivity) { class HMG_Wifi_(flutterMainActivity: FlutterMainActivity) {
val TAG = "WIFI" val TAG = "WIFI"
val TEST = true
var context = flutterMainActivity; var context = flutterMainActivity;
var completionListener: ((status: Boolean, message: String) -> Unit)? = null var completionListener: ((status: Boolean, message: String) -> Unit)? = null
@ -27,6 +31,7 @@ class HMG_Wifi(flutterMainActivity: FlutterMainActivity) {
private var SSID = "HMG-GUEST" private var SSID = "HMG-GUEST"
private var USER_NAME = "" private var USER_NAME = ""
private var PASSWORD = "" private var PASSWORD = ""
var NETWORK_ID = -1 // HMG-GUEST Assigned Network ID by Android
private lateinit var PATIENT_ID:String private lateinit var PATIENT_ID:String
/* /*
* Helpful: * Helpful:
@ -41,7 +46,10 @@ class HMG_Wifi(flutterMainActivity: FlutterMainActivity) {
* Helpful: * Helpful:
* http://stackoverflow.com/questions/8818290/how-to-connect-to-a-specific-wifi-network-in-android-programmatically * http://stackoverflow.com/questions/8818290/how-to-connect-to-a-specific-wifi-network-in-android-programmatically
*/ */
fun connectToWifiNetworkWith(patientId:String): HMG_Wifi { fun connectToWifiNetworkWith(patientId: String): HMG_Wifi_ {
val connectivityManager = context.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
PATIENT_ID = patientId PATIENT_ID = patientId
val security = "OPEN" val security = "OPEN"
@ -66,16 +74,16 @@ class HMG_Wifi(flutterMainActivity: FlutterMainActivity) {
// Then, you need to add it to Android wifi manager settings: // Then, you need to add it to Android wifi manager settings:
val wifiManager = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager val wifiManager = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
val networkId = wifiManager.addNetwork(conf) NETWORK_ID = wifiManager.addNetwork(conf)
Log.d(TAG, "Network ID: $networkId") Log.d(TAG, "Network ID: $NETWORK_ID")
//wifiManager.disconnect(); //wifiManager.disconnect();
val result = wifiManager.enableNetwork(networkId, true) val result = wifiManager.enableNetwork(NETWORK_ID, true)
//wifiManager.reconnect(); //wifiManager.reconnect();
wifiManager.saveConfiguration() wifiManager.saveConfiguration()
if(result == true){ if(result == true){
authNetworkConnection(networkId); authNetworkConnection(NETWORK_ID);
}else{ }else{
completionListener?.let { it(false, "Error connecting to HMG network") } completionListener?.let { it(false, "Error connecting to HMG network") }
} }
@ -108,13 +116,11 @@ class HMG_Wifi(flutterMainActivity: FlutterMainActivity) {
} }
fun authServerCall(){ fun authServerCall(){
fun forceCallOverWifi(){
val connectivityManager = context.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
connectivityManager.networkPreference = ConnectivityManager.TYPE_WIFI
}
fun call(){ fun call(){
forceCallOverWifi()
forceNetworkCallOverWifi()
val params = listOf("cmd" to "authenticate", "password" to PASSWORD, "user" to USER_NAME) val params = listOf("cmd" to "authenticate", "password" to PASSWORD, "user" to USER_NAME)
val serverUrl = "https://captiveportal-login.hmg.com/cgi-bin/login" val serverUrl = "https://captiveportal-login.hmg.com/cgi-bin/login"
// val serverUrl = "http://192.168.102.223/cgi-bin/login" // val serverUrl = "http://192.168.102.223/cgi-bin/login"
@ -148,6 +154,9 @@ class HMG_Wifi(flutterMainActivity: FlutterMainActivity) {
} }
fun haveInternet(completion: ((status: Boolean) -> Unit)){ fun haveInternet(completion: ((status: Boolean) -> Unit)){
if (TEST)
completion(true)
"https://captive.apple.com".httpGet().response { request, response, result -> "https://captive.apple.com".httpGet().response { request, response, result ->
val have = response.statusCode == 200 && String(response.data).contains("<TITLE>Success</TITLE>", true) val have = response.statusCode == 200 && String(response.data).contains("<TITLE>Success</TITLE>", true)
completion(have) completion(have)
@ -155,8 +164,7 @@ class HMG_Wifi(flutterMainActivity: FlutterMainActivity) {
} }
fun getAuthCredentials(completion: (() -> Unit)){ fun getAuthCredentials(completion: (() -> Unit)){
val test = true if (TEST){
if (test){
USER_NAME = "2300" USER_NAME = "2300"
PASSWORD = "1820" PASSWORD = "1820"
completion() completion()
@ -198,6 +206,33 @@ class HMG_Wifi(flutterMainActivity: FlutterMainActivity) {
} }
} }
fun forceNetworkCallOverWifi(){
val connectivityManager = context.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
// val network = Network
// connectivityManager.activeNetwork
// Exit app if Network disappears.
// Exit app if Network disappears.
// val networkCapabilities: NetworkCapabilities = ConnectivityManager.from(context).getNetworkCapabilities(network)
// val networkCapabilities: NetworkCapabilities = connectivityManager.getNetworkCapabilities(network)
// if (networkCapabilities == null) {
// return
// }
val mNetworkCallback = object : ConnectivityManager.NetworkCallback() {
override fun onLost(lostNetwork: Network?) {
// if (network.equals(lostNetwork)){
// //GlyphLayout.done(false)
// }
}
}
val builder: NetworkRequest.Builder = NetworkRequest.Builder()
// for (transportType in networkCapabilities.getTransportTypes()) {
// builder.addTransportType(transportType)
// }
connectivityManager.registerNetworkCallback(builder.build(), mNetworkCallback)
}
/* /*
* Helpful: * Helpful:
* http://stackoverflow.com/questions/6517314/android-wifi-connection-programmatically * http://stackoverflow.com/questions/6517314/android-wifi-connection-programmatically

@ -1,7 +1,9 @@
package com.cloud.diplomaticquarterapp.utils package com.cloud.diplomaticquarterapp.utils
import android.util.Log import android.util.Log
import android.widget.Toast
import com.cloud.diplomaticquarterapp.FlutterMainActivity import com.cloud.diplomaticquarterapp.FlutterMainActivity
import com.cloud.diplomaticquarterapp.hmgwifi.HMG_Wifi
import io.flutter.plugin.common.BinaryMessenger import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.MethodCall import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel import io.flutter.plugin.common.MethodChannel
@ -22,26 +24,47 @@ class PlatformBridge(binaryMessenger: BinaryMessenger, flutterMainActivity: Flut
channel = MethodChannel(binaryMessenger, CHANNEL) channel = MethodChannel(binaryMessenger, CHANNEL)
channel.setMethodCallHandler { methodCall: MethodCall, result: MethodChannel.Result -> channel.setMethodCallHandler { methodCall: MethodCall, result: MethodChannel.Result ->
if (methodCall.method == METHOD_CONNECT_WIFI) { if (methodCall.method == METHOD_CONNECT_WIFI) {
connectHMGGuestWifi(methodCall,result)
}else if (methodCall.method == METHOD_SHOW_LOADING) {
}else {
result.notImplemented()
}
}
}
private fun connectHMGGuestWifi(methodCall: MethodCall, result: MethodChannel.Result){
(methodCall.arguments as ArrayList<*>).let { (methodCall.arguments as ArrayList<*>).let {
require(it.size > 0 && (it.get(0) is String),lazyMessage = { require(it.size > 0 && (it[0] is String),lazyMessage = {
"Missing or invalid arguments (Must have one argument 'String at 0'" "Missing or invalid arguments (Must have one argument 'String at 0'"
}) })
val patientId = it.get(0).toString() val patientId = it[0].toString()
HMGUtils.showLoading(mainActivity,true,"Connecting...")
HMG_Wifi(mainActivity) HMG_Wifi(mainActivity)
.connectToWifiNetworkWith(patientId) .connectToHMGGuestNetwork(patientId){ status, message ->
.completionListener = { status, message -> HMGUtils.showLoading(mainActivity,false)
if(status){
HMGUtils.showMessage(mainActivity,"Error", message)
}else{
HMGUtils.showMessage(mainActivity,"Success",message)
}
Log.v(this.javaClass.simpleName, "$status | $message") Log.v(this.javaClass.simpleName, "$status | $message")
} }
} }
}
}else if (methodCall.method == METHOD_CONNECT_WIFI) { private fun showLoading(methodCall: MethodCall, result: MethodChannel.Result){
(methodCall.arguments as ArrayList<*>).let {
require(it.size > 1 && (it[0] is Boolean) && (it[1] is String),lazyMessage = {
"Missing or invalid arguments (Must have two argument 'Boolean at 0' and 'String at 1'"
})
}else { val show = it[0] as Boolean
result.notImplemented() val message = it[0] as String
} HMGUtils.showLoading(mainActivity,show,message)
} }
} }
} }

@ -12,11 +12,6 @@
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="match_parent"/> android:layout_height="match_parent"/>
<TextView <include layout="@layout/loading_view" android:visibility="gone"/>
android:text="Zohaib"
android:textSize="50dp"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout> </RelativeLayout>

@ -0,0 +1,42 @@
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/loadingView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#B3000000">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_margin="60dp"
android:layout_centerInParent="true"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.wang.avi.AVLoadingIndicatorView
android:id="@+id/avLoadingView"
style="@style/AVLoadingIndicatorView"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_centerInParent="true"
android:visibility="visible"
app:indicatorColor="#4CAF50"
app:indicatorName="BallScaleMultipleIndicator"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintDimensionRatio="w,1:1"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
<TextView
android:id="@+id/lblLoadingView"
android:textSize="12sp"
android:textColor="#FFFFFF"
android:layout_centerInParent="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
Loading…
Cancel
Save