Example usage for android.database ContentObserver ContentObserver

List of usage examples for android.database ContentObserver ContentObserver

Introduction

In this page you can find the example usage for android.database ContentObserver ContentObserver.

Prototype

public ContentObserver(Handler handler) 

Source Link

Document

Creates a content observer.

Usage

From source file:com.ferdi2005.secondgram.AndroidUtilities.java

private static void registerLoginContentObserver(boolean shouldRegister, final String number) {
    if (shouldRegister) {
        if (callLogContentObserver != null) {
            return;
        }/*from  w  w  w  . j av  a 2s  .co  m*/
        ApplicationLoader.applicationContext.getContentResolver().registerContentObserver(
                android.provider.CallLog.Calls.CONTENT_URI, true,
                callLogContentObserver = new ContentObserver(new Handler()) {
                    @Override
                    public boolean deliverSelfNotifications() {
                        return true;
                    }

                    @Override
                    public void onChange(boolean selfChange) {
                        registerLoginContentObserver(false, number);
                        removeLoginPhoneCall(number, false);
                    }
                });
        runOnUIThread(unregisterRunnable = new Runnable() {
            @Override
            public void run() {
                unregisterRunnable = null;
                registerLoginContentObserver(false, number);
            }
        }, 10000);
    } else {
        if (callLogContentObserver == null) {
            return;
        }
        if (unregisterRunnable != null) {
            cancelRunOnUIThread(unregisterRunnable);
            unregisterRunnable = null;
        }
        try {
            ApplicationLoader.applicationContext.getContentResolver()
                    .unregisterContentObserver(callLogContentObserver);
        } catch (Exception ignore) {

        } finally {
            callLogContentObserver = null;
        }
    }
}

From source file:com.bernard.beaconportal.activities.activity.MessageList.java

