Example usage for android.support.v4.content LocalBroadcastManager registerReceiver

List of usage examples for android.support.v4.content LocalBroadcastManager registerReceiver

Introduction

In this page you can find the example usage for android.support.v4.content LocalBroadcastManager registerReceiver.

Prototype

public void registerReceiver(BroadcastReceiver receiver, IntentFilter filter) 

Source Link

Document

Register a receive for any local broadcasts that match the given IntentFilter.

Usage

From source file:com.facebook.LikeView.java

private void associateWithLikeActionController(LikeActionController likeActionController) {
    this.likeActionController = likeActionController;

    this.broadcastReceiver = new LikeControllerBroadcastReceiver();
    LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(getContext());

    // add the broadcast receiver
    IntentFilter filter = new IntentFilter();
    filter.addAction(LikeActionController.ACTION_LIKE_ACTION_CONTROLLER_UPDATED);
    filter.addAction(LikeActionController.ACTION_LIKE_ACTION_CONTROLLER_DID_ERROR);
    filter.addAction(LikeActionController.ACTION_LIKE_ACTION_CONTROLLER_DID_RESET);

    localBroadcastManager.registerReceiver(broadcastReceiver, filter);
}

From source file:com.facebook.SessionTests.java

@SmallTest
@MediumTest/*w  ww .j  ava  2s . co  m*/
@LargeTest
public void testActiveSessionChangeRegistration() {
    final WaitForBroadcastReceiver receiver0 = new WaitForBroadcastReceiver();
    final WaitForBroadcastReceiver receiver1 = new WaitForBroadcastReceiver();
    final WaitForBroadcastReceiver receiver2 = new WaitForBroadcastReceiver();
    final LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(getActivity());

    try {
        // Register these on the blocker thread so they will send
        // notifications there as well. The notifications need to be on a
        // different thread than the progress.
        Runnable initialize0 = new Runnable() {
            @Override
            public void run() {
                broadcastManager.registerReceiver(receiver0, getActiveSessionAllFilter());

                broadcastManager.registerReceiver(receiver1,
                        getActiveSessionFilter(Session.ACTION_ACTIVE_SESSION_SET));
                broadcastManager.registerReceiver(receiver1,
                        getActiveSessionFilter(Session.ACTION_ACTIVE_SESSION_OPENED));
                broadcastManager.registerReceiver(receiver1,
                        getActiveSessionFilter(Session.ACTION_ACTIVE_SESSION_CLOSED));

                broadcastManager.registerReceiver(receiver2,
                        getActiveSessionFilter(Session.ACTION_ACTIVE_SESSION_OPENED));
                broadcastManager.registerReceiver(receiver2,
                        getActiveSessionFilter(Session.ACTION_ACTIVE_SESSION_CLOSED));
            }
        };
        runOnBlockerThread(initialize0, true);

        // Verify all actions show up where they are expected
        WaitForBroadcastReceiver.incrementExpectCounts(receiver0, receiver1, receiver2);
        Session.postActiveSessionAction(Session.ACTION_ACTIVE_SESSION_OPENED);
        WaitForBroadcastReceiver.waitForExpectedCalls(receiver0, receiver1, receiver2);

        WaitForBroadcastReceiver.incrementExpectCounts(receiver0, receiver1, receiver2);
        Session.postActiveSessionAction(Session.ACTION_ACTIVE_SESSION_CLOSED);
        WaitForBroadcastReceiver.waitForExpectedCalls(receiver0, receiver1, receiver2);

        WaitForBroadcastReceiver.incrementExpectCounts(receiver0, receiver1);
        Session.postActiveSessionAction(Session.ACTION_ACTIVE_SESSION_SET);
        WaitForBroadcastReceiver.waitForExpectedCalls(receiver0, receiver1);

        receiver0.incrementExpectCount();
        Session.postActiveSessionAction(Session.ACTION_ACTIVE_SESSION_UNSET);
        receiver0.waitForExpectedCalls();

        // Remove receiver1 and verify actions continue to show up where
        // expected
        broadcastManager.unregisterReceiver(receiver1);

        WaitForBroadcastReceiver.incrementExpectCounts(receiver0, receiver2);
        Session.postActiveSessionAction(Session.ACTION_ACTIVE_SESSION_OPENED);
        WaitForBroadcastReceiver.waitForExpectedCalls(receiver0, receiver2);

        WaitForBroadcastReceiver.incrementExpectCounts(receiver0, receiver2);
        Session.postActiveSessionAction(Session.ACTION_ACTIVE_SESSION_CLOSED);
        WaitForBroadcastReceiver.waitForExpectedCalls(receiver0, receiver2);

        receiver0.incrementExpectCount();
        Session.postActiveSessionAction(Session.ACTION_ACTIVE_SESSION_SET);
        receiver0.waitForExpectedCalls();

        receiver0.incrementExpectCount();
        Session.postActiveSessionAction(Session.ACTION_ACTIVE_SESSION_UNSET);
        receiver0.waitForExpectedCalls();

        // Remove receiver0 and register receiver1 multiple times for one
        // action
        broadcastManager.unregisterReceiver(receiver0);

        Runnable initialize1 = new Runnable() {
            @Override
            public void run() {
                broadcastManager.registerReceiver(receiver1,
                        getActiveSessionFilter(Session.ACTION_ACTIVE_SESSION_OPENED));
                broadcastManager.registerReceiver(receiver1,
                        getActiveSessionFilter(Session.ACTION_ACTIVE_SESSION_OPENED));
                broadcastManager.registerReceiver(receiver1,
                        getActiveSessionFilter(Session.ACTION_ACTIVE_SESSION_OPENED));
            }
        };
        runOnBlockerThread(initialize1, true);

        receiver1.incrementExpectCount(3);
        receiver2.incrementExpectCount();
        Session.postActiveSessionAction(Session.ACTION_ACTIVE_SESSION_OPENED);
        receiver1.waitForExpectedCalls();
        receiver2.waitForExpectedCalls();

        receiver2.incrementExpectCount();
        Session.postActiveSessionAction(Session.ACTION_ACTIVE_SESSION_CLOSED);
        receiver2.waitForExpectedCalls();

        Session.postActiveSessionAction(Session.ACTION_ACTIVE_SESSION_SET);
        Session.postActiveSessionAction(Session.ACTION_ACTIVE_SESSION_UNSET);

        closeBlockerAndAssertSuccess();
    } finally {
        broadcastManager.unregisterReceiver(receiver0);
        broadcastManager.unregisterReceiver(receiver1);
        broadcastManager.unregisterReceiver(receiver2);
        Session.setActiveSession(null);
    }
}

