Search in sources :

Example 61 with LocationManager

use of android.location.LocationManager in project Osmand by osmandapp.

the class SampleLocationProvider method resumeAllUpdates.

public void resumeAllUpdates() {
    final LocationManager service = (LocationManager) app.getSystemService(Context.LOCATION_SERVICE);
    if (app.isInternetConnectionAvailable()) {
        if (System.currentTimeMillis() - agpsDataLastTimeDownloaded > AGPS_TO_REDOWNLOAD) {
            // force an updated check for internet connectivity here before destroying A-GPS-data
            if (app.isInternetConnectionAvailable(true)) {
                redownloadAGPS();
            }
        }
    }
    if (isLocationPermissionAvailable(app)) {
        service.addGpsStatusListener(getGpsStatusListener(service));
        try {
            service.requestLocationUpdates(LocationManager.GPS_PROVIDER, GPS_TIMEOUT_REQUEST, GPS_DIST_REQUEST, gpsListener);
        } catch (IllegalArgumentException e) {
            // $NON-NLS-1$
            Log.d(PlatformUtil.TAG, "GPS location provider not available");
        }
        // try to always ask for network provide : it is faster way to find location
        List<String> providers = service.getProviders(true);
        if (providers == null) {
            return;
        }
        for (String provider : providers) {
            if (provider == null || provider.equals(LocationManager.GPS_PROVIDER)) {
                continue;
            }
            try {
                NetworkListener networkListener = new NetworkListener();
                service.requestLocationUpdates(provider, GPS_TIMEOUT_REQUEST, GPS_DIST_REQUEST, networkListener);
                networkListeners.add(networkListener);
            } catch (IllegalArgumentException e) {
                // $NON-NLS-1$
                Log.d(PlatformUtil.TAG, provider + " location provider not available");
            }
        }
    }
}
Also used : LocationManager(android.location.LocationManager)

Example 62 with LocationManager

use of android.location.LocationManager in project Osmand by osmandapp.

the class SampleLocationProvider method redownloadAGPS.

public void redownloadAGPS() {
    try {
        final LocationManager service = (LocationManager) app.getSystemService(Context.LOCATION_SERVICE);
        service.sendExtraCommand(LocationManager.GPS_PROVIDER, "delete_aiding_data", null);
        Bundle bundle = new Bundle();
        service.sendExtraCommand("gps", "force_xtra_injection", bundle);
        service.sendExtraCommand("gps", "force_time_injection", bundle);
        agpsDataLastTimeDownloaded = System.currentTimeMillis();
    } catch (Exception e) {
        agpsDataLastTimeDownloaded = 0L;
        e.printStackTrace();
    }
}
Also used : LocationManager(android.location.LocationManager) Bundle(android.os.Bundle)

Example 63 with LocationManager

use of android.location.LocationManager in project opacclient by opacapp.

the class LibraryListActivity method showListGeo.

public void showListGeo() {
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.ACCESS_COARSE_LOCATION }, REQUEST_LOCATION_PERMISSION);
        return;
    }
    final LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    // no GPS
    criteria.setAccuracy(Criteria.ACCURACY_COARSE);
    final String provider = locationManager.getBestProvider(criteria, true);
    if (provider == null) {
        Toast.makeText(this, R.string.geolocate_not_available, Toast.LENGTH_LONG).show();
        tvLocateString.setText(R.string.geolocate);
        ivLocationIcon.setImageResource(R.drawable.ic_locate_24dp);
        return;
    }
    if (libraries == null) {
        return;
    }
    locationManager.requestLocationUpdates(provider, 0, 0, new LocationListener() {

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }

        @Override
        public void onProviderEnabled(String provider) {
        }

        @Override
        public void onProviderDisabled(String provider) {
        }

        @Override
        public void onLocationChanged(Location location) {
            if (!visible) {
                return;
            }
            fragment = new LocatedLibraryListFragment();
            Bundle args = new Bundle();
            args.putInt("level", LEVEL_LIBRARY);
            fragment.setArguments(args);
            if (location != null && libraries != null) {
                double lat = location.getLatitude();
                double lon = location.getLongitude();
                // Calculate distances
                List<Library> distancedlibs = new ArrayList<>();
                for (Library lib : libraries) {
                    float[] result = new float[1];
                    double[] geo = lib.getGeo();
                    if (geo == null) {
                        continue;
                    }
                    Location.distanceBetween(lat, lon, geo[0], geo[1], result);
                    lib.setGeo_distance(result[0]);
                    distancedlibs.add(lib);
                }
                Collections.sort(distancedlibs, new DistanceComparator());
                if (distancedlibs.size() > 20) {
                    distancedlibs = distancedlibs.subList(0, 20);
                }
                LibraryAdapter adapter = new LibraryAdapter(LibraryListActivity.this, R.layout.listitem_library, R.id.tvTitle, distancedlibs);
                fragment.setListAdapter(adapter);
                getSupportFragmentManager().beginTransaction().addToBackStack(null).setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE).replace(R.id.container, fragment).commit();
                if (fragment2 != null) {
                    getSupportFragmentManager().beginTransaction().detach(fragment2).commit();
                }
                if (fragment3 != null) {
                    getSupportFragmentManager().beginTransaction().detach(fragment3).commit();
                }
                if (fragment4 != null) {
                    getSupportFragmentManager().beginTransaction().detach(fragment4).commit();
                }
                tvLocateString.setText(R.string.alphabetic_list);
                ivLocationIcon.setImageResource(R.drawable.ic_list_24dp);
            }
        }
    });
}
Also used : LocationManager(android.location.LocationManager) Bundle(android.os.Bundle) Criteria(android.location.Criteria) LocationListener(android.location.LocationListener) List(java.util.List) ArrayList(java.util.ArrayList) Library(de.geeksfactory.opacclient.objects.Library) Location(android.location.Location)

Example 64 with LocationManager

use of android.location.LocationManager in project PhoneProfilesPlus by henrichg.

the class ActivateProfileHelper method doExecuteForRadios.

