Wifi check network available - android

tweaking at geofence code
merge-requests/236/head
Zohaib Kambrani 5 years ago
parent 4c00f9b3f2
commit a11d93332d

@ -76,11 +76,12 @@
<receiver android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationReceiver" /> <receiver android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationReceiver" />
<!-- Geofencing --> <!-- Geofencing -->
<service android:name=".geofence.GeofenceTransitionsJobIntentService" android:exported="true" android:permission="android.permission.BIND_JOB_SERVICE" /> <service android:name=".geofence.intent_receivers.GeofenceTransitionsJobIntentService" android:exported="true" android:permission="android.permission.BIND_JOB_SERVICE" />
<receiver android:name=".geofence.GeofenceBroadcastReceiver" android:enabled="true" android:exported="true" /> <receiver android:name=".geofence.intent_receivers.GeofenceBroadcastReceiver" android:enabled="true" android:exported="true" />
<receiver android:name=".geofence.GeofencingRebootBroadcastReceiver" android:enabled="true"> <receiver android:name=".geofence.intent_receivers.GeofencingRebootBroadcastReceiver" android:enabled="true">
<intent-filter> <intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETE"/> <action android:name="android.intent.action.BOOT_COMPLETED"/>
<!-- <action android:name="android.intent.action.BOOT_COMPLETE"/>-->
</intent-filter> </intent-filter>
</receiver> </receiver>

@ -8,6 +8,7 @@ import android.content.SharedPreferences
import android.content.pm.PackageManager import android.content.pm.PackageManager
import android.location.Location import android.location.Location
import androidx.core.content.ContextCompat import androidx.core.content.ContextCompat
import com.cloud.diplomaticquarterapp.geofence.intent_receivers.GeofenceBroadcastReceiver
import com.cloud.diplomaticquarterapp.utils.* import com.cloud.diplomaticquarterapp.utils.*
import com.google.android.gms.location.Geofence import com.google.android.gms.location.Geofence
import com.google.android.gms.location.GeofencingClient import com.google.android.gms.location.GeofencingClient

@ -1,11 +1,13 @@
package com.cloud.diplomaticquarterapp.geofence package com.cloud.diplomaticquarterapp.geofence.intent_receivers
import android.content.BroadcastReceiver import android.content.BroadcastReceiver
import android.content.Context import android.content.Context
import android.content.Intent import android.content.Intent
import android.util.Log import android.util.Log
import com.cloud.diplomaticquarterapp.geofence.GeofenceTransition
import com.cloud.diplomaticquarterapp.geofence.HMG_Geofence
import com.cloud.diplomaticquarterapp.utils.saveLog import com.cloud.diplomaticquarterapp.utils.saveLog
import com.google.android.gms.location.GeofencingEvent import com.google.android.gms.location.GeofencingEvent

@ -1,12 +1,12 @@
package com.cloud.diplomaticquarterapp.geofence package com.cloud.diplomaticquarterapp.geofence.intent_receivers
import android.content.BroadcastReceiver import android.content.BroadcastReceiver
import android.content.Context import android.content.Context
import android.content.Intent import android.content.Intent
class GeofenceBroadcastReceiverWithService : BroadcastReceiver() { class GeofenceBroadcastReceiverWithJobService : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) { override fun onReceive(context: Context, intent: Intent) {
GeofenceTransitionsJobIntentService.enqueueWork(context, intent) GeofenceTransitionsJobIntentService.enqueueWork(context, intent)
} }

@ -1,6 +1,6 @@
package com.cloud.diplomaticquarterapp.geofence package com.cloud.diplomaticquarterapp.geofence.intent_receivers
import android.content.Context import android.content.Context
import com.cloud.diplomaticquarterapp.R import com.cloud.diplomaticquarterapp.R

@ -0,0 +1,29 @@
package com.cloud.diplomaticquarterapp.geofence.intent_receivers
import android.content.Intent
import android.util.Log
import androidx.core.app.JobIntentService
import com.cloud.diplomaticquarterapp.geofence.GeofenceTransition
import com.cloud.diplomaticquarterapp.geofence.HMG_Geofence
import com.cloud.diplomaticquarterapp.utils.saveLog
import com.google.android.gms.location.GeofencingEvent
class GeofenceJobIntentService : JobIntentService(){
private val LOG_TAG = "GeofenceBroadcastReceiver"
override fun onHandleWork(intent: Intent) {
val geofencingEvent = GeofencingEvent.fromIntent(intent)
if (geofencingEvent.hasError()) {
val errorMessage = GeofenceErrorMessages.getErrorString(this, geofencingEvent.errorCode)
Log.e(LOG_TAG, errorMessage)
saveLog(this, LOG_TAG,errorMessage)
return
}
HMG_Geofence.shared(this).handleEvent(geofencingEvent.triggeringGeofences,geofencingEvent.triggeringLocation, GeofenceTransition.fromInt(geofencingEvent.geofenceTransition))
}
}