From source file:org.torproject.android.OrbotMainActivity.java

/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mPrefs = TorServiceUtils.getSharedPrefs(getApplicationContext());

    /* Create the widgets before registering for broadcasts to guarantee
     * that the widgets exist when the status updates try to update them */
    doLayout();/*from w  w w  .  ja  v  a 2 s. co  m*/

    /* receive the internal status broadcasts, which are separate from the public
     * status broadcasts to prevent other apps from sending fake/wrong status
     * info to this app */
    LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
    lbm.registerReceiver(mLocalBroadcastReceiver, new IntentFilter(TorServiceConstants.ACTION_STATUS));
    lbm.registerReceiver(mLocalBroadcastReceiver, new IntentFilter(TorServiceConstants.LOCAL_ACTION_BANDWIDTH));
    lbm.registerReceiver(mLocalBroadcastReceiver, new IntentFilter(TorServiceConstants.LOCAL_ACTION_LOG));
}

From source file:com.tourmaline.example.activities.MainActivity.java

private void registerEngineAlerts() {
    final LocalBroadcastManager mgr = LocalBroadcastManager.getInstance(this);
    receiver = new BroadcastReceiver() {
        @Override/*from w w w  . java2 s.  c  o  m*/
        public void onReceive(Context context, Intent i) {
            int state = i.getIntExtra("state", Engine.INIT_SUCCESS);
            switch (state) {
            case Engine.GPS_ENABLED:
            case Engine.GPS_DISABLED:
            case Engine.LOCATION_PERMISSION_GRANTED:
            case Engine.LOCATION_PERMISSION_DENIED:
            case Engine.POWER_SAVE_MODE_DISABLED:
            case Engine.POWER_SAVE_MODE_ENABLED:
            case Engine.SDK_UP_TO_DATE:
            case Engine.SDK_UPDATE_AVAILABLE:
            case Engine.SDK_UPDATE_MANDATORY: {
                setAlerts();
                break;
            }
            default:
                break;
            }
            setAlerts();
        }
    };
    mgr.registerReceiver(receiver, new IntentFilter(Engine.ACTION_LIFECYCLE));
}