@SuppressLint("ResourceAsColor")
@Override//from   w w  w. j a v a 2  s.  c  o m
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    requestWindowFeature(Window.FEATURE_PROGRESS);

    if (!K9.isHideSpecialAccounts()) {
        createSpecialAccounts();
    }

    Account[] accounts = Preferences.getPreferences(this).getAccounts();
    Intent intent = getIntent();
    // onNewIntent(intent);

    // see if we should show the welcome message
    if (ACTION_IMPORT_SETTINGS.equals(intent.getAction())) {
        mAccounts.onImport();
    } else if (accounts.length < 1) {
        WelcomeMessage.showWelcomeMessage(this);
        finish();
        return;
    }

    if (UpgradeDatabases.actionUpgradeDatabases(this, intent)) {
        finish();
        return;
    }

    Log.d(TAG, "onCreate()");

    String packageName = "com.bernard.beaconportal.activities";

    counterss = "0";

    int versionNumber = 0;

    try {
        PackageInfo pi = getApplicationContext().getPackageManager().getPackageInfo(packageName,
                PackageManager.GET_META_DATA);
        versionNumber = pi.versionCode;
        String versionName = pi.versionName;

        Log.d(TAG, "K-9 is installed - " + versionNumber + " " + versionName);

    } catch (NameNotFoundException e) {
        Log.d(TAG, "K-9 not found");
    }

    if (versionNumber <= 1) {
        // Register a listener for broadcasts (needed for the older versions
        // of k9)
        Log.d(TAG, "Initialising BroadcastReceiver for old K-9 version");
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Log.d(TAG, "receiver.onReceive()");
                doRefresh();
            }
        };

        filter = new IntentFilter();
        filter.addAction("com.bernard.beaconportal.activities.intent.action.EMAIL_RECEIVED");
        filter.addAction("com.bernard.beaconportal.activities.intent.action.EMAIL_DELETED");
        filter.addDataScheme("email");
        registerReceiver(receiver, filter);
    } else {
        // Register our own content observer, rather than using
        // addWatchContentUris()
        // since DashClock might not have permission to access the database
        Log.d(TAG, "Initialising ContentObserver for new K-9 version");
        contentObserver = new ContentObserver(null) {
            @Override
            public void onChange(boolean selfChange) {
                Log.d(TAG, "contentResolver.onChange()");
                doRefresh();
            }
        };
        getContentResolver().registerContentObserver(Uri.parse(k9UnreadUri), true, contentObserver);
    }

    doRefresh();

    if (UpgradeDatabases.actionUpgradeDatabases(this, getIntent())) {
        finish();
        return;
    }

    if (useSplitView()) {
        setContentView(R.layout.split_drawer_main);
    } else {
        setContentView(R.layout.drawermain1);
        mViewSwitcher = (ViewSwitcher) findViewById(R.id.container);
        mViewSwitcher.setFirstInAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_in_left));
        mViewSwitcher.setFirstOutAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_out_right));
        mViewSwitcher.setSecondInAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_in_right));
        mViewSwitcher.setSecondOutAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_out_left));
        mViewSwitcher.setOnSwitchCompleteListener(this);
    }

    mergeadapter = new MergeAdapter();

    LayoutInflater inflater = getLayoutInflater();

    accounts_view = inflater.inflate(R.layout.accounts_list, null);

    portals_view = inflater.inflate(R.layout.portal_list, null);

    folders_view = inflater.inflate(R.layout.folders_list, null);

    header_folders = inflater.inflate(R.layout.header_folders, null);

    header_drawer = inflater.inflate(R.layout.header_drawer, null);

    initializeActionBar();

    mListView = (ListView) findViewById(android.R.id.list);
    // mListView.addHeaderView(header_folders, null, false);

    mListView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
    mListView.setLongClickable(true);
    mListView.setFastScrollEnabled(true);
    mListView.setScrollingCacheEnabled(false);
    // mListView.setOnItemClickListener(new OnItemClickListener() {
    // public void onItemClick(AdapterView<?> parent, View view,
    // int position, long id) {
    //
    // onOpenFolder(((FolderInfoHolder) mAdapter.getItem(position)).name);
    //
    // Log.d("Folder Click Listener", "clicked");
    //
    // }
    // });

    setResult(RESULT_CANCELED);

    // mDrawerList_Inbox = (ListView) findViewById(R.id.listview_inbox);
    //
    // View header_inbox = (View) inflater
    // .inflate(R.layout.header_inbox, null);
    //
    // mDrawerList_Inbox.setOnItemClickListener(this);
    //
    // mDrawerList_Inbox.setItemsCanFocus(false);
    //
    // mDrawerList_Inbox.setLongClickable(true);

    mListView.setSaveEnabled(true);

    mInflater = getLayoutInflater();

    onNewIntent(getIntent());

    context = this;

    SharedPreferences sharedpre = getSharedPreferences("show_view", Context.MODE_PRIVATE);

    Show_View = sharedpre.getString("show_view", "");

    SharedPreferences Today_Homework = getApplicationContext().getSharedPreferences("due_today",
            Context.MODE_PRIVATE);

    SharedPreferences counts = getSharedPreferences("due_today", Context.MODE_PRIVATE);

    if (counts.contains("homeworkdue")) {
        counterss = counts.getString("homeworkdue", null);
    } else {

        counterss = null;
    }

    title_Inbox = new String[] { "Inbox" };

    icon_Inbox = new int[] { R.drawable.ic_action_email };

    count_Inbox = new String[] { K9counts };

    if (Show_View.equals("Homework Due")) {

        title = new String[] { "Homework Due", "Schedule", "Resources", "Options", "Logout" };

        icon = new int[] { R.drawable.ic_action_duehomework, R.drawable.ic_action_go_to_today,
                R.drawable.ic_action_resources, R.drawable.ic_action_settings, R.drawable.ic_action_logout };

        if (counterss == null && counterss.isEmpty()) {

            count = new String[] { "", "", "", "", "" };

        } else {

            count = new String[] { counterss, "", "", "", "" };

        }

    } else {

        if (counterss == null && counterss.isEmpty()) {

            count = new String[] { "", "", "", "", "" };

        } else {

            count = new String[] { "", counterss, "", "", "" };

        }

        title = new String[] { "Schedule", "Homework Due", "Resources", "Options", "Logout" };

        icon = new int[] { R.drawable.ic_action_go_to_today, R.drawable.ic_action_duehomework,
                R.drawable.ic_action_resources, R.drawable.ic_action_settings, R.drawable.ic_action_logout };

    }

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

    mDrawerLinear = (LinearLayout) findViewById(R.id.left_drawer);

    // mDrawerList_Inbox = (ListView) findViewById(R.id.listview_inbox);

    // mDrawerList = (ListView) findViewById(R.id.listview_drawer);

    // mDrawer_Scroll = (ScrollView)
    // findViewById(R.id.left_drawer_scrollview);

    // mDrawerList.addHeaderView(header_drawer, null, false);

    mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);

    // mMenuAdapter_Inbox = new MenuListAdapter(MessageList.this,
    // title_Inbox,
    // icon_Inbox, count_Inbox);

    // mDrawerList_Inbox.setAdapter(mMenuAdapter_Inbox);

    // mDrawerList_Inbox
    // .setOnItemClickListener(new DrawerItemClickListener_Inbox());

    mMenuAdapter = new MenuListAdapter(MessageList.this, title, icon, count);

    // mDrawerList.setAdapter(mMenuAdapter);

    // mergeadapter.addView(header_drawer);
    //
    // mergeadapter.addAdapter(mMenuAdapter);
    //
    // mergeadapter.addadapter(AccountsAdapter);
    //
    // mDrawerList.setAdapter(mergeadapter);

    getListView().setOnItemClickListener(new DrawerItemClickListener());

    // mDrawerList_Inbox.setOnItemClickListener(new
    // DrawerItemClickListener());

    //
    // if (savedInstanceState == null) {
    // selectItem_Inbox(1);
    // }

    SharedPreferences sharedpref = getSharedPreferences("actionbar_color", Context.MODE_PRIVATE);

    final int splitBarId = getResources().getIdentifier("split_action_bar", "id", "android");
    final View splitActionBar = findViewById(splitBarId);

    if (!sharedpref.contains("actionbar_color")) {

        getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#4285f4")));

        if (splitActionBar != null) {

            splitActionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#4285f4")));

        }

    } else {

        actionbar_colors = sharedpref.getString("actionbar_color", null);

        getActionBar().setBackgroundDrawable(

                new ColorDrawable(Color.parseColor(actionbar_colors)));

        if (splitActionBar != null) {

            splitActionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor(actionbar_colors)));

        }

    }

    android.app.ActionBar bar = getActionBar();

    bar.setIcon(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
    // Enable gesture detection for MessageLists
    // setupGestureDetector(this);

    if (!decodeExtras(getIntent())) {
        return;
    }

    findFragments();
    initializeDisplayMode(savedInstanceState);
    initializeLayout();
    initializeFragments();
    displayViews();
    // registerForContextMenu(mDrawerList_Inbox);
    registerForContextMenu(mListView);

    getActionBar().setHomeButtonEnabled(true);
    getActionBar().setDisplayHomeAsUpEnabled(true);

    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer, R.string.drawer_open,
            R.string.drawer_close) {

        @Override
        public void onDrawerClosed(View view) {
            // TODO Auto-generated method stub
            super.onDrawerClosed(view);
        }

        @Override
        public void onDrawerOpened(View drawerView) {
            // TODO Auto-generated method stub

            super.onDrawerOpened(drawerView);
        }
    };

    mDrawerLayout.setDrawerListener(mDrawerToggle);

}

