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" />
<!-- Geofencing -->
<service android:name=".geofence.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.GeofencingRebootBroadcastReceiver" android:enabled="true">
<service android:name=".geofence.intent_receivers.GeofenceTransitionsJobIntentService" android:exported="true" android:permission="android.permission.BIND_JOB_SERVICE" />
<receiver android:name=".geofence.intent_receivers.GeofenceBroadcastReceiver" android:enabled="true" android:exported="true" />
<receiver android:name=".geofence.intent_receivers.GeofencingRebootBroadcastReceiver" android:enabled="true">
<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>
</receiver>

@ -8,6 +8,7 @@ import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.location.Location
import androidx.core.content.ContextCompat
import com.cloud.diplomaticquarterapp.geofence.intent_receivers.GeofenceBroadcastReceiver
import com.cloud.diplomaticquarterapp.utils.*
import com.google.android.gms.location.Geofence
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.Context
import android.content.Intent
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.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.Context
import android.content.Intent
class GeofenceBroadcastReceiverWithService : BroadcastReceiver() {
class GeofenceBroadcastReceiverWithJobService : BroadcastReceiver() {
override fun onReceive(context: Context, intent: 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 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.Intent
import android.location.Location
import android.util.Log
import androidx.core.app.JobIntentService
import com.cloud.diplomaticquarterapp.utils.API
import com.cloud.diplomaticquarterapp.utils.httpPost
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.cloud.diplomaticquarterapp.geofence.GeofenceTransition
import com.cloud.diplomaticquarterapp.geofence.HMG_Geofence
import com.google.android.gms.location.Geofence
import com.google.android.gms.location.GeofencingEvent
import com.google.gson.Gson
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.Context
import android.content.Intent
import android.os.Handler
import android.os.Message
import com.cloud.diplomaticquarterapp.geofence.HMG_Geofence
import com.cloud.diplomaticquarterapp.geofence.PREFS_STORAGE
import com.cloud.diplomaticquarterapp.utils.HMGUtils
class GeofencingRebootBroadcastReceiver : BroadcastReceiver(){
override fun onReceive(context: Context, intent: Intent) {
// if (Intent.ACTION_BOOT_COMPLETED.equals(intent.action)) {
if (intent.action.equals("android.intent.action.BOOT_COMPLETE")) {
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.action)) {
// if (intent.action.equals("android.intent.action.BOOT_COMPLETE")) {
val pref = context.getSharedPreferences(PREFS_STORAGE, Context.MODE_PRIVATE)
pref.edit().putString("REBOOT_DETECTED","YES").apply()

@ -126,7 +126,7 @@ fun sendNotification(context: Context, title:String, @Nullable subtitle:String?,
.addNextIntent(intent)
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)
.setContentIntent(notificationPendingIntent)
.setAutoCancel(true)
@ -154,9 +154,9 @@ fun isJSONValid(jsonString: String?): Boolean {
fun saveLog(context:Context, tag:String, message:String){
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"
pref.edit().putString("PLATFORM_LOGS", logs).apply();
pref.edit().putString("GEOFENCE_LOGS", logs).apply();
}
class HTTPResponse<T>(data: T){

@ -1 +1 @@
3f3d14a0ae775b56806906c2cb14a1f0
d9d141e787a8aa802f90b776d75f04fc

@ -2,6 +2,7 @@ import UIKit
import Flutter
import GoogleMaps
var userNotificationCenterDelegate:UNUserNotificationCenterDelegate? = nil
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
@ -12,6 +13,7 @@ import GoogleMaps
GMSServices.provideAPIKey("AIzaSyCiiJiHkocPbcziHt9O8rGWavDrxHRQys8")
GeneratedPluginRegistrant.register(with: self)
if let mainViewController = window.rootViewController as? MainFlutterVC{
HMGPlatformBridge.initialize(flutterViewController: mainViewController)
}
@ -20,6 +22,18 @@ import GoogleMaps
HMG_Geofence.initGeofencing()
}
UNUserNotificationCenter.current().delegate = self
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{
func merge(dict:[String:Any?]) -> [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 notificationContent = UNMutableNotificationContent()
if identifier != nil { notificationContent.categoryIdentifier = identifier! }
if title != nil { notificationContent.title = title! }
if subtitle != nil { notificationContent.body = message! }
if message != nil { notificationContent.subtitle = subtitle! }
notificationContent.sound = UNNotificationSound.default
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
let request = UNNotificationRequest(identifier: "\(Date().timeIntervalSinceNow)", content: notificationContent, trigger: trigger)
UNUserNotificationCenter.current().add(request) { error in
if let error = error {
print("Error: \(error)")
let HmgLocalNotificationCategoryIdentifier = "hmg.local.notification"
func showNotification(identifier:String? = nil, title:String?, subtitle:String?, message:String?, sound:UNNotificationSound = UNNotificationSound.default, categoryIdentifier:String = HmgLocalNotificationCategoryIdentifier){
DispatchQueue.main.async {
let notificationContent = UNMutableNotificationContent()
notificationContent.categoryIdentifier = categoryIdentifier
if identifier != nil { notificationContent.categoryIdentifier = identifier! }
if title != nil { notificationContent.title = title! }
if subtitle != nil { notificationContent.body = message! }
if message != nil { notificationContent.subtitle = subtitle! }
notificationContent.sound = UNNotificationSound.default
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
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)
}
}else{
completion?(false,nil)
}
}

@ -129,8 +129,10 @@ extension HMG_Geofence : CLLocationManagerDelegate{
extension HMG_Geofence{
func handleEvent(for region: CLRegion!, transition:Transition, location:CLLocation?) {
notifyUser(forRegion: region, transition: transition, location: locationManager.location)
notifyServer(forRegion: region, transition: transition, location: locationManager.location)
if let userProfile = userProfile(){
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? {
@ -144,25 +146,14 @@ extension HMG_Geofence{
}
func notifyUser(forRegion:CLRegion, transition:Transition, location:CLLocation?){
if let zone = geoZone(by: forRegion.identifier){
if UIApplication.shared.applicationState == .active {
mainViewController.showAlert(withTitle: transition.name(), message: zone.message())
}else{
}
func notifyUser(forRegion:CLRegion, transition:Transition, location:CLLocation?, userProfile:[String:Any?]){
if let patientId = userProfile["PatientID"] as? Int{
}
}
func notifyServer(forRegion:CLRegion, transition:Transition, location:CLLocation?){
df.dateFormat = "MMM/dd/yyyy hh:mm:ss"
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{
func notifyServer(forRegion:CLRegion, transition:Transition, location:CLLocation?, userProfile:[String:Any?]){
if let patientId = userProfile["PatientID"] as? Int{
if let idString = forRegion.identifier.split(separator: "_").first, let idInt = Int(idString){
let body:[String:Any] = [
@ -170,19 +161,18 @@ extension HMG_Geofence{
"GeoType":transition.rawValue,
"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"
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_)
var logs = UserDefaults.init(suiteName: "GeoFenceLog")?.dictionary(forKey: "GEOFENCE_LOGS") ?? [:]
if var geo = logs[forRegion.identifier] as? [String]{
geo.append("\(status_) at \(df.string(from: Date()))")
}else{
logs.updateValue(["\(status_) at \(df.string(from: Date()))"], forKey: forRegion.identifier)
}
geo.append("\(status_) \(transition.name()) at \(Date().toString(format: "dd/MMM/yyy hh:mm:ss"))")
logs.updateValue( geo, forKey: forRegion.identifier)
UserDefaults.init(suiteName: "GeoFenceLog")?.set(logs, forKey: "GEOFENCE_LOGS")
}

@ -47,18 +47,28 @@ class HMGNetworkConnectivity {
void confirmFromUser() {
TranslationBase translator = TranslationBase.of(context);
ConfirmDialog(
context: context,
confirmMessage: translator.wantToConnectWithHmgNetwork,
okText: translator.yes,
okFunction: () {
ConfirmDialog.closeAlertDialog(context);
callBack();
},
cancelText: translator.no,
cancelFunction: () {
ConfirmDialog.closeAlertDialog(context);
}).showAlertDialog(context);
void doIt() {
ConfirmDialog(
context: context,
confirmMessage: translator.wantToConnectWithHmgNetwork,
okText: translator.yes,
okFunction: () {
ConfirmDialog.closeAlertDialog(context);
callBack();
},
cancelText: translator.no,
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) {

Loading…
Cancel
Save