@ -29,22 +29,16 @@
*/ */
package com.cloud.diplomaticquarterapp.geofence package com.cloud.diplomaticquarterapp.geofence.intent_receivers
import android.content.Context import android.content.Context
import android.content.Intent import android.content.Intent
import android.location.Location
import android.util.Log import android.util.Log
import androidx.core.app.JobIntentService import androidx.core.app.JobIntentService
import com.cloud.diplomaticquarterapp.utils.API import com.cloud.diplomaticquarterapp.geofence.GeofenceTransition
import com.cloud.diplomaticquarterapp.utils.httpPost import com.cloud.diplomaticquarterapp.geofence.HMG_Geofence
import com.cloud.diplomaticquarterapp.utils.sendNotification
import com.github.kittinunf.fuel.core.extensions.jsonBody
import com.github.kittinunf.fuel.core.isSuccessful
import com.github.kittinunf.fuel.httpPost
import com.google.android.gms.location.Geofence import com.google.android.gms.location.Geofence
import com.google.android.gms.location.GeofencingEvent import com.google.android.gms.location.GeofencingEvent
import com.google.gson.Gson
class GeofenceTransitionsJobIntentService : JobIntentService() { class GeofenceTransitionsJobIntentService : JobIntentService() {

@ -1,20 +1,19 @@
package com.cloud.diplomaticquarterapp.geofence package com.cloud.diplomaticquarterapp.geofence.intent_receivers
import android.content.BroadcastReceiver import android.content.BroadcastReceiver
import android.content.Context import android.content.Context
import android.content.Intent import android.content.Intent
import android.os.Handler
import android.os.Message
import com.cloud.diplomaticquarterapp.geofence.HMG_Geofence import com.cloud.diplomaticquarterapp.geofence.HMG_Geofence
import com.cloud.diplomaticquarterapp.geofence.PREFS_STORAGE
import com.cloud.diplomaticquarterapp.utils.HMGUtils import com.cloud.diplomaticquarterapp.utils.HMGUtils
class GeofencingRebootBroadcastReceiver : BroadcastReceiver(){ class GeofencingRebootBroadcastReceiver : BroadcastReceiver(){
override fun onReceive(context: Context, intent: Intent) { override fun onReceive(context: Context, intent: Intent) {
// if (Intent.ACTION_BOOT_COMPLETED.equals(intent.action)) { if (Intent.ACTION_BOOT_COMPLETED.equals(intent.action)) {
if (intent.action.equals("android.intent.action.BOOT_COMPLETE")) { // if (intent.action.equals("android.intent.action.BOOT_COMPLETE")) {
val pref = context.getSharedPreferences(PREFS_STORAGE, Context.MODE_PRIVATE) val pref = context.getSharedPreferences(PREFS_STORAGE, Context.MODE_PRIVATE)
pref.edit().putString("REBOOT_DETECTED","YES").apply() pref.edit().putString("REBOOT_DETECTED","YES").apply()

@ -126,7 +126,7 @@ fun sendNotification(context: Context, title:String, @Nullable subtitle:String?,
.addNextIntent(intent) .addNextIntent(intent)
val notificationPendingIntent = stackBuilder.getPendingIntent(getUniqueId(), PendingIntent.FLAG_UPDATE_CURRENT) val notificationPendingIntent = stackBuilder.getPendingIntent(getUniqueId(), PendingIntent.FLAG_UPDATE_CURRENT)
val notification = NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID) val notification = NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID + ".geofence")
.setSmallIcon(R.mipmap.ic_launcher) .setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(notificationPendingIntent) .setContentIntent(notificationPendingIntent)
.setAutoCancel(true) .setAutoCancel(true)
@ -154,9 +154,9 @@ fun isJSONValid(jsonString: String?): Boolean {
fun saveLog(context:Context, tag:String, message:String){ fun saveLog(context:Context, tag:String, message:String){
val pref = context.getSharedPreferences(PREFS_STORAGE, Context.MODE_PRIVATE) val pref = context.getSharedPreferences(PREFS_STORAGE, Context.MODE_PRIVATE)
var logs = pref.getString("GEO_LOGS","") var logs = pref.getString("GEOFENCE_LOGS","")
logs += "$tag -> $message \n" logs += "$tag -> $message \n"
pref.edit().putString("PLATFORM_LOGS", logs).apply(); pref.edit().putString("GEOFENCE_LOGS", logs).apply();
} }
class HTTPResponse<T>(data: T){ class HTTPResponse<T>(data: T){

@ -1 +1 @@
3f3d14a0ae775b56806906c2cb14a1f0 d9d141e787a8aa802f90b776d75f04fc

@ -2,6 +2,7 @@ import UIKit
import Flutter import Flutter
import GoogleMaps import GoogleMaps
var userNotificationCenterDelegate:UNUserNotificationCenterDelegate? = nil
@UIApplicationMain @UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate { @objc class AppDelegate: FlutterAppDelegate {
@ -12,6 +13,7 @@ import GoogleMaps
GMSServices.provideAPIKey("AIzaSyCiiJiHkocPbcziHt9O8rGWavDrxHRQys8") GMSServices.provideAPIKey("AIzaSyCiiJiHkocPbcziHt9O8rGWavDrxHRQys8")
GeneratedPluginRegistrant.register(with: self) GeneratedPluginRegistrant.register(with: self)
if let mainViewController = window.rootViewController as? MainFlutterVC{ if let mainViewController = window.rootViewController as? MainFlutterVC{
HMGPlatformBridge.initialize(flutterViewController: mainViewController) HMGPlatformBridge.initialize(flutterViewController: mainViewController)
} }
@ -20,6 +22,18 @@ import GoogleMaps
HMG_Geofence.initGeofencing() HMG_Geofence.initGeofencing()
} }
UNUserNotificationCenter.current().delegate = self
return super.application(application, didFinishLaunchingWithOptions: launchOptions) return super.application(application, didFinishLaunchingWithOptions: launchOptions)
} }
} }
extension AppDelegate{
override func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
if (notification.request.content.categoryIdentifier == HmgLocalNotificationCategoryIdentifier){
completionHandler([.alert,.sound])
}else{
super.userNotificationCenter(center, willPresent: notification, withCompletionHandler: completionHandler)
}
}
}

@ -18,6 +18,14 @@ extension String{
} }
} }
extension Date{
func toString(format:String) -> String{
let df = DateFormatter()
df.dateFormat = format
return df.string(from: self)
}
}
extension Dictionary{ extension Dictionary{
func merge(dict:[String:Any?]) -> [String:Any?]{ func merge(dict:[String:Any?]) -> [String:Any?]{
var self_ = self as! [String:Any?] var self_ = self as! [String:Any?]

@ -31,20 +31,26 @@ func dictionary(from:String) -> [String:Any]?{
} }
func showNotification(identifier:String? = nil, title:String?, subtitle:String?, message:String?, sound:UNNotificationSound = UNNotificationSound.default){ let HmgLocalNotificationCategoryIdentifier = "hmg.local.notification"
let notificationContent = UNMutableNotificationContent() func showNotification(identifier:String? = nil, title:String?, subtitle:String?, message:String?, sound:UNNotificationSound = UNNotificationSound.default, categoryIdentifier:String = HmgLocalNotificationCategoryIdentifier){
DispatchQueue.main.async {
if identifier != nil { notificationContent.categoryIdentifier = identifier! } let notificationContent = UNMutableNotificationContent()
if title != nil { notificationContent.title = title! } notificationContent.categoryIdentifier = categoryIdentifier
if subtitle != nil { notificationContent.body = message! }
if message != nil { notificationContent.subtitle = subtitle! } if identifier != nil { notificationContent.categoryIdentifier = identifier! }
if title != nil { notificationContent.title = title! }
notificationContent.sound = UNNotificationSound.default if subtitle != nil { notificationContent.body = message! }
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false) if message != nil { notificationContent.subtitle = subtitle! }
let request = UNNotificationRequest(identifier: "\(Date().timeIntervalSinceNow)", content: notificationContent, trigger: trigger)
UNUserNotificationCenter.current().add(request) { error in notificationContent.sound = UNNotificationSound.default
if let error = error { let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
print("Error: \(error)") let request = UNNotificationRequest(identifier: "\(Date().timeIntervalSinceNow)", content: notificationContent, trigger: trigger)
UNUserNotificationCenter.current().add(request) { error in
if let error = error {
print("Error: \(error)")
}
} }
} }
} }
@ -103,6 +109,8 @@ func httpPostRequest(urlString:String, jsonBody:[String:Any?], completion:((Bool
completion?(false,responseJSON) completion?(false,responseJSON)
} }
}else{
completion?(false,nil)
} }
} }

