Search in sources :

Example 51 with ContentObserver

use of android.database.ContentObserver in project aware-client by denzilferreira.

the class Scheduler method onStartCommand.

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStartCommand(intent, flags, startId);
    if (PERMISSIONS_OK) {
        // Restores core AWARE service in case it get's killed
        if (!Aware.IS_CORE_RUNNING) {
            Intent aware = new Intent(getApplicationContext(), Aware.class);
            startService(aware);
        }
        DEBUG = Aware.getSetting(this, Aware_Preferences.DEBUG_FLAG).equals("true");
        if (DEBUG)
            Log.d(TAG, "Checking for scheduled tasks: " + getPackageName());
        String standalone = "";
        if (getApplicationContext().getResources().getBoolean(R.bool.standalone)) {
            standalone = " OR " + Scheduler_Provider.Scheduler_Data.PACKAGE_NAME + " LIKE 'com.aware.phone'";
        }
        Cursor scheduled_tasks = getContentResolver().query(Scheduler_Provider.Scheduler_Data.CONTENT_URI, null, Scheduler_Provider.Scheduler_Data.PACKAGE_NAME + " LIKE '" + getPackageName() + "'" + standalone, null, Scheduler_Provider.Scheduler_Data.TIMESTAMP + " ASC");
        if (scheduled_tasks != null && scheduled_tasks.moveToFirst()) {
            if (DEBUG)
                Log.d(TAG, "Scheduled tasks for " + getPackageName() + ": " + scheduled_tasks.getCount());
            do {
                try {
                    final Schedule schedule = getSchedule(this, scheduled_tasks.getString(scheduled_tasks.getColumnIndex(Scheduler_Provider.Scheduler_Data.SCHEDULE_ID)));
                    // unable to load schedule. This should never happen.
                    if (schedule == null) {
                        if (DEBUG)
                            Log.e(TAG, "Failed to load schedule... something is wrong with the database.");
                        continue;
                    }
                    // Schedulers triggered by broadcasts
                    if (schedule.getContexts().length() > 0) {
                        // Check if we already registered the broadcastreceiver for this schedule
                        if (!schedulerListeners.containsKey(schedule.getScheduleID())) {
                            final JSONArray contexts = schedule.getContexts();
                            IntentFilter filter = new IntentFilter();
                            for (int i = 0; i < contexts.length(); i++) {
                                String context = contexts.getString(i);
                                filter.addAction(context);
                            }
                            BroadcastReceiver listener = new BroadcastReceiver() {

                                @Override
                                public void onReceive(Context context, Intent intent) {
                                    if (is_trigger(schedule)) {
                                        if (DEBUG)
                                            Log.d(TAG, "Triggered contextual trigger: " + contexts.toString());
                                        performAction(schedule);
                                    }
                                }
                            };
                            Hashtable<IntentFilter, BroadcastReceiver> scheduler_listener = new Hashtable<>();
                            scheduler_listener.put(filter, listener);
                            schedulerListeners.put(schedule.getScheduleID(), scheduler_listener);
                            registerReceiver(listener, filter);
                            if (DEBUG)
                                Log.d(TAG, "Registered a contextual trigger for " + contexts.toString());
                        } else {
                            if (DEBUG)
                                Log.d(TAG, "Contextual triggers are active: " + schedule.getContexts().toString());
                        }
                        continue;
                    }
                    // Schedulers triggered by database changes
                    if (schedule.getConditions().length() > 0) {
                        // Check if we already registered the ContentObservers for this schedule
                        if (!schedulerDataObservers.containsKey(schedule.getScheduleID())) {
                            Hashtable<Uri, ContentObserver> dataObs = new Hashtable<>();
                            final JSONArray conditions = schedule.getConditions();
                            for (int i = 0; i < conditions.length(); i++) {
                                JSONObject condition = conditions.getJSONObject(i);
                                Uri content_uri = Uri.parse(condition.getString(CONDITION_URI));
                                String content_where = condition.getString(CONDITION_WHERE);
                                DBObserver dbObs = new DBObserver(new Handler()).setCondition(content_where).setData(content_uri).setSchedule(schedule);
                                dataObs.put(content_uri, dbObs);
                                getContentResolver().registerContentObserver(content_uri, true, dbObs);
                            }
                            schedulerDataObservers.put(schedule.getScheduleID(), dataObs);
                            if (DEBUG)
                                Log.d(TAG, "Registered conditional triggers: " + conditions.toString());
                        } else {
                            if (DEBUG)
                                Log.d(TAG, "Conditional triggers are active: " + schedule.getConditions().toString());
                        }
                        continue;
                    }
                    // Not contextual or conditional scheduler, it is time-based
                    if (is_trigger(schedule)) {
                        if (DEBUG)
                            Log.d(TAG, "Triggering scheduled task: " + schedule.getScheduleID() + " in package: " + getPackageName());
                        performAction(schedule);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } while (scheduled_tasks.moveToNext());
        } else {
            if (DEBUG)
                Log.d(TAG, "No scheduled tasks for " + getPackageName());
        }
        if (scheduled_tasks != null && !scheduled_tasks.isClosed())
            scheduled_tasks.close();
    }
    return START_STICKY;
}
Also used : Context(android.content.Context) IntentFilter(android.content.IntentFilter) Hashtable(java.util.Hashtable) JSONArray(org.json.JSONArray) Handler(android.os.Handler) JSONException(org.json.JSONException) Intent(android.content.Intent) Cursor(android.database.Cursor) BroadcastReceiver(android.content.BroadcastReceiver) Uri(android.net.Uri) JSONObject(org.json.JSONObject) ContentObserver(android.database.ContentObserver)

Example 52 with ContentObserver

use of android.database.ContentObserver in project aware-client by denzilferreira.

the class Scheduler method clearContentObservers.

private static void clearContentObservers(Context c, String schedule_id) {
    if (schedulerDataObservers.size() == 0)
        return;
    Hashtable<Uri, ContentObserver> scheduled = schedulerDataObservers.get(schedule_id);
    for (Uri data : scheduled.keySet()) {
        try {
            c.getContentResolver().unregisterContentObserver(scheduled.get(data));
        } catch (IllegalArgumentException | NullPointerException e) {
        }
    }
    schedulerDataObservers.remove(schedule_id);
}
Also used : Uri(android.net.Uri) ContentObserver(android.database.ContentObserver)

Example 53 with ContentObserver

use of android.database.ContentObserver in project android_frameworks_base by crdroidandroid.

the class DropBoxManagerService method onStart.

@Override
public void onStart() {
    // Set up intent receivers
    IntentFilter filter = new IntentFilter();
    filter.addAction(Intent.ACTION_DEVICE_STORAGE_LOW);
    getContext().registerReceiver(mReceiver, filter);
    mContentResolver.registerContentObserver(Settings.Global.CONTENT_URI, true, new ContentObserver(new Handler()) {

        @Override
        public void onChange(boolean selfChange) {
            mReceiver.onReceive(getContext(), (Intent) null);
        }
    });
    publishBinderService(Context.DROPBOX_SERVICE, mStub);
// The real work gets done lazily in init() -- that way service creation always
// succeeds, and things like disk problems cause individual method failures.
}
Also used : IntentFilter(android.content.IntentFilter) Handler(android.os.Handler) Intent(android.content.Intent) ContentObserver(android.database.ContentObserver)

Example 54 with ContentObserver

use of android.database.ContentObserver in project android_frameworks_base by ResurrectionRemix.

the class SettingsProviderTest method setSettingAndAssertSuccessfulChange.

private void setSettingAndAssertSuccessfulChange(Runnable setCommand, final int type, final String name, final String value, final int userId) throws Exception {
    ContentResolver contentResolver = getContext().getContentResolver();
    final Uri settingUri = getBaseUriForType(type);
    final AtomicBoolean success = new AtomicBoolean();
    ContentObserver contentObserver = new ContentObserver(new Handler(Looper.getMainLooper())) {

        public void onChange(boolean selfChange, Uri changeUri, int changeId) {
            Log.i(LOG_TAG, "onChange(" + selfChange + ", " + changeUri + ", " + changeId + ")");
            assertEquals("Wrong change Uri", changeUri, settingUri);
            assertEquals("Wrong user id", userId, changeId);
            String changeValue = getStringViaFrontEndApiSetting(type, name, userId);
            assertEquals("Wrong setting value", value, changeValue);
            success.set(true);
            synchronized (mLock) {
                mLock.notifyAll();
            }
        }
    };
    contentResolver.registerContentObserver(settingUri, false, contentObserver, userId);
    try {
        setCommand.run();
        final long startTimeMillis = SystemClock.uptimeMillis();
        synchronized (mLock) {
            if (success.get()) {
                return;
            }
            final long elapsedTimeMillis = SystemClock.uptimeMillis() - startTimeMillis;
            if (elapsedTimeMillis > WAIT_FOR_SETTING_URI_CHANGE_TIMEOUT_MILLIS) {
                fail("Could not change setting for " + WAIT_FOR_SETTING_URI_CHANGE_TIMEOUT_MILLIS + " ms");
            }
            final long remainingTimeMillis = WAIT_FOR_SETTING_URI_CHANGE_TIMEOUT_MILLIS - elapsedTimeMillis;
            try {
                mLock.wait(remainingTimeMillis);
            } catch (InterruptedException ie) {
            /* ignore */
            }
        }
    } finally {
        contentResolver.unregisterContentObserver(contentObserver);
    }
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Handler(android.os.Handler) Uri(android.net.Uri) ContentResolver(android.content.ContentResolver) ContentObserver(android.database.ContentObserver)

Example 55 with ContentObserver

use of android.database.ContentObserver in project muzei by romannurik.

the class NextArtworkTileService method onStartListening.

@Override
public void onStartListening() {
    // Start listening for source changes, which will include when a source
    // starts or stops supporting the 'Next Artwork' command
    mSourceContentObserver = new ContentObserver(null) {

        @Override
        public void onChange(final boolean selfChange, final Uri uri) {
            updateTile();
        }
    };
    getContentResolver().registerContentObserver(MuzeiContract.Sources.CONTENT_URI, true, mSourceContentObserver);
    // Check if the wallpaper is currently active
    EventBus.getDefault().register(this);
    WallpaperActiveStateChangedEvent e = EventBus.getDefault().getStickyEvent(WallpaperActiveStateChangedEvent.class);
    // This will call through to updateTile()
    onEventMainThread(e);
}
Also used : WallpaperActiveStateChangedEvent(com.google.android.apps.muzei.event.WallpaperActiveStateChangedEvent) Uri(android.net.Uri) ContentObserver(android.database.ContentObserver)

Aggregations

ContentObserver (android.database.ContentObserver)96 Handler (android.os.Handler)41 Uri (android.net.Uri)35 ContentResolver (android.content.ContentResolver)28 Intent (android.content.Intent)16 IntentFilter (android.content.IntentFilter)16 BroadcastReceiver (android.content.BroadcastReceiver)9 Context (android.content.Context)9 PendingIntent (android.app.PendingIntent)7 RemoteException (android.os.RemoteException)7 Test (org.junit.Test)7 AppOpsManager (android.app.AppOpsManager)6 GeofenceManager (com.android.server.location.GeofenceManager)6 LocationBlacklist (com.android.server.location.LocationBlacklist)6 LocationFudger (com.android.server.location.LocationFudger)6 HashSet (java.util.HashSet)6 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)6 Mockito.doAnswer (org.mockito.Mockito.doAnswer)6 InvocationOnMock (org.mockito.invocation.InvocationOnMock)6 Answer (org.mockito.stubbing.Answer)6