From source file:com.raspi.chatapp.ui.chatting.ChatFragment.java

@Override
public void onResume() {
    super.onResume();
    // start the different receiver and init the ui
    IntentFilter filter = new IntentFilter(Constants.MESSAGE_RECEIVED);
    filter.setPriority(1);/* w  ww .j  av a2  s  . c  om*/
    // messageReceiver. this is for reasons not on the localBroadcastManager...
    getContext().registerReceiver(messageReceiver, filter);
    LocalBroadcastManager LBmgr = LocalBroadcastManager.getInstance(getContext());
    // the reconnected receiver
    LBmgr.registerReceiver(reconnectedReceiver, new IntentFilter(Constants.RECONNECTED));
    // the presence changed receiver
    LBmgr.registerReceiver(presenceChangeReceiver, new IntentFilter(Constants.PRESENCE_CHANGED));
    // the messageStatus changed receiver
    LBmgr.registerReceiver(messageStatusChangedReceiver, new IntentFilter(Constants.MESSAGE_STATUS_CHANGED));
    uploadReceiver.register(getContext());
    // also init the ui
    if (init)
        initUI();
    init = false;
}

From source file:nodomain.freeyourgadget.gadgetbridge.service.devices.miband2.MiBand2Support.java

public MiBand2Support() {
    super(LOG);/*from   w  w  w.j  a va  2s .  c  o  m*/
    addSupportedService(GattService.UUID_SERVICE_GENERIC_ACCESS);
    addSupportedService(GattService.UUID_SERVICE_GENERIC_ATTRIBUTE);
    addSupportedService(GattService.UUID_SERVICE_HEART_RATE);
    addSupportedService(GattService.UUID_SERVICE_IMMEDIATE_ALERT);
    addSupportedService(GattService.UUID_SERVICE_DEVICE_INFORMATION);
    addSupportedService(GattService.UUID_SERVICE_ALERT_NOTIFICATION);

    addSupportedService(MiBandService.UUID_SERVICE_MIBAND_SERVICE);
    addSupportedService(MiBandService.UUID_SERVICE_MIBAND2_SERVICE);
    addSupportedService(MiBand2Service.UUID_SERVICE_FIRMWARE_SERVICE);

    deviceInfoProfile = new DeviceInfoProfile<>(this);
    addSupportedProfile(deviceInfoProfile);
    heartRateProfile = new HeartRateProfile<>(this);
    addSupportedProfile(heartRateProfile);

    LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(getContext());
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(DeviceInfoProfile.ACTION_DEVICE_INFO);
    intentFilter.addAction(DeviceService.ACTION_MIBAND2_AUTH);
    broadcastManager.registerReceiver(mReceiver, intentFilter);
}

From source file:no.nordicsemi.android.nrftoolbox.dfu.DfuService.java

@Override
public void onCreate() {
    super.onCreate();

    final LocalBroadcastManager manager = LocalBroadcastManager.getInstance(this);
    manager.registerReceiver(mDfuActionReceiver, makeDfuActionIntentFilter());
}