@ -129,8 +129,10 @@ extension HMG_Geofence : CLLocationManagerDelegate{
extension HMG_Geofence{ extension HMG_Geofence{
func handleEvent(for region: CLRegion!, transition:Transition, location:CLLocation?) { func handleEvent(for region: CLRegion!, transition:Transition, location:CLLocation?) {
notifyUser(forRegion: region, transition: transition, location: locationManager.location) if let userProfile = userProfile(){
notifyServer(forRegion: region, transition: transition, location: locationManager.location) notifyUser(forRegion: region, transition: transition, location: locationManager.location, userProfile: userProfile)
notifyServer(forRegion: region, transition: transition, location: locationManager.location, userProfile: userProfile)
}
} }
func geoZone(by id: String) -> GeoZoneModel? { func geoZone(by id: String) -> GeoZoneModel? {
@ -144,25 +146,14 @@ extension HMG_Geofence{
} }
func notifyUser(forRegion:CLRegion, transition:Transition, location:CLLocation?){ func notifyUser(forRegion:CLRegion, transition:Transition, location:CLLocation?, userProfile:[String:Any?]){
if let zone = geoZone(by: forRegion.identifier){ if let patientId = userProfile["PatientID"] as? Int{
if UIApplication.shared.applicationState == .active {
mainViewController.showAlert(withTitle: transition.name(), message: zone.message())
}else{
}
} }
} }
func notifyServer(forRegion:CLRegion, transition:Transition, location:CLLocation?){ func notifyServer(forRegion:CLRegion, transition:Transition, location:CLLocation?, userProfile:[String:Any?]){
df.dateFormat = "MMM/dd/yyyy hh:mm:ss" if let patientId = userProfile["PatientID"] as? Int{
var userInfo = UserDefaults.standard.string(forKey: "flutter.imei-user-data")
if(userInfo == nil){
userInfo = UserDefaults.standard.string(forKey: "flutter.user-profile")
}
if let userProfile = userProfile(),
let patientId = userProfile["PatientID"] as? Int{
if let idString = forRegion.identifier.split(separator: "_").first, let idInt = Int(idString){ if let idString = forRegion.identifier.split(separator: "_").first, let idInt = Int(idString){
let body:[String:Any] = [ let body:[String:Any] = [
@ -170,19 +161,18 @@ extension HMG_Geofence{
"GeoType":transition.rawValue, "GeoType":transition.rawValue,
"PatientID":patientId "PatientID":patientId
] ]
var logs = UserDefaults.init(suiteName: "GeoFenceLog")?.dictionary(forKey: "GEOFENCE_LOGS") ?? [:]
var geo = (logs[forRegion.identifier] as? [String]) ?? []
let url = "https://hmgwebservices.com/Services/Patients.svc/REST/GeoF_InsertPatientFileInfo" let url = "https://hmgwebservices.com/Services/Patients.svc/REST/GeoF_InsertPatientFileInfo"
httpPostRequest(urlString: url, jsonBody: body){ (status,json) in httpPostRequest(urlString: url, jsonBody: body){ (status,json) in
let status_ = status ? "Notified" : "Not notified" let status_ = status ? "Notified successfully:" : "Failed to notify:"
showNotification(title: transition.name(), subtitle: forRegion.identifier, message: status_) showNotification(title: transition.name(), subtitle: forRegion.identifier, message: status_)
var logs = UserDefaults.init(suiteName: "GeoFenceLog")?.dictionary(forKey: "GEOFENCE_LOGS") ?? [:] geo.append("\(status_) \(transition.name()) at \(Date().toString(format: "dd/MMM/yyy hh:mm:ss"))")
if var geo = logs[forRegion.identifier] as? [String]{ logs.updateValue( geo, forKey: forRegion.identifier)
geo.append("\(status_) at \(df.string(from: Date()))")
}else{
logs.updateValue(["\(status_) at \(df.string(from: Date()))"], forKey: forRegion.identifier)
}
UserDefaults.init(suiteName: "GeoFenceLog")?.set(logs, forKey: "GEOFENCE_LOGS") UserDefaults.init(suiteName: "GeoFenceLog")?.set(logs, forKey: "GEOFENCE_LOGS")
} }

@ -47,18 +47,28 @@ class HMGNetworkConnectivity {
void confirmFromUser() { void confirmFromUser() {
TranslationBase translator = TranslationBase.of(context); TranslationBase translator = TranslationBase.of(context);
ConfirmDialog(
context: context, void doIt() {
confirmMessage: translator.wantToConnectWithHmgNetwork, ConfirmDialog(
okText: translator.yes, context: context,
okFunction: () { confirmMessage: translator.wantToConnectWithHmgNetwork,
ConfirmDialog.closeAlertDialog(context); okText: translator.yes,
callBack(); okFunction: () {
}, ConfirmDialog.closeAlertDialog(context);
cancelText: translator.no, callBack();
cancelFunction: () { },
ConfirmDialog.closeAlertDialog(context); cancelText: translator.no,
}).showAlertDialog(context); cancelFunction: () {
ConfirmDialog.closeAlertDialog(context);
}).showAlertDialog(context);
}
if (Platform.isAndroid)
Wifi.list(SSID).then((value) {
if (!value.indexWhere((element) => element.ssid == SSID).isNegative) doIt();
});
else
doIt();
} }
void showFailDailog(String message) { void showFailDailog(String message) {

Loading…
Cancel
Save