List of usage examples for android.support.v4.content LocalBroadcastManager unregisterReceiver
public void unregisterReceiver(BroadcastReceiver receiver)
From source file:com.facebook.appevents.AppEventsLoggerTests.java
public void testSimpleCall() throws InterruptedException { AppEventsLogger.setFlushBehavior(AppEventsLogger.FlushBehavior.EXPLICIT_ONLY); AccessToken accessToken1 = getAccessTokenForSharedUser(); AccessToken accessToken2 = getAccessTokenForSharedUser(SECOND_TEST_USER_TAG); AppEventsLogger logger1 = AppEventsLogger.newLogger(getActivity(), accessToken1); AppEventsLogger logger2 = AppEventsLogger.newLogger(getActivity(), accessToken2); final WaitForBroadcastReceiver waitForBroadcastReceiver = new WaitForBroadcastReceiver(); waitForBroadcastReceiver.incrementExpectCount(); final LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(getActivity()); try {/*from w w w . ja v a 2 s .co m*/ // Need to get notifications on another thread so we can wait for them. runOnBlockerThread(new Runnable() { @Override public void run() { broadcastManager.registerReceiver(waitForBroadcastReceiver, new IntentFilter(AppEventsLogger.ACTION_APP_EVENTS_FLUSHED)); } }, true); logger1.logEvent("an_event"); logger2.logEvent("another_event"); // test illegal event name and event key, should not crash in non-debug environment. logger1.logEvent("$illegal_event_name"); Bundle params = new Bundle(); params.putString("illegal%key", "good_value"); logger1.logEvent("legal_event_name", params); char[] val = { 'b', 'a', 'd' }; params.putCharArray("legal_key", val); logger1.logEvent("legal_event", params); logger1.flush(); waitForBroadcastReceiver.waitForExpectedCalls(); closeBlockerAndAssertSuccess(); } finally { broadcastManager.unregisterReceiver(waitForBroadcastReceiver); } }
From source file:com.wanikani.androidnotifier.MainActivity.java
/** * Unregister the intent listeners that were registered by {@link #registerIntent}. */// w w w . j a v a 2 s. c om private void unregisterIntents() { LocalBroadcastManager lbm; lbm = LocalBroadcastManager.getInstance(this); lbm.unregisterReceiver(receiver); unregisterReceiver(receiver); }
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:no.nordicsemi.android.nrftoolbox.dfu.DfuService.java
@Override public void onDestroy() { super.onDestroy(); final LocalBroadcastManager manager = LocalBroadcastManager.getInstance(this); manager.unregisterReceiver(mDfuActionReceiver); }
From source file:com.ubuntuone.android.files.activity.FilesActivity.java
@Override public void onDestroy() { LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this); lbm.unregisterReceiver(mSignOutReceiver); if (mTracker != null) { mTracker.dispatch();/* ww w.j a va2 s . c om*/ mTracker.stop(); } super.onDestroy(); }
From source file:com.facebook.AppEventsLoggerTests.java
public void testPersistedEvents() throws IOException, ClassNotFoundException { AppEventsLogger.setFlushBehavior(AppEventsLogger.FlushBehavior.EXPLICIT_ONLY); final WaitForBroadcastReceiver waitForBroadcastReceiver = new WaitForBroadcastReceiver(); final LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(getActivity()); // Need to get notifications on another thread so we can wait for them. runOnBlockerThread(new Runnable() { @Override//from w w w. ja v a 2s. c o m public void run() { broadcastManager.registerReceiver(waitForBroadcastReceiver, new IntentFilter(AppEventsLogger.ACTION_APP_EVENTS_FLUSHED)); } }, true); getActivity().getFileStreamPath(AppEventsLogger.PersistedEvents.PERSISTED_EVENTS_FILENAME).delete(); TestSession session1 = TestSession.createSessionWithSharedUser(getActivity(), null); AppEventsLogger logger1 = AppEventsLogger.newLogger(getActivity(), session1); logger1.logEvent("an_event"); AppEventsLogger.onContextStop(); FileInputStream fis = getActivity() .openFileInput(AppEventsLogger.PersistedEvents.PERSISTED_EVENTS_FILENAME); assertNotNull(fis); ObjectInputStream ois = new ObjectInputStream(fis); Object obj = ois.readObject(); ois.close(); assertTrue(obj instanceof HashMap); logger1.flush(); logger1.logEvent("another_event"); waitForBroadcastReceiver.incrementExpectCount(); logger1.flush(); waitForBroadcastReceiver.waitForExpectedCalls(); List<Intent> receivedIntents = waitForBroadcastReceiver.getReceivedIntents(); assertEquals(1, receivedIntents.size()); Intent intent = receivedIntents.get(0); assertNotNull(intent); assertEquals(2, intent.getIntExtra(AppEventsLogger.APP_EVENTS_EXTRA_NUM_EVENTS_FLUSHED, 0)); broadcastManager.unregisterReceiver(waitForBroadcastReceiver); }
From source file:org.kontalk.sync.Syncer.java
/** * The actual sync procedure.//from w w w. java 2 s .c o m * This one uses the slowest method ever: it first checks for every phone * number in all contacts and it sends them to the server. Once a response * is received, it deletes all the raw contacts created by us and then * recreates only the ones the server has found a match for. */ public void performSync(Context context, Account account, String authority, ContentProviderClient provider, ContentProviderClient usersProvider, SyncResult syncResult) throws OperationCanceledException { final Map<String, RawPhoneNumberEntry> lookupNumbers = new HashMap<>(); final List<String> jidList = new ArrayList<>(); // resync users database Log.v(TAG, "resyncing users database"); Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); // update users database Uri uri = Users.CONTENT_URI.buildUpon().appendQueryParameter(Users.RESYNC, "true").build(); try { int count = usersProvider.update(uri, new ContentValues(), null, null); Log.d(TAG, "users database resynced (" + count + ")"); } catch (Exception e) { Log.e(TAG, "error resyncing users database - aborting sync", e); syncResult.databaseError = true; return; } // query all contacts Cursor cursor; try { cursor = usersProvider.query(Users.CONTENT_URI_OFFLINE, new String[] { Users.JID, Users.NUMBER, Users.LOOKUP_KEY }, null, null, null); } catch (Exception e) { Log.e(TAG, "error querying users database - aborting sync", e); syncResult.databaseError = true; return; } while (cursor.moveToNext()) { if (mCanceled) { cursor.close(); throw new OperationCanceledException(); } String jid = cursor.getString(0); String number = cursor.getString(1); String lookupKey = cursor.getString(2); // avoid to send duplicates to the server if (lookupNumbers.put(XmppStringUtils.parseLocalpart(jid), new RawPhoneNumberEntry(lookupKey, number, jid)) == null) jidList.add(jid); } cursor.close(); if (mCanceled) throw new OperationCanceledException(); // empty contacts :-| if (jidList.size() == 0) { // delete all Kontalk raw contacts try { syncResult.stats.numDeletes += deleteAll(account, provider); } catch (Exception e) { Log.e(TAG, "contact delete error", e); syncResult.databaseError = true; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { try { syncResult.stats.numDeletes += deleteProfile(account, provider); } catch (Exception e) { Log.e(TAG, "profile delete error", e); syncResult.databaseError = true; } } commit(usersProvider, syncResult); } else { final LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(mContext); // register presence broadcast receiver PresenceBroadcastReceiver receiver = new PresenceBroadcastReceiver(jidList, this); IntentFilter f = new IntentFilter(); f.addAction(MessageCenterService.ACTION_PRESENCE); f.addAction(MessageCenterService.ACTION_ROSTER_MATCH); f.addAction(MessageCenterService.ACTION_PUBLICKEY); f.addAction(MessageCenterService.ACTION_BLOCKLIST); f.addAction(MessageCenterService.ACTION_LAST_ACTIVITY); f.addAction(MessageCenterService.ACTION_CONNECTED); lbm.registerReceiver(receiver, f); // request current connection status MessageCenterService.requestConnectionStatus(mContext); // wait for the service to complete its job synchronized (this) { // wait for connection try { wait(MAX_WAIT_TIME); } catch (InterruptedException e) { // simulate canceled operation mCanceled = true; } } lbm.unregisterReceiver(receiver); // last chance to quit if (mCanceled) throw new OperationCanceledException(); List<PresenceItem> res = receiver.getResponse(); if (res != null) { ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>(); // TODO operations.size() could be used instead (?) int op = 0; // this is the time - delete all Kontalk raw contacts try { syncResult.stats.numDeletes += deleteAll(account, provider); } catch (Exception e) { Log.e(TAG, "contact delete error", e); syncResult.databaseError = true; return; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { try { syncResult.stats.numDeletes += deleteProfile(account, provider); } catch (Exception e) { Log.e(TAG, "profile delete error", e); syncResult.databaseError = true; } } ContentValues registeredValues = new ContentValues(); registeredValues.put(Users.REGISTERED, 1); for (int i = 0; i < res.size(); i++) { PresenceItem entry = res.get(i); if (entry.discarded) continue; final RawPhoneNumberEntry data = lookupNumbers.get(XmppStringUtils.parseLocalpart(entry.from)); if (data != null && data.lookupKey != null) { // add contact addContact(account, getDisplayName(provider, data.lookupKey, data.number), data.number, data.jid, operations, op++); } else { syncResult.stats.numSkippedEntries++; } // update fields try { String status = entry.status; if (!TextUtils.isEmpty(status)) registeredValues.put(Users.STATUS, status); else registeredValues.putNull(Users.STATUS); if (entry.timestamp >= 0) registeredValues.put(Users.LAST_SEEN, entry.timestamp); else registeredValues.putNull(Users.LAST_SEEN); if (entry.publicKey != null) { try { PGPPublicKey pubKey = PGP.getMasterKey(entry.publicKey); // trust our own key blindly int trustLevel = Authenticator.isSelfJID(mContext, entry.from) ? MyUsers.Keys.TRUST_VERIFIED : -1; // update keys table immediately Keyring.setKey(mContext, entry.from, entry.publicKey, trustLevel); // no data from system contacts, use name from public key if (data == null) { PGPUserID uid = PGP.parseUserId(pubKey, XmppStringUtils.parseDomain(entry.from)); if (uid != null) { registeredValues.put(Users.DISPLAY_NAME, uid.getName()); } } } catch (Exception e) { Log.w(TAG, "unable to parse public key", e); } } else { // use roster name if no contact data available if (data == null && entry.rosterName != null) { registeredValues.put(Users.DISPLAY_NAME, entry.rosterName); } } // blocked status registeredValues.put(Users.BLOCKED, entry.blocked); // user JID as reported by the server registeredValues.put(Users.JID, entry.from); /* * Since UsersProvider.resync inserted the user row * using our server name, it might have changed because * of what the server reported. We already put into the * values the new JID, but we need to use the old one * in the where condition so we will have a match. */ String origJid; if (data != null) origJid = XMPPUtils.createLocalJID(mContext, XmppStringUtils.parseLocalpart(entry.from)); else origJid = entry.from; usersProvider.update(Users.CONTENT_URI_OFFLINE, registeredValues, Users.JID + " = ?", new String[] { origJid }); // clear data registeredValues.remove(Users.DISPLAY_NAME); // if this is our own contact, trust our own key later if (Authenticator.isSelfJID(mContext, entry.from)) { // register our profile while we're at it if (data != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { // add contact addProfile(account, Authenticator.getDefaultDisplayName(mContext), data.number, data.jid, operations, op++); } } } catch (Exception e) { Log.e(TAG, "error updating users database", e); // we shall continue here... } } try { if (operations.size() > 0) provider.applyBatch(operations); syncResult.stats.numInserts += op; syncResult.stats.numEntries += op; } catch (Exception e) { Log.w(TAG, "contact write error", e); syncResult.stats.numSkippedEntries += op; /* * We do not consider system contacts failure a fatal error. * This is actually a workaround for systems with disabled permissions or * exotic firmwares. It can also protect against security 3rd party apps or * non-Android platforms, such as Jolla/Alien Dalvik. */ } commit(usersProvider, syncResult); } // timeout or error else { Log.w(TAG, "connection timeout - aborting sync"); syncResult.stats.numIoExceptions++; } } }
From source file:com.facebook.SessionTests.java
@SmallTest @MediumTest// w ww . j a va 2 s . c om @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:com.facebook.SessionTests.java
@SmallTest @MediumTest/* w w w . j a va2 s . c o m*/ @LargeTest public void testSetActiveSession() { Session.setActiveSession(null); final WaitForBroadcastReceiver receiverOpened = new WaitForBroadcastReceiver(); final WaitForBroadcastReceiver receiverClosed = new WaitForBroadcastReceiver(); final WaitForBroadcastReceiver receiverSet = new WaitForBroadcastReceiver(); final WaitForBroadcastReceiver receiverUnset = new WaitForBroadcastReceiver(); final LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(getActivity()); try { Runnable initializeOnBlockerThread = new Runnable() { @Override public void run() { broadcastManager.registerReceiver(receiverOpened, getActiveSessionFilter(Session.ACTION_ACTIVE_SESSION_OPENED)); broadcastManager.registerReceiver(receiverClosed, getActiveSessionFilter(Session.ACTION_ACTIVE_SESSION_CLOSED)); broadcastManager.registerReceiver(receiverSet, getActiveSessionFilter(Session.ACTION_ACTIVE_SESSION_SET)); broadcastManager.registerReceiver(receiverUnset, getActiveSessionFilter(Session.ACTION_ACTIVE_SESSION_UNSET)); } }; runOnBlockerThread(initializeOnBlockerThread, true); // null -> null should not fire events assertEquals(null, Session.getActiveSession()); Session.setActiveSession(null); assertEquals(null, Session.getActiveSession()); Session session0 = new Session.Builder(getActivity()).setApplicationId("FakeAppId") .setTokenCachingStrategy(new MockTokenCachingStrategy()).build(); assertEquals(SessionState.CREATED_TOKEN_LOADED, session0.getState()); // For unopened session, we should only see the Set event. receiverSet.incrementExpectCount(); Session.setActiveSession(session0); assertEquals(session0, Session.getActiveSession()); receiverSet.waitForExpectedCalls(); // When we open it, then we should see the Opened event. receiverOpened.incrementExpectCount(); session0.openForRead(null); receiverOpened.waitForExpectedCalls(); // Setting to itself should not fire events Session.setActiveSession(session0); assertEquals(session0, Session.getActiveSession()); // Setting from one opened session to another should deliver a full // cycle of events WaitForBroadcastReceiver.incrementExpectCounts(receiverClosed, receiverUnset, receiverSet, receiverOpened); Session session1 = new Session.Builder(getActivity()).setApplicationId("FakeAppId") .setTokenCachingStrategy(new MockTokenCachingStrategy()).build(); assertEquals(SessionState.CREATED_TOKEN_LOADED, session1.getState()); session1.openForRead(null); assertEquals(SessionState.OPENED, session1.getState()); Session.setActiveSession(session1); WaitForBroadcastReceiver.waitForExpectedCalls(receiverClosed, receiverUnset, receiverSet, receiverOpened); assertEquals(SessionState.CLOSED, session0.getState()); assertEquals(session1, Session.getActiveSession()); closeBlockerAndAssertSuccess(); } finally { broadcastManager.unregisterReceiver(receiverOpened); broadcastManager.unregisterReceiver(receiverClosed); broadcastManager.unregisterReceiver(receiverSet); broadcastManager.unregisterReceiver(receiverUnset); Session.setActiveSession(null); } }