From source file:org.cm.podd.report.activity.ReportActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(this);
    broadcastManager.registerReceiver(mAlertReceiver, new IntentFilter(FollowAlertService.TAG));

    broadcastManager.registerReceiver(new BroadcastReceiver() {
        @Override/*from   w ww.j a  v  a 2  s  .  c  o  m*/
        public void onReceive(Context context, Intent intent) {
            long administrationAreaId = intent.getLongExtra("administrationAreaId", -99);
            setRegionId(administrationAreaId);
        }
    }, new IntentFilter(SyncAdministrationAreaService.TAG));

    sharedPrefUtil = new SharedPrefUtil(this);

    setContentView(R.layout.activity_report);

    Toolbar myToolbar = findViewById(R.id.report_toolbar);
    setSupportActionBar(myToolbar);

    long areaId = sharedPrefUtil.getDefaultAdministrationAreaId();
    if (areaId != -99) {
        setRegionId(areaId);
    }

    formView = findViewById(R.id.form);
    locationView = findViewById(R.id.location);

    textProgressLocationView = findViewById(R.id.progress_location_text);
    textProgressLocationView.setTypeface(StyleUtil.getDefaultTypeface(getAssets(), Typeface.NORMAL));
    countdownTextView = findViewById(R.id.countdownTextView);
    countdownTextView.setTypeface(StyleUtil.getDefaultTypeface(getAssets(), Typeface.NORMAL));
    refreshLocationButton = findViewById(R.id.refresh_location_button);
    refreshLocationButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            requestGPSLocation();
            startLocationSearchTimeoutCountdown();
        }
    });
    progressBar = findViewById(R.id.progressBar);

    prevBtn = findViewById(R.id.prevBtn);
    nextBtn = findViewById(R.id.nextBtn);
    nextBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            nextScreen();
        }
    });
    nextBtn.setTypeface(StyleUtil.getDefaultTypeface(getAssets(), Typeface.NORMAL));
    prevBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            onBackPressed();
        }
    });
    prevBtn.setTypeface(StyleUtil.getDefaultTypeface(getAssets(), Typeface.NORMAL));

    disableMaskView = findViewById(R.id.disableMask);

    reportDataSource = new ReportDataSource(this);
    reportTypeDataSource = new ReportTypeDataSource(this);
    reportQueueDataSource = new ReportQueueDataSource(this);

    recordSpecDataSource = RecordSpecDataSource.Companion.getInstance(this);
    followAlertDataSource = new FollowAlertDataSource(this);

    if (savedInstanceState != null) {
        currentFragment = savedInstanceState.getString("currentFragment");
        reportId = savedInstanceState.getLong("reportId");
        reportType = savedInstanceState.getLong("reportType");
        follow = savedInstanceState.getBoolean("follow");
        testReport = savedInstanceState.getBoolean("testReport");
        formIterator = (FormIterator) savedInstanceState.getSerializable("formIterator");
        if (formIterator != null) {
            trigger = formIterator.getForm().getTrigger();
        }
        reportSubmit = savedInstanceState.getInt("reportSubmit");
        followActionName = savedInstanceState.getString("followActionName");
        Log.d(TAG, "onCreate from savedInstance, testFlag = " + testReport);

        currentLatitude = savedInstanceState.getDouble("currentLatitude");
        currentLongitude = savedInstanceState.getDouble("currentLongitude");
        recordSpec = (RecordSpec) savedInstanceState.get("recordSpec");
        parentReportGuid = savedInstanceState.getString("parentReportGuid");
    } else {
        Intent intent = getIntent();
        String action = intent.getAction();
        int startPageId = -1;
        switch (action) {
        case ACTION_NEW_REPORT:
            reportType = intent.getLongExtra("reportType", 0);
            testReport = intent.getBooleanExtra("test", false);
            reportId = reportDataSource.createDraftReport(reportType, testReport);
            follow = false;
            break;
        case FollowAlertService.ORG_CM_PODD_REPORT_FOLLOW:
            reportType = intent.getLongExtra("reportType", 0);
            testReport = false;
            reportId = intent.getLongExtra("reportId", -99);
            follow = intent.getBooleanExtra("follow", false);
            break;
        case ACTION_FOR_EDIT_OR_VIEW:
            reportType = intent.getLongExtra("reportType", 0);
            testReport = intent.getBooleanExtra("test", false);
            reportId = intent.getLongExtra("reportId", -99);
            break;
        case ACTION_CREATE_FOLLOW_REPORT:
            reportType = intent.getLongExtra("reportType", 0);
            parentReportId = intent.getLongExtra("reportId", -99);
            reportId = reportDataSource.createFollowReport(parentReportId);
            follow = true;
            followActionName = "follow";
            break;
        case ACTION_CREATE_FOLLOW_REPORT_WITH_ACTION:
            reportType = intent.getLongExtra("reportType", 0);
            parentReportId = intent.getLongExtra("reportId", -99);
            reportId = reportDataSource.createFollowReport(parentReportId);
            follow = true;
            followActionName = intent.getStringExtra("followActionName");
            startPageId = intent.getIntExtra("startPageId", -1);
            break;
        case ACTION_CREATE_FOLLOW_REPORT_FROM_RECORD:
            reportType = intent.getLongExtra("reportType", 0);
            parentReportGuid = intent.getStringExtra("parentReportGuid");
            String preloadFormData = intent.getStringExtra("preloadFormData");
            reportId = reportDataSource.createFollowReport(reportType, parentReportGuid, preloadFormData);
            follow = true;
            break;

        }

        Form form = reportTypeDataSource.getForm(reportType);
        trigger = form.getTrigger();
        if (trigger != null) {
            Log.d(TAG, String.format(
                    "This report type contain a trigger with pattern:%s, pageId:%d, notificationText:%s",
                    trigger.getPattern(), trigger.getPageId(), trigger.getNotificationText()));
        }
        if (intent.getAction() != null
                && intent.getAction().equals(FollowAlertService.ORG_CM_PODD_REPORT_FOLLOW)) {
            form.setStartWithTrigger(true);
        }

        if (startPageId != -1) {
            form.setStartPageId(startPageId);
        }

        formIterator = new FormIterator(form);
        Report report = loadFormData(form);
        recordSpec = recordSpecDataSource.getByReportTypeId(report.getType());

        nextScreen();
    }

    if (recordSpec != null) {
        final FirebaseContext firebaseContext = FirebaseContext.Companion
                .getInstance(PreferenceContext.Companion.getInstance(getApplicationContext()));
        firebaseContext.auth(this, new Function1<Boolean, Unit>() {
            @Override
            public Unit invoke(Boolean success) {
                if (success) {
                    recordDataSource = firebaseContext.recordDataSource(recordSpec, parentReportGuid);
                }
                return null;
            }
        });
    }

    // open location service only when
    // 1. Create a New report
    // 2. Edit a draft report which don't have any location attach.
    if ((reportSubmit == 0) && (currentLatitude == 0.00)) {
        buildGoogleApiClient();
        if (formIterator.getForm().isForceLocation()) {
            switchToProgressLocationMode();
        }
    }

    /* check softkeyboard visibility */
    final View rootView = getWindow().getDecorView().findViewById(android.R.id.content);
    rootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            // different devices' screens have normal height diff differently
            // eg, roughly 5.5" xxhdpi has 220px, 4.5" xhdpi has 110px, 4", 3.5" hdpi has 75px
            int heightDiff = rootView.getRootView().getHeight() - rootView.getHeight();
            int limitHeightPx = (int) (getResources().getDisplayMetrics().density * 100);
            Log.d(TAG, String.format("diff height=%d, limit height=%d", heightDiff, limitHeightPx));
        }
    });

    Tracker tracker = ((PoddApplication) getApplication()).getTracker(PoddApplication.TrackerName.APP_TRACKER);
    tracker.setScreenName("Report-" + reportType);
    tracker.send(new HitBuilders.AppViewBuilder().build());

    startTime = System.currentTimeMillis();
}