From source file:nl.sogeti.android.gpstracker.viewer.LoggerMap.java

private void createListeners() {
    mFab.setOnClickListener(new View.OnClickListener() {
        @Override//from   ww w  . ja  v a2s  .co m
        public void onClick(View v) {
            Intent intent = new Intent(LoggerMap.this, ControlTracking.class);
            startActivityForResult(intent, MENU_TRACKING);
        }
    });
    /*******************************************************
     * 8 Runnable listener actions
     */
    speedCalculator = new Runnable() {
        @Override
        public void run() {
            double avgspeed = 0.0;
            ContentResolver resolver = LoggerMap.this.getContentResolver();
            Cursor waypointsCursor = null;
            try {
                waypointsCursor = resolver.query(
                        Uri.withAppendedPath(Tracks.CONTENT_URI, LoggerMap.this.mTrackId + "/waypoints"),
                        new String[] { "avg(" + Waypoints.SPEED + ")", "max(" + Waypoints.SPEED + ")" }, null,
                        null, null);

                if (waypointsCursor != null && waypointsCursor.moveToLast()) {
                    double average = waypointsCursor.getDouble(0);
                    double maxBasedAverage = waypointsCursor.getDouble(1) / 2;
                    avgspeed = Math.min(average, maxBasedAverage);
                }
                if (avgspeed < 2) {
                    avgspeed = 5.55d / 2;
                }
            } finally {
                if (waypointsCursor != null) {
                    waypointsCursor.close();
                }
            }
            mAverageSpeed = avgspeed;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    updateSpeedColoring();
                }
            });
        }
    };
    mServiceConnected = new Runnable() {
        @Override
        public void run() {
            updateBlankingBehavior();
        }
    };
    /*******************************************************
     * 8 Various dialog listeners
     */
    mNoteSelectDialogListener = new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            Uri selected = (Uri) mGallery.getSelectedItem();
            SegmentOverlay.handleMedia(LoggerMap.this, selected);
        }
    };
    mGroupCheckedChangeListener = new android.widget.RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            switch (checkedId) {
            case R.id.layer_google_satellite:
                setSatelliteOverlay(true);
                break;
            case R.id.layer_google_regular:
                setSatelliteOverlay(false);
                break;
            default:
                break;
            }
        }
    };
    mCheckedChangeListener = new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            int checkedId;
            checkedId = buttonView.getId();
            switch (checkedId) {
            case R.id.layer_traffic:
                setTrafficOverlay(isChecked);
                break;
            case R.id.layer_speed:
                setSpeedOverlay(isChecked);
                break;
            case R.id.layer_altitude:
                setAltitudeOverlay(isChecked);
                break;
            case R.id.layer_distance:
                setDistanceOverlay(isChecked);
                break;
            case R.id.layer_compass:
                setCompassOverlay(isChecked);
                break;
            case R.id.layer_location:
                setLocationOverlay(isChecked);
                break;
            default:
                break;
            }
        }
    };
    mNoTrackDialogListener = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            //            Log.d( TAG, "mNoTrackDialogListener" + which);
            Intent tracklistIntent = new Intent(LoggerMap.this, TrackList.class);
            tracklistIntent.putExtra(Tracks._ID, LoggerMap.this.mTrackId);
            startActivityForResult(tracklistIntent, MENU_TRACKLIST);
        }
    };
    /**
     * Listeners to events outside this mapview
     */
    mSharedPreferenceChangeListener = new OnSharedPreferenceChangeListener() {
        @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
            if (key.equals(Constants.TRACKCOLORING)) {
                mAverageSpeed = 0.0;
                updateSpeedColoring();
            } else if (key.equals(Constants.DISABLEBLANKING) || key.equals(Constants.DISABLEDIMMING)) {
                updateBlankingBehavior();
            } else if (key.equals(Constants.SPEED)) {
                updateSpeedDisplayVisibility();
            } else if (key.equals(Constants.ALTITUDE)) {
                updateAltitudeDisplayVisibility();
            } else if (key.equals(Constants.DISTANCE)) {
                updateDistanceDisplayVisibility();
            } else if (key.equals(Constants.COMPASS)) {
                updateCompassDisplayVisibility();
            } else if (key.equals(Constants.TRAFFIC)) {
                updateGoogleOverlays();
            } else if (key.equals(Constants.SATELLITE)) {
                updateGoogleOverlays();
            } else if (key.equals(Constants.LOCATION)) {
                updateLocationDisplayVisibility();
            }
        }
    };
    mTrackMediasObserver = new ContentObserver(new Handler()) {
        @Override
        public void onChange(boolean selfUpdate) {
            if (!selfUpdate) {
                if (mLastSegmentOverlay != null) {
                    mLastSegmentOverlay.calculateMedia();
                    mMapView.postInvalidate();
                }
            } else {
                Log.w(this, "mTrackMediasObserver skipping change on " + mLastSegment);
            }
        }
    };
    mTrackSegmentsObserver = new ContentObserver(new Handler()) {
        @Override
        public void onChange(boolean selfUpdate) {
            if (!selfUpdate) {
                LoggerMap.this.updateDataOverlays();
            } else {
                Log.w(this, "mTrackSegmentsObserver skipping change on " + mLastSegment);
            }
        }
    };
    mSegmentWaypointsObserver = new ContentObserver(new Handler()) {
        @Override
        public void onChange(boolean selfUpdate) {
            if (!selfUpdate) {
                LoggerMap.this.updateTrackNumbers();
                if (mLastSegmentOverlay != null) {
                    moveActiveViewWindow();
                } else {
                    Log.e(this, "Error the last segment changed but it is not on screen! " + mLastSegment);
                }
            } else {
                Log.w(this, "mSegmentWaypointsObserver skipping change on " + mLastSegment);
            }
        }
    };
    mUnitsChangeListener = new UnitsI18n.UnitsChangeListener() {
        @Override
        public void onUnitsChange() {
            mAverageSpeed = 0.0;
            updateTrackNumbers();
            updateSpeedColoring();
        }
    };
}

From source file:org.brandroid.openmanager.activities.OpenExplorer.java

public void handleMediaReceiver() {
    storageReceiver = new BroadcastReceiver() {
        @Override/*from w  w  w.  j av  a2  s.c  o  m*/
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            String data = intent.getDataString();
            final String path = data.replace("file://", "");
            if (action.equals(Intent.ACTION_MEDIA_MOUNTED))
                handleRefreshMedia(path, true, 10);
            else
                refreshBookmarks();
        }
    };

    IntentFilter filter = new IntentFilter();
    filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
    filter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
    filter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED);
    filter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
    filter.addAction(Intent.ACTION_MEDIA_EJECT);
    filter.addDataScheme("file");
    registerReceiver(storageReceiver, filter);

    ContentObserver mDbObserver = new ContentObserver(mHandler) {
        @Override
        public void onChange(boolean selfChange) {
            //rebake(false, ImageManager.isMediaScannerScanning(
            //      getContentResolver()));
        }
    };

    getContentResolver().registerContentObserver(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, true,
            mDbObserver);
}