private static void doExecuteForRadios(Context context, Profile profile) {
    PPApplication.sleep(300);
    // setup network type
    if (profile._deviceNetworkType >= 100) {
        if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_DEVICE_NETWORK_TYPE, context) == PPApplication.PREFERENCE_ALLOWED) {
            setPreferredNetworkType(context, profile._deviceNetworkType - 100);
            // try { Thread.sleep(200); } catch (InterruptedException e) { }
            // SystemClock.sleep(200);
            PPApplication.sleep(200);
        }
    }
    // setup mobile data
    if (profile._deviceMobileData != 0) {
        if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_DEVICE_MOBILE_DATA, context) == PPApplication.PREFERENCE_ALLOWED) {
            boolean _isMobileData = isMobileData(context);
            // PPApplication.logE("ActivateProfileHelper.doExecuteForRadios","_isMobileData="+_isMobileData);
            boolean _setMobileData = false;
            switch(profile._deviceMobileData) {
                case 1:
                    if (!_isMobileData) {
                        _isMobileData = true;
                        _setMobileData = true;
                    }
                    break;
                case 2:
                    if (_isMobileData) {
                        _isMobileData = false;
                        _setMobileData = true;
                    }
                    break;
                case 3:
                    _isMobileData = !_isMobileData;
                    _setMobileData = true;
                    break;
            }
            if (_setMobileData) {
                setMobileData(context, _isMobileData);
                // try { Thread.sleep(200); } catch (InterruptedException e) { }
                // SystemClock.sleep(200);
                PPApplication.sleep(200);
            }
        }
    }
    // setup WiFi AP
    boolean canChangeWifi = true;
    if (profile._deviceWiFiAP != 0) {
        if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_DEVICE_WIFI_AP, context) == PPApplication.PREFERENCE_ALLOWED) {
            PPApplication.logE("$$$ WifiAP", "ActivateProfileHelper.doExecuteForRadios-start");
            WifiApManager wifiApManager = null;
            try {
                wifiApManager = new WifiApManager(context);
            } catch (Exception ignored) {
            }
            if (wifiApManager != null) {
                PPApplication.logE("$$$ WifiAP", "ActivateProfileHelper.doExecuteForRadios-wifiApManager!=null");
                boolean setWifiAPState = false;
                boolean isWifiAPEnabled = wifiApManager.isWifiAPEnabled();
                PPApplication.logE("$$$ WifiAP", "ActivateProfileHelper.doExecuteForRadios-isWifiAPEnabled=" + isWifiAPEnabled);
                switch(profile._deviceWiFiAP) {
                    case 1:
                        if (!isWifiAPEnabled) {
                            isWifiAPEnabled = true;
                            setWifiAPState = true;
                            canChangeWifi = false;
                        }
                        break;
                    case 2:
                        if (isWifiAPEnabled) {
                            isWifiAPEnabled = false;
                            setWifiAPState = true;
                            canChangeWifi = true;
                        }
                        break;
                    case 3:
                        isWifiAPEnabled = !isWifiAPEnabled;
                        setWifiAPState = true;
                        canChangeWifi = !isWifiAPEnabled;
                        break;
                }
                PPApplication.logE("$$$ WifiAP", "ActivateProfileHelper.doExecuteForRadios-setWifiAPState=" + setWifiAPState);
                PPApplication.logE("$$$ WifiAP", "ActivateProfileHelper.doExecuteForRadios-isWifiAPEnabled=" + isWifiAPEnabled);
                PPApplication.logE("$$$ WifiAP", "ActivateProfileHelper.doExecuteForRadios-canChangeWifi=" + canChangeWifi);
                if (setWifiAPState) {
                    setWifiAP(wifiApManager, isWifiAPEnabled, context);
                    // try { Thread.sleep(200); } catch (InterruptedException e) { }
                    // SystemClock.sleep(200);
                    PPApplication.sleep(200);
                }
            }
        }
    }
    if (canChangeWifi) {
        // setup Wi-Fi
        if (profile._deviceWiFi != 0) {
            if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_DEVICE_WIFI, context) == PPApplication.PREFERENCE_ALLOWED) {
                boolean isWifiAPEnabled = WifiApManager.isWifiAPEnabled(context);
                if ((!isWifiAPEnabled) || (profile._deviceWiFi == 4)) {
                    // only when wifi AP is not enabled, change wifi
                    PPApplication.logE("$$$ WifiAP", "ActivateProfileHelper.doExecuteForRadios-isWifiAPEnabled=false");
                    WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
                    if (wifiManager != null) {
                        int wifiState = wifiManager.getWifiState();
                        boolean isWifiEnabled = ((wifiState == WifiManager.WIFI_STATE_ENABLED) || (wifiState == WifiManager.WIFI_STATE_ENABLING));
                        boolean setWifiState = false;
                        switch(profile._deviceWiFi) {
                            case 1:
                            case 4:
                                if (!isWifiEnabled) {
                                    isWifiEnabled = true;
                                    setWifiState = true;
                                }
                                break;
                            case 2:
                                if (isWifiEnabled) {
                                    isWifiEnabled = false;
                                    setWifiState = true;
                                }
                                break;
                            case 3:
                            case 5:
                                isWifiEnabled = !isWifiEnabled;
                                setWifiState = true;
                                break;
                        }
                        if (isWifiEnabled)
                            // when wifi is enabled from profile, no disable wifi after scan
                            WifiScanJob.setWifiEnabledForScan(context, false);
                        if (setWifiState) {
                            try {
                                wifiManager.setWifiEnabled(isWifiEnabled);
                            } catch (Exception e) {
                                Log.e("ActivateProfileHelper.doExecuteForRadios", Log.getStackTraceString(e));
                            }
                            // try { Thread.sleep(200); } catch (InterruptedException e) { }
                            // SystemClock.sleep(200);
                            PPApplication.sleep(200);
                        }
                    }
                }
            }
        }
        // connect to SSID
        if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_DEVICE_CONNECT_TO_SSID, context) == PPApplication.PREFERENCE_ALLOWED) {
            if (!profile._deviceConnectToSSID.equals(Profile.CONNECTTOSSID_JUSTANY)) {
                if (Permissions.checkLocation(context)) {
                    WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
                    if (wifiManager != null) {
                        int wifiState = wifiManager.getWifiState();
                        if (wifiState == WifiManager.WIFI_STATE_ENABLED) {
                            // check if wifi is connected
                            ConnectivityManager connManager = null;
                            try {
                                connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                            } catch (Exception ignored) {
                            // java.lang.NullPointerException: missing IConnectivityManager
                            // Dual SIM?? Bug in Android ???
                            }
                            if (connManager != null) {
                                NetworkInfo activeNetwork = connManager.getActiveNetworkInfo();
                                boolean wifiConnected = (activeNetwork != null) && (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) && activeNetwork.isConnected();
                                WifiInfo wifiInfo = null;
                                if (wifiConnected)
                                    wifiInfo = wifiManager.getConnectionInfo();
                                List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
                                if (list != null) {
                                    for (WifiConfiguration i : list) {
                                        if (i.SSID != null && i.SSID.equals(profile._deviceConnectToSSID)) {
                                            if (wifiConnected) {
                                                if (!wifiInfo.getSSID().equals(i.SSID)) {
                                                    PhoneProfilesService.connectToSSIDStarted = true;
                                                    // connected to another SSID
                                                    wifiManager.disconnect();
                                                    wifiManager.enableNetwork(i.networkId, true);
                                                    wifiManager.reconnect();
                                                }
                                            } else
                                                wifiManager.enableNetwork(i.networkId, true);
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            // else {
            // WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            // int wifiState = wifiManager.getWifiState();
            // if  (wifiState == WifiManager.WIFI_STATE_ENABLED) {
            // wifiManager.disconnect();
            // wifiManager.reconnect();
            // }
            // }
            PhoneProfilesService.connectToSSID = profile._deviceConnectToSSID;
        }
    }
    // setup bluetooth
    if (profile._deviceBluetooth != 0) {
        if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_DEVICE_BLUETOOTH, context) == PPApplication.PREFERENCE_ALLOWED) {
            PPApplication.logE("ActivateProfileHelper.doExecuteForRadios", "setBluetooth");
            BluetoothAdapter bluetoothAdapter = BluetoothScanJob.getBluetoothAdapter(context);
            if (bluetoothAdapter != null) {
                boolean isBluetoothEnabled = bluetoothAdapter.isEnabled();
                boolean setBluetoothState = false;
                switch(profile._deviceBluetooth) {
                    case 1:
                        if (!isBluetoothEnabled) {
                            isBluetoothEnabled = true;
                            setBluetoothState = true;
                        }
                        break;
                    case 2:
                        if (isBluetoothEnabled) {
                            isBluetoothEnabled = false;
                            setBluetoothState = true;
                        }
                        break;
                    case 3:
                        isBluetoothEnabled = !isBluetoothEnabled;
                        setBluetoothState = true;
                        break;
                }
                PPApplication.logE("ActivateProfileHelper.doExecuteForRadios", "setBluetoothState=" + setBluetoothState);
                PPApplication.logE("ActivateProfileHelper.doExecuteForRadios", "isBluetoothEnabled=" + isBluetoothEnabled);
                if (isBluetoothEnabled) {
                    // when bluetooth is enabled from profile, no disable bluetooth after scan
                    PPApplication.logE("ActivateProfileHelper.doExecuteForRadios", "isBluetoothEnabled=true; setBluetoothEnabledForScan=false");
                    BluetoothScanJob.setBluetoothEnabledForScan(context, false);
                }
                if (setBluetoothState) {
                    if (isBluetoothEnabled)
                        bluetoothAdapter.enable();
                    else
                        bluetoothAdapter.disable();
                }
            }
        }
    }
    // setup GPS
    if (profile._deviceGPS != 0) {
        if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_DEVICE_GPS, context) == PPApplication.PREFERENCE_ALLOWED) {
            // String provider = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
            boolean isEnabled = false;
            boolean ok = true;
            /*if (android.os.Build.VERSION.SDK_INT < 19)
                    isEnabled = Settings.Secure.isLocationProviderEnabled(context.getContentResolver(), LocationManager.GPS_PROVIDER);
                else {*/
            LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
            if (locationManager != null)
                isEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
            else
                ok = false;
            // }
            if (ok) {
                PPApplication.logE("ActivateProfileHelper.doExecuteForRadios", "isEnabled=" + isEnabled);
                switch(profile._deviceGPS) {
                    case 1:
                        setGPS(context, true);
                        break;
                    case 2:
                        setGPS(context, false);
                        break;
                    case 3:
                        if (!isEnabled) {
                            setGPS(context, true);
                        } else {
                            setGPS(context, false);
                        }
                        break;
                }
            }
        }
    }
    // setup NFC
    if (profile._deviceNFC != 0) {
        if (Profile.isProfilePreferenceAllowed(Profile.PREF_PROFILE_DEVICE_NFC, context) == PPApplication.PREFERENCE_ALLOWED) {
            NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(context);
            if (nfcAdapter != null) {
                switch(profile._deviceNFC) {
                    case 1:
                        setNFC(context, true);
                        break;
                    case 2:
                        setNFC(context, false);
                        break;
                    case 3:
                        if (!nfcAdapter.isEnabled()) {
                            setNFC(context, true);
                        } else if (nfcAdapter.isEnabled()) {
                            setNFC(context, false);
                        }
                        break;
                }
            }
        }
    }
}
Also used : LocationManager(android.location.LocationManager) WifiManager(android.net.wifi.WifiManager) WifiConfiguration(android.net.wifi.WifiConfiguration) NetworkInfo(android.net.NetworkInfo) ConnectivityManager(android.net.ConnectivityManager) IOException(java.io.IOException) SuppressLint(android.annotation.SuppressLint) WifiInfo(android.net.wifi.WifiInfo) NfcAdapter(android.nfc.NfcAdapter) BluetoothAdapter(android.bluetooth.BluetoothAdapter)

Example 65 with LocationManager

use of android.location.LocationManager in project PhoneProfilesPlus by henrichg.

the class DataWrapper method doHandleEvents.

@SuppressLint({ "NewApi", "SimpleDateFormat" })
void doHandleEvents(Event event, boolean statePause, boolean restartEvent, /*boolean interactive,*/
boolean forDelayStartAlarm, boolean forDelayEndAlarm, boolean reactivate, Profile mergedProfile, String sensorType) {
    if (!Permissions.grantEventPermissions(context, event, true))
        return;
    // = Event.ESTATUS_NONE;
    int newEventStatus;
    boolean ignoreTime = false;
    boolean ignoreBattery = false;
    boolean ignoreCall = false;
    boolean ignorePeripheral = false;
    boolean ignoreCalendar = false;
    boolean ignoreWifi = false;
    boolean ignoreScreen = false;
    boolean ignoreBluetooth = false;
    boolean ignoreSms = false;
    boolean ignoreNotification = false;
    boolean ignoreApplication = false;
    boolean ignoreLocation = false;
    boolean ignoreOrientation = false;
    boolean ignoreMobileCell = false;
    boolean ignoreNfc = false;
    boolean ignoreRadioSwitch = false;
    boolean timePassed = true;
    boolean batteryPassed = true;
    boolean callPassed = true;
    boolean peripheralPassed = true;
    boolean calendarPassed = true;
    boolean wifiPassed = true;
    boolean screenPassed = true;
    boolean bluetoothPassed = true;
    boolean smsPassed = true;
    boolean notificationPassed = true;
    boolean applicationPassed = true;
    boolean locationPassed = true;
    boolean orientationPassed = true;
    boolean mobileCellPassed = true;
    boolean nfcPassed = true;
    boolean radioSwitchPassed = true;
    PPApplication.logE("%%%%%%% DataWrapper.doHandleEvents", "--- start --------------------------");
    PPApplication.logE("%%%%%%% DataWrapper.doHandleEvents", "------- event._id=" + event._id);
    PPApplication.logE("%%%%%%% DataWrapper.doHandleEvents", "------- event._name=" + event._name);
    PPApplication.logE("%%%%%%% DataWrapper.doHandleEvents", "------- sensorType=" + sensorType);
    if (event._eventPreferencesTime._enabled && (Event.isEventPreferenceAllowed(EventPreferencesTime.PREF_EVENT_TIME_ENABLED, context) == PPApplication.PREFERENCE_ALLOWED)) {
        // compute start datetime
        long startAlarmTime;
        long endAlarmTime;
        startAlarmTime = event._eventPreferencesTime.computeAlarm(true);
        String alarmTimeS = DateFormat.getDateFormat(context).format(startAlarmTime) + " " + DateFormat.getTimeFormat(context).format(startAlarmTime);
        PPApplication.logE("%%% DataWrapper.doHandleEvents", "startAlarmTime=" + alarmTimeS);
        endAlarmTime = event._eventPreferencesTime.computeAlarm(false);
        alarmTimeS = DateFormat.getDateFormat(context).format(endAlarmTime) + " " + DateFormat.getTimeFormat(context).format(endAlarmTime);
        PPApplication.logE("%%% DataWrapper.doHandleEvents", "endAlarmTime=" + alarmTimeS);
        Calendar now = Calendar.getInstance();
        long nowAlarmTime = now.getTimeInMillis();
        alarmTimeS = DateFormat.getDateFormat(context).format(nowAlarmTime) + " " + DateFormat.getTimeFormat(context).format(nowAlarmTime);
        PPApplication.logE("%%% DataWrapper.doHandleEvents", "nowAlarmTime=" + alarmTimeS);
        timePassed = ((nowAlarmTime >= startAlarmTime) && (nowAlarmTime < endAlarmTime));
        PPApplication.logE("%%% DataWrapper.doHandleEvents", "timePassed=" + timePassed);
    // eventStart = eventStart && timePassed;
    }
    if (event._eventPreferencesBattery._enabled && (Event.isEventPreferenceAllowed(EventPreferencesBattery.PREF_EVENT_BATTERY_ENABLED, context) == PPApplication.PREFERENCE_ALLOWED)) {
        boolean isPowerSaveMode = isPowerSaveMode(context);
        PPApplication.logE("*** DataWrapper.doHandleEvents", "isPowerSaveMode=" + isPowerSaveMode);
        boolean isCharging;
        int batteryPct;
        // get battery status
        Intent batteryStatus = null;
        try {
            // Huawei devices: java.lang.IllegalArgumentException: regist too many Broadcast Receivers
            IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
            batteryStatus = context.registerReceiver(null, filter);
        } catch (Exception ignored) {
        }
        if (batteryStatus != null) {
            batteryPassed = false;
            int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
            PPApplication.logE("*** DataWrapper.doHandleEvents", "status=" + status);
            isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL;
            PPApplication.logE("*** DataWrapper.doHandleEvents", "isCharging=" + isCharging);
            int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
            int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
            PPApplication.logE("*** DataWrapper.doHandleEvents", "level=" + level);
            PPApplication.logE("*** DataWrapper.doHandleEvents", "scale=" + scale);
            batteryPct = Math.round(level / (float) scale * 100);
            PPApplication.logE("*** DataWrapper.doHandleEvents", "batteryPct=" + batteryPct);
            if ((batteryPct >= event._eventPreferencesBattery._levelLow) && (batteryPct <= event._eventPreferencesBattery._levelHight))
                batteryPassed = true;
            if (event._eventPreferencesBattery._charging > 0) {
                if (event._eventPreferencesBattery._charging == 1)
                    batteryPassed = batteryPassed && isCharging;
                else
                    batteryPassed = batteryPassed && (!isCharging);
            } else if (event._eventPreferencesBattery._powerSaveMode)
                batteryPassed = batteryPassed && isPowerSaveMode;
        } else
            ignoreBattery = true;
    }
    if ((event._eventPreferencesCall._enabled) && (Event.isEventPreferenceAllowed(EventPreferencesCall.PREF_EVENT_CALL_ENABLED, context) == PPApplication.PREFERENCE_ALLOWED) && Permissions.checkEventCallContacts(context, event, null) && Permissions.checkEventPhoneBroadcast(context, event, null)) {
        ApplicationPreferences.getSharedPreferences(context);
        int callEventType = ApplicationPreferences.preferences.getInt(PhoneCallBroadcastReceiver.PREF_EVENT_CALL_EVENT_TYPE, PhoneCallBroadcastReceiver.CALL_EVENT_UNDEFINED);
        String phoneNumber = ApplicationPreferences.preferences.getString(PhoneCallBroadcastReceiver.PREF_EVENT_CALL_PHONE_NUMBER, "");
        PPApplication.logE("[CALL] DataWrapper.doHandleEvents", "callEventType=" + callEventType);
        PPApplication.logE("[CALL] DataWrapper.doHandleEvents", "phoneNumber=" + phoneNumber);
        boolean phoneNumberFound = false;
        if (callEventType != PhoneCallBroadcastReceiver.CALL_EVENT_UNDEFINED) {
            if (event._eventPreferencesCall._contactListType != EventPreferencesCall.CONTACT_LIST_TYPE_NOT_USE) {
                PPApplication.logE("[CALL] DataWrapper.doHandleEvents", "search in gropus");
                // find phone number in groups
                String[] splits = event._eventPreferencesCall._contactGroups.split("\\|");
                for (String split : splits) {
                    String[] projection = new String[] { ContactsContract.CommonDataKinds.GroupMembership.CONTACT_ID };
                    String selection = ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID + "=? AND " + ContactsContract.CommonDataKinds.GroupMembership.MIMETYPE + "='" + ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE + "'";
                    String[] selectionArgs = new String[] { split };
                    Cursor mCursor = context.getContentResolver().query(ContactsContract.Data.CONTENT_URI, projection, selection, selectionArgs, null);
                    if (mCursor != null) {
                        while (mCursor.moveToNext()) {
                            String contactId = mCursor.getString(mCursor.getColumnIndex(ContactsContract.CommonDataKinds.GroupMembership.CONTACT_ID));
                            String[] projection2 = new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER };
                            String selection2 = ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=?" + " and " + ContactsContract.CommonDataKinds.Phone.HAS_PHONE_NUMBER + "=1";
                            String[] selection2Args = new String[] { contactId };
                            Cursor phones = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection2, selection2, selection2Args, null);
                            if (phones != null) {
                                while (phones.moveToNext()) {
                                    String _phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                                    if (PhoneNumberUtils.compare(_phoneNumber, phoneNumber)) {
                                        phoneNumberFound = true;
                                        break;
                                    }
                                }
                                phones.close();
                            }
                            if (phoneNumberFound)
                                break;
                        }
                        mCursor.close();
                    }
                    if (phoneNumberFound)
                        break;
                }
                if (!phoneNumberFound) {
                    PPApplication.logE("[CALL] DataWrapper.doHandleEvents", "search in contacts");
                    // find phone number in contacts
                    splits = event._eventPreferencesCall._contacts.split("\\|");
                    for (String split : splits) {
                        // PPApplication.logE("[CALL] DataWrapper.doHandleEvents", "split="+split);
                        String[] splits2 = split.split("#");
                        // get phone number from contacts
                        String[] projection = new String[] { ContactsContract.Contacts._ID, ContactsContract.Contacts.HAS_PHONE_NUMBER };
                        String selection = ContactsContract.Contacts.HAS_PHONE_NUMBER + "='1' and " + ContactsContract.Contacts._ID + "=?";
                        String[] selectionArgs = new String[] { splits2[0] };
                        Cursor mCursor = context.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, projection, selection, selectionArgs, null);
                        if (mCursor != null) {
                            while (mCursor.moveToNext()) {
                                String[] projection2 = new String[] { ContactsContract.CommonDataKinds.Phone._ID, ContactsContract.CommonDataKinds.Phone.NUMBER };
                                String selection2 = ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=?" + " and " + ContactsContract.CommonDataKinds.Phone._ID + "=?";
                                String[] selection2Args = new String[] { splits2[0], splits2[1] };
                                Cursor phones = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection2, selection2, selection2Args, null);
                                if (phones != null) {
                                    while (phones.moveToNext()) {
                                        String _phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                                        PPApplication.logE("[CALL] DataWrapper.doHandleEvents", "_phoneNumber=" + _phoneNumber);
                                        if (PhoneNumberUtils.compare(_phoneNumber, phoneNumber)) {
                                            phoneNumberFound = true;
                                            break;
                                        }
                                    }
                                    phones.close();
                                }
                                if (phoneNumberFound)
                                    break;
                            }
                            mCursor.close();
                        }
                        if (phoneNumberFound)
                            break;
                    }
                }
                if (event._eventPreferencesCall._contactListType == EventPreferencesCall.CONTACT_LIST_TYPE_BLACK_LIST)
                    phoneNumberFound = !phoneNumberFound;
            } else
                phoneNumberFound = true;
            PPApplication.logE("[CALL] DataWrapper.doHandleEvents", "phoneNumberFound=" + phoneNumberFound);
            if (phoneNumberFound) {
                if (event._eventPreferencesCall._callEvent == EventPreferencesCall.CALL_EVENT_RINGING) {
                    // noinspection StatementWithEmptyBody
                    if ((callEventType == PhoneCallBroadcastReceiver.CALL_EVENT_INCOMING_CALL_RINGING) || ((callEventType == PhoneCallBroadcastReceiver.CALL_EVENT_INCOMING_CALL_ANSWERED)))
                        // eventStart = eventStart && true;
                        ;
                    else
                        callPassed = false;
                } else if (event._eventPreferencesCall._callEvent == EventPreferencesCall.CALL_EVENT_INCOMING_CALL_ANSWERED) {
                    // noinspection StatementWithEmptyBody
                    if (callEventType == PhoneCallBroadcastReceiver.CALL_EVENT_INCOMING_CALL_ANSWERED)
                        // eventStart = eventStart && true;
                        ;
                    else
                        callPassed = false;
                } else if (event._eventPreferencesCall._callEvent == EventPreferencesCall.CALL_EVENT_OUTGOING_CALL_STARTED) {
                    // noinspection StatementWithEmptyBody
                    if (callEventType == PhoneCallBroadcastReceiver.CALL_EVENT_OUTGOING_CALL_ANSWERED)
                        // eventStart = eventStart && true;
                        ;
                    else
                        callPassed = false;
                } else if (event._eventPreferencesCall._callEvent == EventPreferencesCall.CALL_EVENT_MISSED_CALL) {
                    // TimeZone.getDefault().getRawOffset();
                    int gmtOffset = 0;
                    long startTime = event._eventPreferencesCall._startTime - gmtOffset;
                    if (PPApplication.logEnabled()) {
                        SimpleDateFormat sdf = new SimpleDateFormat("EE d.MM.yyyy HH:mm:ss:S");
                        String alarmTimeS = sdf.format(startTime);
                        PPApplication.logE("[CALL] DataWrapper.doHandleEvents", "startTime=" + alarmTimeS);
                    }
                    // compute end datetime
                    long endAlarmTime = event._eventPreferencesCall.computeAlarm();
                    if (PPApplication.logEnabled()) {
                        SimpleDateFormat sdf = new SimpleDateFormat("EE d.MM.yyyy HH:mm:ss:S");
                        String alarmTimeS = sdf.format(endAlarmTime);
                        PPApplication.logE("[CALL] DataWrapper.doHandleEvents", "endAlarmTime=" + alarmTimeS);
                    }
                    Calendar now = Calendar.getInstance();
                    long nowAlarmTime = now.getTimeInMillis();
                    if (PPApplication.logEnabled()) {
                        SimpleDateFormat sdf = new SimpleDateFormat("EE d.MM.yyyy HH:mm:ss:S");
                        String alarmTimeS = sdf.format(nowAlarmTime);
                        PPApplication.logE("[CALL] DataWrapper.doHandleEvents", "nowAlarmTime=" + alarmTimeS);
                    }
                    if (sensorType.equals(EventsHandler.SENSOR_TYPE_PHONE_CALL)) {
                        // noinspection StatementWithEmptyBody
                        if (callEventType == PhoneCallBroadcastReceiver.CALL_EVENT_MISSED_CALL)
                            // eventStart = eventStart && true;
                            ;
                        else
                            callPassed = false;
                    } else if (!event._eventPreferencesCall._permanentRun) {
                        if (sensorType.equals(EventsHandler.SENSOR_TYPE_PHONE_CALL_EVENT_END))
                            callPassed = false;
                        else
                            callPassed = ((nowAlarmTime >= startTime) && (nowAlarmTime < endAlarmTime));
                    } else {
                        callPassed = nowAlarmTime >= startTime;
                    }
                }
                if ((callEventType == PhoneCallBroadcastReceiver.CALL_EVENT_INCOMING_CALL_ENDED) || (callEventType == PhoneCallBroadcastReceiver.CALL_EVENT_OUTGOING_CALL_ENDED)) {
                    // callPassed = true;
                    // eventStart = eventStart && false;
                    callPassed = false;
                }
            } else
                callPassed = false;
        } else
            callPassed = false;
        PPApplication.logE("[CALL] DataWrapper.doHandleEvents", "callPassed=" + callPassed);
        if (!callPassed) {
            event._eventPreferencesCall._startTime = 0;
            DatabaseHandler.getInstance(context).updateCallStartTime(event);
        }
    }
    if (event._eventPreferencesPeripherals._enabled && (Event.isEventPreferenceAllowed(EventPreferencesPeripherals.PREF_EVENT_PERIPHERAL_ENABLED, context) == PPApplication.PREFERENCE_ALLOWED)) {
        if ((event._eventPreferencesPeripherals._peripheralType == EventPreferencesPeripherals.PERIPHERAL_TYPE_DESK_DOCK) || (event._eventPreferencesPeripherals._peripheralType == EventPreferencesPeripherals.PERIPHERAL_TYPE_CAR_DOCK)) {
            // get dock status
            IntentFilter iFilter = new IntentFilter(Intent.ACTION_DOCK_EVENT);
            Intent dockStatus = context.registerReceiver(null, iFilter);
            if (dockStatus != null) {
                int dockState = dockStatus.getIntExtra(Intent.EXTRA_DOCK_STATE, -1);
                boolean isDocked = dockState != Intent.EXTRA_DOCK_STATE_UNDOCKED;
                boolean isCar = dockState == Intent.EXTRA_DOCK_STATE_CAR;
                boolean isDesk = dockState == Intent.EXTRA_DOCK_STATE_DESK || dockState == Intent.EXTRA_DOCK_STATE_LE_DESK || dockState == Intent.EXTRA_DOCK_STATE_HE_DESK;
                if (isDocked) {
                    if ((event._eventPreferencesPeripherals._peripheralType == EventPreferencesPeripherals.PERIPHERAL_TYPE_DESK_DOCK) && isDesk)
                        peripheralPassed = true;
                    else
                        peripheralPassed = (event._eventPreferencesPeripherals._peripheralType == EventPreferencesPeripherals.PERIPHERAL_TYPE_CAR_DOCK) && isCar;
                } else
                    peripheralPassed = false;
            // eventStart = eventStart && peripheralPassed;
            } else
                ignorePeripheral = true;
        } else if ((event._eventPreferencesPeripherals._peripheralType == EventPreferencesPeripherals.PERIPHERAL_TYPE_WIRED_HEADSET) || (event._eventPreferencesPeripherals._peripheralType == EventPreferencesPeripherals.PERIPHERAL_TYPE_BLUETOOTH_HEADSET) || (event._eventPreferencesPeripherals._peripheralType == EventPreferencesPeripherals.PERIPHERAL_TYPE_HEADPHONES)) {
            ApplicationPreferences.getSharedPreferences(context);
            boolean headsetConnected = ApplicationPreferences.preferences.getBoolean(HeadsetConnectionBroadcastReceiver.PREF_EVENT_HEADSET_CONNECTED, false);
            boolean headsetMicrophone = ApplicationPreferences.preferences.getBoolean(HeadsetConnectionBroadcastReceiver.PREF_EVENT_HEADSET_MICROPHONE, false);
            boolean bluetoothHeadset = ApplicationPreferences.preferences.getBoolean(HeadsetConnectionBroadcastReceiver.PREF_EVENT_HEADSET_BLUETOOTH, false);
            if (headsetConnected) {
                if ((event._eventPreferencesPeripherals._peripheralType == EventPreferencesPeripherals.PERIPHERAL_TYPE_WIRED_HEADSET) && headsetMicrophone && (!bluetoothHeadset))
                    peripheralPassed = true;
                else if ((event._eventPreferencesPeripherals._peripheralType == EventPreferencesPeripherals.PERIPHERAL_TYPE_BLUETOOTH_HEADSET) && headsetMicrophone && bluetoothHeadset)
                    peripheralPassed = true;
                else
                    peripheralPassed = (event._eventPreferencesPeripherals._peripheralType == EventPreferencesPeripherals.PERIPHERAL_TYPE_HEADPHONES) && (!headsetMicrophone) && (!bluetoothHeadset);
            } else
                peripheralPassed = false;
        // eventStart = eventStart && peripheralPassed;
        }
    }
    if ((event._eventPreferencesCalendar._enabled) && (Event.isEventPreferenceAllowed(EventPreferencesCalendar.PREF_EVENT_CALENDAR_ENABLED, context) == PPApplication.PREFERENCE_ALLOWED) && (Permissions.checkEventCalendar(context, event, null))) {
        // compute start datetime
        long startAlarmTime;
        long endAlarmTime;
        if (event._eventPreferencesCalendar._eventFound) {
            startAlarmTime = event._eventPreferencesCalendar.computeAlarm(true);
            String alarmTimeS = DateFormat.getDateFormat(context).format(startAlarmTime) + " " + DateFormat.getTimeFormat(context).format(startAlarmTime);
            PPApplication.logE("DataWrapper.doHandleEvents", "startAlarmTime=" + alarmTimeS);
            endAlarmTime = event._eventPreferencesCalendar.computeAlarm(false);
            alarmTimeS = DateFormat.getDateFormat(context).format(endAlarmTime) + " " + DateFormat.getTimeFormat(context).format(endAlarmTime);
            PPApplication.logE("DataWrapper.doHandleEvents", "endAlarmTime=" + alarmTimeS);
            Calendar now = Calendar.getInstance();
            long nowAlarmTime = now.getTimeInMillis();
            alarmTimeS = DateFormat.getDateFormat(context).format(nowAlarmTime) + " " + DateFormat.getTimeFormat(context).format(nowAlarmTime);
            PPApplication.logE("DataWrapper.doHandleEvents", "nowAlarmTime=" + alarmTimeS);
            calendarPassed = ((nowAlarmTime >= startAlarmTime) && (nowAlarmTime < endAlarmTime));
        } else
            calendarPassed = false;
    // eventStart = eventStart && calendarPassed;
    }
    if (event._eventPreferencesWifi._enabled && (Event.isEventPreferenceAllowed(EventPreferencesWifi.PREF_EVENT_WIFI_ENABLED, context) == PPApplication.PREFERENCE_ALLOWED) && Permissions.checkEventLocation(context, event, null)) {
        PPApplication.logE("----- DataWrapper.doHandleEvents", "-------- eventSSID=" + event._eventPreferencesWifi._SSID);
        wifiPassed = false;
        WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        boolean isWifiEnabled = wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLED;
        List<WifiSSIDData> wifiConfigurationList = WifiScanJob.getWifiConfigurationList(context);
        boolean done = false;
        if (isWifiEnabled) {
            PPApplication.logE("----- DataWrapper.doHandleEvents", "wifiStateEnabled=true");
            // PPApplication.logE("----- DataWrapper.doHandleEvents","-- eventSSID="+event._eventPreferencesWifi._SSID);
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            boolean wifiConnected = false;
            ConnectivityManager connManager = null;
            try {
                connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            } catch (Exception ignored) {
            // java.lang.NullPointerException: missing IConnectivityManager
            // Dual SIM?? Bug in Android ???
            }
            if (connManager != null) {
                if (android.os.Build.VERSION.SDK_INT >= 21) {
                    Network[] networks = connManager.getAllNetworks();
                    if ((networks != null) && (networks.length > 0)) {
                        for (Network ntk : networks) {
                            try {
                                NetworkInfo ntkInfo = connManager.getNetworkInfo(ntk);
                                if (ntkInfo != null) {
                                    if (ntkInfo.getType() == ConnectivityManager.TYPE_WIFI && ntkInfo.isConnected()) {
                                        if (wifiInfo != null) {
                                            wifiConnected = true;
                                            break;
                                        }
                                    }
                                }
                            } catch (Exception ignored) {
                            }
                        }
                    }
                } else {
                    NetworkInfo ntkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
                    wifiConnected = (ntkInfo != null) && ntkInfo.isConnected();
                }
            }
            if (wifiConnected) {
                PPApplication.logE("----- DataWrapper.doHandleEvents", "wifi connected");
                PPApplication.logE("----- DataWrapper.doHandleEvents", "wifiSSID=" + WifiScanJob.getSSID(wifiInfo, wifiConfigurationList));
                PPApplication.logE("----- DataWrapper.doHandleEvents", "wifiBSSID=" + wifiInfo.getBSSID());
                // PPApplication.logE("----- DataWrapper.doHandleEvents","SSID="+event._eventPreferencesWifi._SSID);
                String[] splits = event._eventPreferencesWifi._SSID.split("\\|");
                for (String _ssid : splits) {
                    if (_ssid.equals(EventPreferencesWifi.ALL_SSIDS_VALUE)) {
                        wifiPassed = true;
                    } else if (_ssid.equals(EventPreferencesWifi.CONFIGURED_SSIDS_VALUE)) {
                        for (WifiSSIDData data : wifiConfigurationList) {
                            wifiPassed = WifiScanJob.compareSSID(wifiInfo, data.ssid.replace("\"", ""), wifiConfigurationList);
                            if (wifiPassed)
                                break;
                        }
                    } else
                        wifiPassed = WifiScanJob.compareSSID(wifiInfo, _ssid, wifiConfigurationList);
                    if (wifiPassed)
                        break;
                }
                if (wifiPassed) {
                    // event SSID is connected
                    done = true;
                    if ((event._eventPreferencesWifi._connectionType == EventPreferencesWifi.CTYPE_NOTCONNECTED) || (event._eventPreferencesWifi._connectionType == EventPreferencesWifi.CTYPE_NOTINFRONT))
                        // for this connectionTypes, wifi must not be connected to event SSID
                        wifiPassed = false;
                // PPApplication.logE("----- DataWrapper.doHandleEvents","wifiPassed="+wifiPassed);
                } else {
                    if (event._eventPreferencesWifi._connectionType == EventPreferencesWifi.CTYPE_NOTCONNECTED) {
                        // for this connectionTypes, wifi must not be connected to event SSID
                        done = true;
                        wifiPassed = true;
                    }
                }
            } else {
                PPApplication.logE("----- DataWrapper.doHandleEvents", "wifi not connected");
                if (event._eventPreferencesWifi._connectionType == EventPreferencesWifi.CTYPE_NOTCONNECTED) {
                    // for this connectionTypes, wifi must not be connected to event SSID
                    done = true;
                    wifiPassed = true;
                }
            }
        } else {
            PPApplication.logE("----- DataWrapper.doHandleEvents", "wifiStateEnabled=false");
            if ((event._eventPreferencesWifi._connectionType == EventPreferencesWifi.CTYPE_CONNECTED) || (event._eventPreferencesWifi._connectionType == EventPreferencesWifi.CTYPE_NOTCONNECTED)) {
                // for this connectionTypes, wifi must not be connected to event SSID
                done = true;
                wifiPassed = (event._eventPreferencesWifi._connectionType == EventPreferencesWifi.CTYPE_NOTCONNECTED);
            }
        }
        PPApplication.logE("----- DataWrapper.doHandleEvents", "wifiPassed=" + wifiPassed);
        if ((event._eventPreferencesWifi._connectionType == EventPreferencesWifi.CTYPE_INFRONT) || (event._eventPreferencesWifi._connectionType == EventPreferencesWifi.CTYPE_NOTINFRONT)) {
            if (!done) {
                if (!ApplicationPreferences.applicationEventWifiEnableScannig(context)) {
                    // ignore for disabled scanning
                    ignoreWifi = true;
                } else {
                    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
                    if (!pm.isScreenOn() && ApplicationPreferences.applicationEventWifiScanOnlyWhenScreenIsOn(context)) {
                        // ignore for screen Off
                        ignoreWifi = true;
                    } else {
                        wifiPassed = false;
                        List<WifiSSIDData> scanResults = WifiScanJob.getScanResults(context);
                        if (scanResults != null) {
                            PPApplication.logE("----- DataWrapper.doHandleEvents", "scanResults != null");
                            PPApplication.logE("----- DataWrapper.doHandleEvents", "scanResults.size=" + scanResults.size());
                            for (WifiSSIDData result : scanResults) {
                                PPApplication.logE("----- DataWrapper.doHandleEvents", "scanSSID=" + result.ssid);
                                PPApplication.logE("----- DataWrapper.doHandleEvents", "scanBSSID=" + result.bssid);
                                String[] splits = event._eventPreferencesWifi._SSID.split("\\|");
                                for (String _ssid : splits) {
                                    if (_ssid.equals(EventPreferencesWifi.ALL_SSIDS_VALUE)) {
                                        PPApplication.logE("----- DataWrapper.doHandleEvents", "all ssids");
                                        wifiPassed = true;
                                        break;
                                    } else if (_ssid.equals(EventPreferencesWifi.CONFIGURED_SSIDS_VALUE)) {
                                        PPApplication.logE("----- DataWrapper.doHandleEvents", "configured ssids");
                                        for (WifiSSIDData data : wifiConfigurationList) {
                                            PPApplication.logE("----- DataWrapper.doHandleEvents", "configured SSID=" + data.ssid.replace("\"", ""));
                                            if (WifiScanJob.compareSSID(result, data.ssid.replace("\"", ""), wifiConfigurationList)) {
                                                PPApplication.logE("----- DataWrapper.doHandleEvents", "wifi found");
                                                wifiPassed = true;
                                                break;
                                            }
                                        }
                                        if (wifiPassed)
                                            break;
                                    } else {
                                        PPApplication.logE("----- DataWrapper.doHandleEvents", "event SSID=" + event._eventPreferencesWifi._SSID);
                                        if (WifiScanJob.compareSSID(result, _ssid, wifiConfigurationList)) {
                                            PPApplication.logE("----- DataWrapper.doHandleEvents", "wifi found");
                                            wifiPassed = true;
                                            break;
                                        }
                                    }
                                }
                                if (wifiPassed)
                                    break;
                            }
                            PPApplication.logE("----- DataWrapper.doHandleEvents", "wifiPassed=" + wifiPassed);
                            if (event._eventPreferencesWifi._connectionType == EventPreferencesWifi.CTYPE_NOTINFRONT)
                                // if wifi is not in front of event SSID, then passed
                                wifiPassed = !wifiPassed;
                            PPApplication.logE("----- DataWrapper.doHandleEvents", "wifiPassed=" + wifiPassed);
                        } else
                            PPApplication.logE("----- DataWrapper.doHandleEvents", "scanResults == null");
                    }
                }
            }
        }
        PPApplication.logE("----- DataWrapper.doHandleEvents", "------- wifiPassed=" + wifiPassed);
    // eventStart = eventStart && wifiPassed;
    }
    if (event._eventPreferencesScreen._enabled && (Event.isEventPreferenceAllowed(EventPreferencesScreen.PREF_EVENT_SCREEN_ENABLED, context) == PPApplication.PREFERENCE_ALLOWED)) {
        boolean isScreenOn;
        // if (android.os.Build.VERSION.SDK_INT >= 20)
        // {
        // Display display = ((WindowManager)context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
        // isScreenOn = display.getState() != Display.STATE_OFF;
        // }
        // else
        // {
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        isScreenOn = pm.isScreenOn();
        // }
        boolean keyguardShowing = false;
        if (event._eventPreferencesScreen._whenUnlocked) {
            KeyguardManager kgMgr = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
            keyguardShowing = kgMgr.isKeyguardLocked();
        }
        if (event._eventPreferencesScreen._eventType == EventPreferencesScreen.ETYPE_SCREENON) {
            if (event._eventPreferencesScreen._whenUnlocked)
                // passed if screen is on and unlocked => start only when unlocked
                screenPassed = isScreenOn && (!keyguardShowing);
            else
                screenPassed = isScreenOn;
        } else {
            if (event._eventPreferencesScreen._whenUnlocked)
                // passed if screen is off or locked => locked is the same as screen off
                screenPassed = (!isScreenOn) || keyguardShowing;
            else
                screenPassed = !isScreenOn;
        }
    // eventStart = eventStart && screenPassed;
    }
    if (event._eventPreferencesBluetooth._enabled && (Event.isEventPreferenceAllowed(EventPreferencesBluetooth.PREF_EVENT_BLUETOOTH_ENABLED, context) == PPApplication.PREFERENCE_ALLOWED) && Permissions.checkEventLocation(context, event, null)) {
        bluetoothPassed = false;
        List<BluetoothDeviceData> boundedDevicesList = BluetoothScanJob.getBoundedDevicesList(context);
        boolean done = false;
        BluetoothAdapter bluetooth = BluetoothScanJob.getBluetoothAdapter(context);
        if (bluetooth != null) {
            boolean isBluetoothEnabled = bluetooth.isEnabled();
            if (isBluetoothEnabled) {
                PPApplication.logE("[BTScan] DataWrapper.doHandleEvents", "bluetoothEnabled=true");
                PPApplication.logE("[BTScan] DataWrapper.doHandleEvents", "-- eventAdapterName=" + event._eventPreferencesBluetooth._adapterName);
                // List<BluetoothDeviceData> connectedDevices = BluetoothConnectedDevices.getConnectedDevices(context);
                BluetoothConnectionBroadcastReceiver.getConnectedDevices(context);
                if (BluetoothConnectionBroadcastReceiver.isBluetoothConnected(null, "")) {
                    // if (BluetoothConnectedDevices.isBluetoothConnected(connectedDevices,null, "")) {
                    PPApplication.logE("[BTScan] DataWrapper.doHandleEvents", "any device connected");
                    boolean connected = false;
                    String[] splits = event._eventPreferencesBluetooth._adapterName.split("\\|");
                    for (String _bluetoothName : splits) {
                        if (_bluetoothName.equals(EventPreferencesBluetooth.ALL_BLUETOOTH_NAMES_VALUE)) {
                            PPApplication.logE("[BTScan] DataWrapper.doHandleEvents", "any device connected");
                            connected = true;
                            break;
                        } else if (_bluetoothName.equals(EventPreferencesBluetooth.CONFIGURED_BLUETOOTH_NAMES_VALUE)) {
                            for (BluetoothDeviceData data : boundedDevicesList) {
                                PPApplication.logE("[BTScan] DataWrapper.doHandleEvents", "boundedDevice.name=" + data.getName());
                                PPApplication.logE("[BTScan] DataWrapper.doHandleEvents", "boundedDevice.address=" + data.getAddress());
                                connected = BluetoothConnectionBroadcastReceiver.isBluetoothConnected(data, "");
                                // connected = BluetoothConnectedDevices.isBluetoothConnected(connectedDevices, data, "");
                                if (connected)
                                    break;
                            }
                            PPApplication.logE("[BTScan] DataWrapper.doHandleEvents", "paired device connected=" + connected);
                        } else {
                            connected = BluetoothConnectionBroadcastReceiver.isBluetoothConnected(null, _bluetoothName);
                            // connected = BluetoothConnectedDevices.isBluetoothConnected(connectedDevices,null, _bluetoothName);
                            PPApplication.logE("[BTScan] DataWrapper.doHandleEvents", "event sensor device connected=" + connected);
                        }
                        if (connected)
                            break;
                    }
                    if (connected) {
                        // event BT adapter is connected
                        done = true;
                        bluetoothPassed = !((event._eventPreferencesBluetooth._connectionType == EventPreferencesBluetooth.CTYPE_NOTCONNECTED) || (event._eventPreferencesBluetooth._connectionType == EventPreferencesBluetooth.CTYPE_NOTINFRONT));
                    } else {
                        if (event._eventPreferencesBluetooth._connectionType == EventPreferencesBluetooth.CTYPE_NOTCONNECTED) {
                            // for this connectionTypes, BT must not be connected to event BT adapter
                            done = true;
                            bluetoothPassed = true;
                        }
                    }
                } else {
                    PPApplication.logE("[BTScan] DataWrapper.doHandleEvents", "not any device connected");
                    if (event._eventPreferencesBluetooth._connectionType == EventPreferencesBluetooth.CTYPE_NOTCONNECTED) {
                        // for this connectionTypes, BT must not be connected to event BT adapter
                        done = true;
                        bluetoothPassed = true;
                    }
                }
            } else {
                PPApplication.logE("[BTScan] DataWrapper.doHandleEvents", "bluetoothEnabled=true");
                if ((event._eventPreferencesBluetooth._connectionType == EventPreferencesBluetooth.CTYPE_CONNECTED) || (event._eventPreferencesBluetooth._connectionType == EventPreferencesBluetooth.CTYPE_NOTCONNECTED)) {
                    // for this connectionTypes, BT must not be connected to event BT adapter
                    done = true;
                    bluetoothPassed = (event._eventPreferencesBluetooth._connectionType == EventPreferencesBluetooth.CTYPE_NOTCONNECTED);
                }
            }
        }
        PPApplication.logE("[BTScan] DataWrapper.doHandleEvents", "bluetoothPassed=" + bluetoothPassed);
        if ((event._eventPreferencesBluetooth._connectionType == EventPreferencesBluetooth.CTYPE_INFRONT) || (event._eventPreferencesBluetooth._connectionType == EventPreferencesBluetooth.CTYPE_NOTINFRONT)) {
            if (!done) {
                if (!ApplicationPreferences.applicationEventBluetoothEnableScannig(context)) {
                    // ignore for disabled scanning
                    ignoreBluetooth = true;
                } else {
                    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
                    if (!pm.isScreenOn() && ApplicationPreferences.applicationEventBluetoothScanOnlyWhenScreenIsOn(context)) {
                        // ignore for screen Off
                        ignoreBluetooth = true;
                    } else {
                        bluetoothPassed = false;
                        List<BluetoothDeviceData> scanResults = BluetoothScanJob.getScanResults(context);
                        if (scanResults != null) {
                            for (BluetoothDeviceData device : scanResults) {
                                String[] splits = event._eventPreferencesBluetooth._adapterName.split("\\|");
                                for (String _bluetoothName : splits) {
                                    if (_bluetoothName.equals(EventPreferencesBluetooth.ALL_BLUETOOTH_NAMES_VALUE)) {
                                        bluetoothPassed = true;
                                        break;
                                    } else if (_bluetoothName.equals(EventPreferencesBluetooth.CONFIGURED_BLUETOOTH_NAMES_VALUE)) {
                                        for (BluetoothDeviceData data : boundedDevicesList) {
                                            String _device = device.getName().toUpperCase();
                                            String _adapterName = data.getName().toUpperCase();
                                            if (Wildcard.match(_device, _adapterName, '_', '%', true)) {
                                                PPApplication.logE("[BTScan] DataWrapper.doHandleEvents", "bluetooth found");
                                                // PPApplication.logE("@@@ DataWrapper.doHandleEvents","bluetoothAdapterName="+device.getName());
                                                // PPApplication.logE("@@@ DataWrapper.doHandleEvents","bluetoothAddress="+device.getAddress());
                                                bluetoothPassed = true;
                                                break;
                                            }
                                        }
                                        if (bluetoothPassed)
                                            break;
                                    } else {
                                        String _device = device.getName().toUpperCase();
                                        if ((device.getName() == null) || device.getName().isEmpty()) {
                                            // scanned device has not name (hidden BT?)
                                            if ((device.getAddress() != null) && (!device.getAddress().isEmpty())) {
                                                // device has address
                                                for (BluetoothDeviceData data : boundedDevicesList) {
                                                    if ((data.getAddress() != null) && data.getAddress().equals(device.getAddress())) {
                                                        PPApplication.logE("[BTScan] DataWrapper.doHandleEvents", "bluetooth found");
                                                        // PPApplication.logE("@@@ DataWrapper.doHandleEvents","bluetoothAdapterName="+device.getName());
                                                        // PPApplication.logE("@@@ DataWrapper.doHandleEvents","bluetoothAddress="+device.getAddress());
                                                        bluetoothPassed = true;
                                                        break;
                                                    }
                                                }
                                            }
                                        } else {
                                            String _adapterName = _bluetoothName.toUpperCase();
                                            if (Wildcard.match(_device, _adapterName, '_', '%', true)) {
                                                PPApplication.logE("[BTScan] DataWrapper.doHandleEvents", "bluetooth found");
                                                // PPApplication.logE("@@@ DataWrapper.doHandleEvents","bluetoothAdapterName="+device.getName());
                                                // PPApplication.logE("@@@ DataWrapper.doHandleEvents","bluetoothAddress="+device.getAddress());
                                                bluetoothPassed = true;
                                                break;
                                            }
                                        }
                                    }
                                }
                                if (bluetoothPassed)
                                    break;
                            }
                            if (!bluetoothPassed)
                                PPApplication.logE("[BTScan] DataWrapper.doHandleEvents", "bluetooth not found");
                            if (event._eventPreferencesBluetooth._connectionType == EventPreferencesBluetooth.CTYPE_NOTINFRONT)
                                // if bluetooth is not in front of event BT adapter name, then passed
                                bluetoothPassed = !bluetoothPassed;
                        } else
                            PPApplication.logE("[BTScan] DataWrapper.doHandleEvents", "scanResults == null");
                    }
                }
            }
        }
        PPApplication.logE("[BTScan] DataWrapper.doHandleEvents", "bluetoothPassed=" + bluetoothPassed);
    // eventStart = eventStart && bluetoothPassed;
    }
    if ((event._eventPreferencesSMS._enabled) && (Event.isEventPreferenceAllowed(EventPreferencesSMS.PREF_EVENT_SMS_ENABLED, context) == PPApplication.PREFERENCE_ALLOWED) && Permissions.checkEventSMSContacts(context, event, null) && Permissions.checkEventSMSBroadcast(context, event, null)) {
        if (event._eventPreferencesSMS._startTime > 0) {
            // TimeZone.getDefault().getRawOffset();
            int gmtOffset = 0;
            long startTime = event._eventPreferencesSMS._startTime - gmtOffset;
            if (PPApplication.logEnabled()) {
                SimpleDateFormat sdf = new SimpleDateFormat("EE d.MM.yyyy HH:mm:ss:S");
                String alarmTimeS = sdf.format(startTime);
                PPApplication.logE("DataWrapper.doHandleEvents", "startTime=" + alarmTimeS);
            }
            // compute end datetime
            long endAlarmTime = event._eventPreferencesSMS.computeAlarm();
            if (PPApplication.logEnabled()) {
                SimpleDateFormat sdf = new SimpleDateFormat("EE d.MM.yyyy HH:mm:ss:S");
                String alarmTimeS = sdf.format(endAlarmTime);
                PPApplication.logE("DataWrapper.doHandleEvents", "endAlarmTime=" + alarmTimeS);
            }
            Calendar now = Calendar.getInstance();
            long nowAlarmTime = now.getTimeInMillis();
            if (PPApplication.logEnabled()) {
                SimpleDateFormat sdf = new SimpleDateFormat("EE d.MM.yyyy HH:mm:ss:S");
                String alarmTimeS = sdf.format(nowAlarmTime);
                PPApplication.logE("DataWrapper.doHandleEvents", "nowAlarmTime=" + alarmTimeS);
            }
            if (sensorType.equals(EventsHandler.SENSOR_TYPE_SMS))
                smsPassed = true;
            else if (!event._eventPreferencesSMS._permanentRun) {
                if (sensorType.equals(EventsHandler.SENSOR_TYPE_SMS_EVENT_END))
                    smsPassed = false;
                else
                    smsPassed = ((nowAlarmTime >= startTime) && (nowAlarmTime < endAlarmTime));
            } else {
                smsPassed = nowAlarmTime >= startTime;
            }
        } else
            smsPassed = false;
        if (!smsPassed) {
            event._eventPreferencesSMS._startTime = 0;
            DatabaseHandler.getInstance(context).updateSMSStartTime(event);
        }
    }
    if (event._eventPreferencesNotification._enabled && (Event.isEventPreferenceAllowed(EventPreferencesNotification.PREF_EVENT_NOTIFICATION_ENABLED, context) == PPApplication.PREFERENCE_ALLOWED)) {
        // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
        /*if (!event._eventPreferencesNotification._endWhenRemoved) {

                    if (event._eventPreferencesNotification._startTime > 0) {
                        // compute start time
                        int gmtOffset = 0; //TimeZone.getDefault().getRawOffset();
                        long startTime = event._eventPreferencesNotification._startTime - gmtOffset;

                        SimpleDateFormat sdf = new SimpleDateFormat("EE d.MM.yyyy HH:mm:ss:S");
                        String alarmTimeS = sdf.format(startTime);
                        PPApplication.logE("[NOTIF] DataWrapper.doHandleEvents", "startTime=" + alarmTimeS);

                        // compute end datetime
                        long endAlarmTime = event._eventPreferencesNotification.computeAlarm();
                        alarmTimeS = sdf.format(endAlarmTime);
                        PPApplication.logE("[NOTIF] DataWrapper.doHandleEvents", "endAlarmTime=" + alarmTimeS);

                        Calendar now = Calendar.getInstance();
                        long nowAlarmTime = now.getTimeInMillis();
                        alarmTimeS = sdf.format(nowAlarmTime);
                        PPApplication.logE("[NOTIF] DataWrapper.doHandleEvents", "nowAlarmTime=" + alarmTimeS);

                        if (sensorType.equals(EventsHandler.SENSOR_TYPE_NOTIFICATION))
                            notificationPassed = true;
                        else if (!event._eventPreferencesNotification._permanentRun) {
                            if (sensorType.equals(EventsHandler.SENSOR_TYPE_NOTIFICATION_EVENT_END)) {
                                notificationPassed = false;
                            }
                            else
                                notificationPassed = ((nowAlarmTime >= startTime) && (nowAlarmTime < endAlarmTime));
                        }
                        else
                            notificationPassed = nowAlarmTime >= startTime;
                    } else
                        notificationPassed = false;
                } else {*/
        notificationPassed = event._eventPreferencesNotification.isNotificationVisible(this);
        // }
        PPApplication.logE("[NOTIF] DataWrapper.doHandleEvents", "notificationPassed=" + notificationPassed);
    /*if (!notificationPassed) {
                    event._eventPreferencesNotification._startTime = 0;
                    DatabaseHandler.getInstance(context).updateNotificationStartTime(event);
                }*/
    /*}
            else {
                ignoreNotification = true;
            }*/
    }
    if (event._eventPreferencesApplication._enabled && (Event.isEventPreferenceAllowed(EventPreferencesApplication.PREF_EVENT_APPLICATION_ENABLED, context) == PPApplication.PREFERENCE_ALLOWED)) {
        applicationPassed = false;
        if (AccessibilityServiceBroadcastReceiver.isEnabled(context.getApplicationContext())) {
            String foregroundApplication = AccessibilityServiceBroadcastReceiver.getApplicationInForeground(context);
            if (!foregroundApplication.isEmpty()) {
                String[] splits = event._eventPreferencesApplication._applications.split("\\|");
                for (String split : splits) {
                    String packageName = ApplicationsCache.getPackageName(split);
                    if (foregroundApplication.equals(packageName)) {
                        applicationPassed = true;
                        break;
                    }
                }
            } else
                ignoreApplication = true;
        } else
            ignoreApplication = true;
    }
    if (event._eventPreferencesLocation._enabled && (Event.isEventPreferenceAllowed(EventPreferencesLocation.PREF_EVENT_LOCATION_ENABLED, context) == PPApplication.PREFERENCE_ALLOWED) && Permissions.checkEventLocation(context, event, null)) {
        if (!ApplicationPreferences.applicationEventLocationEnableScannig(context)) {
            // ignore for disabled location scanner
            PPApplication.logE("[GeoSensor] DataWrapper.doHandleEvents", "ignore for disabled scanner");
            ignoreLocation = true;
        } else {
            PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            if (!pm.isScreenOn() && ApplicationPreferences.applicationEventLocationScanOnlyWhenScreenIsOn(context)) {
                // ignore for screen Off
                PPApplication.logE("[GeoSensor] DataWrapper.doHandleEvents", "ignore for screen off");
                ignoreLocation = true;
            } else {
                synchronized (PPApplication.geofenceScannerMutex) {
                    if ((PhoneProfilesService.instance != null) && PhoneProfilesService.isGeofenceScannerStarted() && PhoneProfilesService.getGeofencesScanner().mTransitionsUpdated) {
                        locationPassed = false;
                        String[] splits = event._eventPreferencesLocation._geofences.split("\\|");
                        PPApplication.logE("[GeoSensor] DataWrapper.doHandleEvents", "--------");
                        PPApplication.logE("[GeoSensor] DataWrapper.doHandleEvents", "_eventPreferencesLocation._geofences=" + event._eventPreferencesLocation._geofences);
                        for (String _geofence : splits) {
                            if (!_geofence.isEmpty()) {
                                PPApplication.logE("[GeoSensor] DataWrapper.doHandleEvents", "geofence=" + DatabaseHandler.getInstance(context).getGeofenceName(Long.valueOf(_geofence)));
                                int geofenceTransition = DatabaseHandler.getInstance(context).getGeofenceTransition(Long.valueOf(_geofence));
                                if (geofenceTransition == com.google.android.gms.location.Geofence.GEOFENCE_TRANSITION_ENTER)
                                    PPApplication.logE("[GeoSensor] DataWrapper.doHandleEvents", "transitionType=GEOFENCE_TRANSITION_ENTER");
                                else
                                    PPApplication.logE("[GeoSensor] DataWrapper.doHandleEvents", "transitionType=GEOFENCE_TRANSITION_EXIT");
                                if (geofenceTransition == com.google.android.gms.location.Geofence.GEOFENCE_TRANSITION_ENTER) {
                                    locationPassed = true;
                                    break;
                                }
                            }
                        }
                        PPApplication.logE("[GeoSensor] DataWrapper.doHandleEvents", "locationPassed=" + locationPassed);
                        if (event._eventPreferencesLocation._whenOutside)
                            locationPassed = !locationPassed;
                    } else {
                        ignoreLocation = true;
                    }
                }
            }
        }
    }
    if (event._eventPreferencesOrientation._enabled && (Event.isEventPreferenceAllowed(EventPreferencesOrientation.PREF_EVENT_ORIENTATION_ENABLED, context) == PPApplication.PREFERENCE_ALLOWED)) {
        ApplicationPreferences.getSharedPreferences(context);
        int callEventType = ApplicationPreferences.preferences.getInt(PhoneCallBroadcastReceiver.PREF_EVENT_CALL_EVENT_TYPE, PhoneCallBroadcastReceiver.CALL_EVENT_UNDEFINED);
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        if (/*Permissions.checkEventPhoneBroadcast(context, event) &&*/
        (callEventType != PhoneCallBroadcastReceiver.CALL_EVENT_UNDEFINED) && (callEventType != PhoneCallBroadcastReceiver.CALL_EVENT_INCOMING_CALL_ENDED) && (callEventType != PhoneCallBroadcastReceiver.CALL_EVENT_OUTGOING_CALL_ENDED)) {
            // ignore changes during call
            ignoreOrientation = true;
        } else if (!ApplicationPreferences.applicationEventOrientationEnableScannig(context)) {
            ignoreOrientation = true;
        } else if (!pm.isScreenOn() && ApplicationPreferences.applicationEventOrientationScanOnlyWhenScreenIsOn(context)) {
            // ignore for screen Off
            ignoreOrientation = true;
        } else {
            synchronized (PPApplication.orientationScannerMutex) {
                if ((PhoneProfilesService.instance != null) && PhoneProfilesService.isOrientationScannerStarted()) {
                    boolean lApplicationPassed = false;
                    if (AccessibilityServiceBroadcastReceiver.isEnabled(context.getApplicationContext())) {
                        String foregroundApplication = AccessibilityServiceBroadcastReceiver.getApplicationInForeground(context);
                        if (!foregroundApplication.isEmpty()) {
                            String[] splits = event._eventPreferencesOrientation._ignoredApplications.split("\\|");
                            for (String split : splits) {
                                String packageName = ApplicationsCache.getPackageName(split);
                                if (foregroundApplication.equals(packageName)) {
                                    lApplicationPassed = true;
                                    break;
                                }
                            }
                        }
                    }
                    if (!lApplicationPassed) {
                        boolean lDisplayPassed = true;
                        boolean lSidePassed = true;
                        boolean enabledAccelerometer = PhoneProfilesService.getAccelerometerSensor(context) != null;
                        boolean enabledMagneticField = PhoneProfilesService.getMagneticFieldSensor(context) != null;
                        boolean enabledAll = (enabledAccelerometer) && (enabledMagneticField);
                        if (enabledAccelerometer) {
                            if (!event._eventPreferencesOrientation._display.isEmpty()) {
                                String[] splits = event._eventPreferencesOrientation._display.split("\\|");
                                if (splits.length > 0) {
                                    lDisplayPassed = false;
                                    for (String split : splits) {
                                        try {
                                            int side = Integer.valueOf(split);
                                            if (side == PhoneProfilesService.mDisplayUp) {
                                                lDisplayPassed = true;
                                                break;
                                            }
                                        } catch (Exception ignored) {
                                        }
                                    }
                                }
                            }
                        }
                        if (enabledAll) {
                            if (!event._eventPreferencesOrientation._sides.isEmpty()) {
                                String[] splits = event._eventPreferencesOrientation._sides.split("\\|");
                                if (splits.length > 0) {
                                    lSidePassed = false;
                                    for (String split : splits) {
                                        try {
                                            int side = Integer.valueOf(split);
                                            if (side == PhoneProfilesService.DEVICE_ORIENTATION_HORIZONTAL) {
                                                if (PhoneProfilesService.mSideUp == PhoneProfilesService.mDisplayUp) {
                                                    lSidePassed = true;
                                                    break;
                                                }
                                            } else {
                                                if (side == PhoneProfilesService.mSideUp) {
                                                    lSidePassed = true;
                                                    break;
                                                }
                                            }
                                        } catch (Exception ignored) {
                                        }
                                    }
                                }
                            }
                        }
                        boolean lDistancePassed = true;
                        boolean enabled = PhoneProfilesService.getProximitySensor(context) != null;
                        if (enabled) {
                            if (event._eventPreferencesOrientation._distance != 0) {
                                lDistancePassed = event._eventPreferencesOrientation._distance == PhoneProfilesService.mDeviceDistance;
                            }
                        }
                        // Log.d("**** DataWrapper.doHandleEvents","lDisplayPassed="+lDisplayPassed);
                        // Log.d("**** DataWrapper.doHandleEvents","lSidePassed="+lSidePassed);
                        // Log.d("**** DataWrapper.doHandleEvents","lDistancePassed="+lDistancePassed);
                        orientationPassed = lDisplayPassed && lSidePassed && lDistancePassed;
                    } else {
                        ignoreOrientation = true;
                    }
                } else {
                    ignoreOrientation = true;
                }
            }
        }
    }
    if (event._eventPreferencesMobileCells._enabled && (Event.isEventPreferenceAllowed(EventPreferencesMobileCells.PREF_EVENT_MOBILE_CELLS_ENABLED, context) == PPApplication.PREFERENCE_ALLOWED) && Permissions.checkEventLocation(context, event, null)) {
        if (!ApplicationPreferences.applicationEventMobileCellEnableScannig(context)) {
            ignoreMobileCell = true;
        } else {
            PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            if (!pm.isScreenOn() && ApplicationPreferences.applicationEventMobileCellScanOnlyWhenScreenIsOn(context)) {
                // ignore for screen Off
                ignoreMobileCell = true;
            } else {
                synchronized (PPApplication.phoneStateScannerMutex) {
                    if ((PhoneProfilesService.instance != null) && PhoneProfilesService.isPhoneStateScannerStarted()) {
                        String[] splits = event._eventPreferencesMobileCells._cells.split("\\|");
                        if (PhoneProfilesService.phoneStateScanner.registeredCell != Integer.MAX_VALUE) {
                            String registeredCell = Integer.toString(PhoneProfilesService.phoneStateScanner.registeredCell);
                            boolean found = false;
                            for (String cell : splits) {
                                if (cell.equals(registeredCell)) {
                                    found = true;
                                    break;
                                }
                            }
                            mobileCellPassed = found;
                        } else
                            ignoreMobileCell = true;
                        if (event._eventPreferencesMobileCells._whenOutside)
                            mobileCellPassed = !mobileCellPassed;
                    } else
                        ignoreMobileCell = true;
                }
            }
        }
    }
    if (event._eventPreferencesNFC._enabled && (Event.isEventPreferenceAllowed(EventPreferencesNFC.PREF_EVENT_NFC_ENABLED, context) == PPApplication.PREFERENCE_ALLOWED)) {
        if (event._eventPreferencesNFC._startTime > 0) {
            // TimeZone.getDefault().getRawOffset();
            int gmtOffset = 0;
            long startTime = event._eventPreferencesNFC._startTime - gmtOffset;
            if (PPApplication.logEnabled()) {
                SimpleDateFormat sdf = new SimpleDateFormat("EE d.MM.yyyy HH:mm:ss:S");
                String alarmTimeS = sdf.format(startTime);
                PPApplication.logE("DataWrapper.doHandleEvents", "startTime=" + alarmTimeS);
            }
            // compute end datetime
            long endAlarmTime = event._eventPreferencesNFC.computeAlarm();
            if (PPApplication.logEnabled()) {
                SimpleDateFormat sdf = new SimpleDateFormat("EE d.MM.yyyy HH:mm:ss:S");
                String alarmTimeS = sdf.format(endAlarmTime);
                PPApplication.logE("DataWrapper.doHandleEvents", "endAlarmTime=" + alarmTimeS);
            }
            Calendar now = Calendar.getInstance();
            long nowAlarmTime = now.getTimeInMillis();
            if (PPApplication.logEnabled()) {
                SimpleDateFormat sdf = new SimpleDateFormat("EE d.MM.yyyy HH:mm:ss:S");
                String alarmTimeS = sdf.format(nowAlarmTime);
                PPApplication.logE("DataWrapper.doHandleEvents", "nowAlarmTime=" + alarmTimeS);
            }
            if (sensorType.equals(EventsHandler.SENSOR_TYPE_NFC_TAG))
                nfcPassed = true;
            else if (!event._eventPreferencesNFC._permanentRun) {
                if (sensorType.equals(EventsHandler.SENSOR_TYPE_NFC_EVENT_END))
                    nfcPassed = false;
                else
                    nfcPassed = ((nowAlarmTime >= startTime) && (nowAlarmTime < endAlarmTime));
            } else
                nfcPassed = nowAlarmTime >= startTime;
        } else
            nfcPassed = false;
        if (!nfcPassed) {
            event._eventPreferencesNFC._startTime = 0;
            DatabaseHandler.getInstance(context).updateNFCStartTime(event);
        }
    }
    if (event._eventPreferencesRadioSwitch._enabled && (Event.isEventPreferenceAllowed(EventPreferencesRadioSwitch.PREF_EVENT_RADIO_SWITCH_ENABLED, context) == PPApplication.PREFERENCE_ALLOWED)) {
        radioSwitchPassed = true;
        boolean tested = false;
        if ((event._eventPreferencesRadioSwitch._wifi == 1 || event._eventPreferencesRadioSwitch._wifi == 2) && PPApplication.hasSystemFeature(context, PackageManager.FEATURE_WIFI)) {
            if (!((WifiScanJob.getScanRequest(context)) || (WifiScanJob.getWaitForResults(context)) || (WifiScanJob.getWifiEnabledForScan(context)))) {
                // ignore for wifi scanning
                WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
                int wifiState = wifiManager.getWifiState();
                boolean enabled = ((wifiState == WifiManager.WIFI_STATE_ENABLED) || (wifiState == WifiManager.WIFI_STATE_ENABLING));
                PPApplication.logE("-###- DataWrapper.doHandleEvents", "wifiState=" + enabled);
                tested = true;
                if (event._eventPreferencesRadioSwitch._wifi == 1)
                    radioSwitchPassed = radioSwitchPassed && enabled;
                else
                    radioSwitchPassed = radioSwitchPassed && !enabled;
            } else
                ignoreRadioSwitch = true;
        }
        if ((event._eventPreferencesRadioSwitch._bluetooth == 1 || event._eventPreferencesRadioSwitch._bluetooth == 2) && PPApplication.hasSystemFeature(context, PackageManager.FEATURE_BLUETOOTH)) {
            if (!((BluetoothScanJob.getScanRequest(context)) || (BluetoothScanJob.getLEScanRequest(context)) || (BluetoothScanJob.getWaitForResults(context)) || (BluetoothScanJob.getWaitForLEResults(context)) || (BluetoothScanJob.getBluetoothEnabledForScan(context)))) {
                // ignore for bluetooth scanning
                BluetoothAdapter bluetoothAdapter = BluetoothScanJob.getBluetoothAdapter(context);
                if (bluetoothAdapter != null) {
                    boolean enabled = bluetoothAdapter.isEnabled();
                    PPApplication.logE("-###- DataWrapper.doHandleEvents", "bluetoothState=" + enabled);
                    tested = true;
                    if (event._eventPreferencesRadioSwitch._bluetooth == 1)
                        radioSwitchPassed = radioSwitchPassed && enabled;
                    else
                        radioSwitchPassed = radioSwitchPassed && !enabled;
                }
            } else
                ignoreRadioSwitch = true;
        }
        if ((event._eventPreferencesRadioSwitch._mobileData == 1 || event._eventPreferencesRadioSwitch._mobileData == 2) && PPApplication.hasSystemFeature(context, PackageManager.FEATURE_TELEPHONY)) {
            boolean enabled = ActivateProfileHelper.isMobileData(context);
            PPApplication.logE("-###- DataWrapper.doHandleEvents", "mobileDataState=" + enabled);
            tested = true;
            if (event._eventPreferencesRadioSwitch._mobileData == 1)
                radioSwitchPassed = radioSwitchPassed && enabled;
            else
                radioSwitchPassed = radioSwitchPassed && !enabled;
        }
        if ((event._eventPreferencesRadioSwitch._gps == 1 || event._eventPreferencesRadioSwitch._gps == 2) && PPApplication.hasSystemFeature(context, PackageManager.FEATURE_LOCATION_GPS)) {
            boolean enabled;
            /*if (android.os.Build.VERSION.SDK_INT < 19)
                    enabled = Settings.Secure.isLocationProviderEnabled(context.getContentResolver(), LocationManager.GPS_PROVIDER);
                else {*/
            LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
            enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
            // }
            PPApplication.logE("-###- DataWrapper.doHandleEvents", "gpsState=" + enabled);
            tested = true;
            if (event._eventPreferencesRadioSwitch._gps == 1)
                radioSwitchPassed = radioSwitchPassed && enabled;
            else
                radioSwitchPassed = radioSwitchPassed && !enabled;
        }
        if ((event._eventPreferencesRadioSwitch._nfc == 1 || event._eventPreferencesRadioSwitch._nfc == 2) && PPApplication.hasSystemFeature(context, PackageManager.FEATURE_NFC)) {
            NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(context);
            if (nfcAdapter != null) {
                boolean enabled = nfcAdapter.isEnabled();
                PPApplication.logE("-###- DataWrapper.doHandleEvents", "nfcState=" + enabled);
                tested = true;
                if (event._eventPreferencesRadioSwitch._nfc == 1)
                    radioSwitchPassed = radioSwitchPassed && enabled;
                else
                    radioSwitchPassed = radioSwitchPassed && !enabled;
            }
        }
        if (event._eventPreferencesRadioSwitch._airplaneMode == 1 || event._eventPreferencesRadioSwitch._airplaneMode == 2) {
            boolean enabled = ActivateProfileHelper.isAirplaneMode(context);
            PPApplication.logE("-###- DataWrapper.doHandleEvents", "airplaneModeState=" + enabled);
            tested = true;
            if (event._eventPreferencesRadioSwitch._airplaneMode == 1)
                radioSwitchPassed = radioSwitchPassed && enabled;
            else
                radioSwitchPassed = radioSwitchPassed && !enabled;
        }
        radioSwitchPassed = radioSwitchPassed && tested;
    }
    PPApplication.logE("DataWrapper.doHandleEvents", "timePassed=" + timePassed);
    PPApplication.logE("DataWrapper.doHandleEvents", "batteryPassed=" + batteryPassed);
    PPApplication.logE("DataWrapper.doHandleEvents", "callPassed=" + callPassed);
    PPApplication.logE("DataWrapper.doHandleEvents", "peripheralPassed=" + peripheralPassed);
    PPApplication.logE("DataWrapper.doHandleEvents", "calendarPassed=" + calendarPassed);
    PPApplication.logE("DataWrapper.doHandleEvents", "wifiPassed=" + wifiPassed);
    PPApplication.logE("DataWrapper.doHandleEvents", "screenPassed=" + screenPassed);
    PPApplication.logE("DataWrapper.doHandleEvents", "bluetoothPassed=" + bluetoothPassed);
    PPApplication.logE("DataWrapper.doHandleEvents", "smsPassed=" + smsPassed);
    PPApplication.logE("DataWrapper.doHandleEvents", "notificationPassed=" + notificationPassed);
    PPApplication.logE("DataWrapper.doHandleEvents", "applicationPassed=" + applicationPassed);
    PPApplication.logE("DataWrapper.doHandleEvents", "locationPassed=" + locationPassed);
    PPApplication.logE("DataWrapper.doHandleEvents", "orientationPassed=" + orientationPassed);
    PPApplication.logE("DataWrapper.doHandleEvents", "mobileCellPassed=" + mobileCellPassed);
    PPApplication.logE("DataWrapper.doHandleEvents", "nfcPassed=" + nfcPassed);
    PPApplication.logE("DataWrapper.doHandleEvents", "radioSwitchPassed=" + radioSwitchPassed);
    PPApplication.logE("DataWrapper.doHandleEvents", "ignoreTime=" + ignoreTime);
    PPApplication.logE("DataWrapper.doHandleEvents", "ignoreBattery=" + ignoreBattery);
    PPApplication.logE("DataWrapper.doHandleEvents", "ignoreCall=" + ignoreCall);
    PPApplication.logE("DataWrapper.doHandleEvents", "ignorePeripheral=" + ignorePeripheral);
    PPApplication.logE("DataWrapper.doHandleEvents", "ignoreCalendar=" + ignoreCalendar);
    PPApplication.logE("DataWrapper.doHandleEvents", "ignoreWifi=" + ignoreWifi);
    PPApplication.logE("DataWrapper.doHandleEvents", "ignoreScreen=" + ignoreScreen);
    PPApplication.logE("DataWrapper.doHandleEvents", "ignoreBluetooth=" + ignoreBluetooth);
    PPApplication.logE("DataWrapper.doHandleEvents", "ignoreSms=" + ignoreSms);
    PPApplication.logE("DataWrapper.doHandleEvents", "ignoreNotification=" + ignoreNotification);
    PPApplication.logE("DataWrapper.doHandleEvents", "ignoreApplication=" + ignoreApplication);
    PPApplication.logE("DataWrapper.doHandleEvents", "ignoreLocation=" + ignoreLocation);
    PPApplication.logE("DataWrapper.doHandleEvents", "ignoreOrientation=" + ignoreOrientation);
    PPApplication.logE("DataWrapper.doHandleEvents", "ignoreMobileCell=" + ignoreMobileCell);
    PPApplication.logE("DataWrapper.doHandleEvents", "ignoreNfc=" + ignoreNfc);
    PPApplication.logE("DataWrapper.doHandleEvents", "ignoreRadioSwitch=" + ignoreRadioSwitch);
    // PPApplication.logE("DataWrapper.doHandleEvents","eventStart="+eventStart);
    PPApplication.logE("DataWrapper.doHandleEvents", "restartEvent=" + restartEvent);
    PPApplication.logE("DataWrapper.doHandleEvents", "statePause=" + statePause);
    List<EventTimeline> eventTimelineList = getEventTimelineList();
    if (!(ignoreTime || ignoreBattery || ignoreCall || ignorePeripheral || ignoreCalendar || ignoreWifi || ignoreScreen || ignoreBluetooth || ignoreSms || ignoreNotification || ignoreApplication || ignoreLocation || ignoreOrientation || ignoreMobileCell || ignoreNfc || ignoreRadioSwitch)) {
        if (timePassed && batteryPassed && callPassed && peripheralPassed && calendarPassed && wifiPassed && screenPassed && bluetoothPassed && smsPassed && notificationPassed && applicationPassed && locationPassed && orientationPassed && mobileCellPassed && nfcPassed && radioSwitchPassed) {
            // all sensors are passed
            // if (eventStart)
            newEventStatus = Event.ESTATUS_RUNNING;
        // else
        // newEventStatus = Event.ESTATUS_PAUSE;
        } else
            newEventStatus = Event.ESTATUS_PAUSE;
        PPApplication.logE("[***] DataWrapper.doHandleEvents", "event.getStatus()=" + event.getStatus());
        PPApplication.logE("[***] DataWrapper.doHandleEvents", "newEventStatus=" + newEventStatus);
        if ((event.getStatus() != newEventStatus) || restartEvent || event._isInDelayStart || event._isInDelayEnd) {
            PPApplication.logE("[***] DataWrapper.doHandleEvents", " do new event status");
            if ((newEventStatus == Event.ESTATUS_RUNNING) && (!statePause)) {
                PPApplication.logE("[***] DataWrapper.doHandleEvents", "start event");
                PPApplication.logE("[***] DataWrapper.doHandleEvents", "event._name=" + event._name);
                if (event._isInDelayEnd)
                    event.removeDelayEndAlarm(this);
                else {
                    if (!forDelayStartAlarm) {
                        // called not for delay alarm
                        /*if (restartEvent) {
                                event._isInDelayStart = false;
                            } else*/
                        {
                            if (!event._isInDelayStart) {
                                // if not delay alarm is set, set it
                                // for start delay
                                event.setDelayStartAlarm(this);
                            }
                            if (event._isInDelayStart) {
                                // if delay expires, start event
                                event.checkDelayStart();
                            }
                        }
                        PPApplication.logE("[***] DataWrapper.doHandleEvents", "event._isInDelayStart=" + event._isInDelayStart);
                        if (!event._isInDelayStart) {
                            // no delay alarm is set
                            // start event
                            event.startEvent(this, eventTimelineList, /*interactive,*/
                            reactivate, mergedProfile);
                            PPApplication.logE("[***] DataWrapper.doHandleEvents", "mergedProfile._id=" + mergedProfile._id);
                        }
                    }
                    if (forDelayStartAlarm && event._isInDelayStart) {
                        // called for delay alarm
                        // start event
                        event.startEvent(this, eventTimelineList, /*interactive,*/
                        reactivate, mergedProfile);
                    }
                }
            } else if (((newEventStatus == Event.ESTATUS_PAUSE) || restartEvent) && statePause) {
                // when pausing and it is for restart events, force pause
                PPApplication.logE("[***] DataWrapper.doHandleEvents", "pause event");
                PPApplication.logE("[***] DataWrapper.doHandleEvents", "event._name=" + event._name);
                if (event._isInDelayStart) {
                    PPApplication.logE("[***] DataWrapper.doHandleEvents", "isInDelayStart");
                    event.removeDelayStartAlarm(this);
                } else {
                    if (!forDelayEndAlarm) {
                        PPApplication.logE("[***] DataWrapper.doHandleEvents", "!forDelayEndAlarm");
                        // called not for delay alarm
                        if (restartEvent) {
                            event._isInDelayEnd = false;
                        } else {
                            if (!event._isInDelayEnd) {
                                // if not delay alarm is set, set it
                                // for end delay
                                event.setDelayEndAlarm(this);
                            }
                            if (event._isInDelayEnd) {
                                // if delay expires, pause event
                                event.checkDelayEnd();
                            }
                        }
                        if (!event._isInDelayEnd) {
                            // no delay alarm is set
                            // pause event
                            event.pauseEvent(this, eventTimelineList, true, false, false, true, mergedProfile, !restartEvent);
                        }
                    }
                    if (forDelayEndAlarm && event._isInDelayEnd) {
                        // called for delay alarm
                        // pause event
                        event.pauseEvent(this, eventTimelineList, true, false, false, true, mergedProfile, !restartEvent);
                    }
                }
            }
        }
    }
    PPApplication.logE("%%% DataWrapper.doHandleEvents", "--- end --------------------------");
}
Also used : WifiManager(android.net.wifi.WifiManager) ConnectivityManager(android.net.ConnectivityManager) Cursor(android.database.Cursor) PowerManager(android.os.PowerManager) Network(android.net.Network) NfcAdapter(android.nfc.NfcAdapter) LocationManager(android.location.LocationManager) IntentFilter(android.content.IntentFilter) NetworkInfo(android.net.NetworkInfo) Calendar(java.util.Calendar) Intent(android.content.Intent) SuppressLint(android.annotation.SuppressLint) WifiInfo(android.net.wifi.WifiInfo) SimpleDateFormat(java.text.SimpleDateFormat) KeyguardManager(android.app.KeyguardManager) BluetoothAdapter(android.bluetooth.BluetoothAdapter) SuppressLint(android.annotation.SuppressLint)

Aggregations

LocationManager (android.location.LocationManager)151 Location (android.location.Location)51 Bundle (android.os.Bundle)33 LocationListener (android.location.LocationListener)29 Criteria (android.location.Criteria)21 Intent (android.content.Intent)20 BluetoothAdapter (android.bluetooth.BluetoothAdapter)15 View (android.view.View)10 SuppressLint (android.annotation.SuppressLint)9 IOException (java.io.IOException)9 ConnectivityManager (android.net.ConnectivityManager)7 WifiManager (android.net.wifi.WifiManager)7 TextView (android.widget.TextView)7 DialogInterface (android.content.DialogInterface)6 IntentFilter (android.content.IntentFilter)6 SharedPreferences (android.content.SharedPreferences)6 PendingIntent (android.app.PendingIntent)5 NetworkInfo (android.net.NetworkInfo)5 TelephonyManager (android.telephony.TelephonyManager)5 TrackerDataHelper (com.android.locationtracker.data.TrackerDataHelper)5