From source file:com.raspi.chatapp.ui.chatting.ChatFragment.java

@Override
public void onPause() {
    // unregister the different reciever (see onResume)
    InputMethodManager mgr = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
    mgr.hideSoftInputFromWindow(getView().findViewById(R.id.chat_in).getWindowToken(), 0);
    getContext().unregisterReceiver(messageReceiver);
    LocalBroadcastManager LBmgr = LocalBroadcastManager.getInstance(getContext());
    LBmgr.unregisterReceiver(presenceChangeReceiver);
    LBmgr.unregisterReceiver(reconnectedReceiver);
    LBmgr.registerReceiver(messageStatusChangedReceiver, new IntentFilter(Constants.MESSAGE_STATUS_CHANGED));
    uploadReceiver.unregister(getContext());
    super.onPause();
}

From source file:com.wanikani.androidnotifier.MainActivity.java

/**
 * Registers the intent listeners./*w  ww  .jav a  2 s .  c  o m*/
 * Currently the intents we listen to are:
 * <ul>
 *    <li>{@link SettingsActivity#ACT_CREDENTIALS}, when the credentials are changed
 *  <li>{@link SettingsActivity#ACT_NOTIFY}, when notifications are enabled or disabled
 *  <li>{@link #ACTION_REFRESH}, when the dashboard should refreshed
 * </ul>
 * Both intents are triggered by {@link SettingsActivity}
 */
private void registerIntents() {
    IntentFilter filter;
    LocalBroadcastManager lbm;

    lbm = LocalBroadcastManager.getInstance(this);

    filter = new IntentFilter(SettingsActivity.ACT_CREDENTIALS);
    filter.addAction(SettingsActivity.ACT_NOTIFY);
    filter.addAction(ACTION_REFRESH);
    filter.addAction(ACTION_CLEAR);
    lbm.registerReceiver(receiver, filter);

    filter = new IntentFilter(ACTION_REFRESH);
    registerReceiver(receiver, filter);
}