Java Code Examples for android.content.BroadcastReceiver#onReceive()

The following examples show how to use android.content.BroadcastReceiver#onReceive() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BluetoothPeripheralTest.java    From blessed-android with MIT License 6 votes vote down vote up
@Test
public void queueTestRetryCommand() throws Exception {
    BluetoothGattCallback callback = connectAndGetCallback();
    callback.onConnectionStateChange(gatt, GATT_SUCCESS, STATE_CONNECTED);

    BluetoothGattService service = new BluetoothGattService(SERVICE_UUID, 0);
    BluetoothGattCharacteristic characteristic = new BluetoothGattCharacteristic(UUID.fromString("00002A1C-0000-1000-8000-00805f9b34fb"),PROPERTY_READ,0);
    BluetoothGattCharacteristic characteristic2 = new BluetoothGattCharacteristic(UUID.fromString("00002A1E-0000-1000-8000-00805f9b34fb"),PROPERTY_READ,0);
    service.addCharacteristic(characteristic);
    service.addCharacteristic(characteristic2);
    when(gatt.readCharacteristic(characteristic)).thenReturn(true);
    when(gatt.getServices()).thenReturn(Arrays.asList(service));

    peripheral.readCharacteristic(characteristic);

    verify(gatt).readCharacteristic(characteristic);

    // Trigger bonding to start
    callback.onCharacteristicRead(gatt, characteristic, 5);

    Field field = BluetoothPeripheral.class.getDeclaredField("bondStateReceiver");
    field.setAccessible(true);
    BroadcastReceiver broadcastReceiver = (BroadcastReceiver) field.get(peripheral);

    Intent intent = mock(Intent.class);
    when(intent.getAction()).thenReturn(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
    when(intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR)).thenReturn(BOND_BONDED);
    when(intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)).thenReturn(device);

    broadcastReceiver.onReceive(context, intent);

    ShadowLooper.runUiThreadTasksIncludingDelayedTasks();

    verify(gatt, times(2)).readCharacteristic(characteristic);
}
 
Example 2
Source File: BluetoothPeripheralTest.java    From blessed-android with MIT License 6 votes vote down vote up
@Test
public void onBondStateChangedBonded() throws Exception {
    connectAndGetCallback();

    Field field = BluetoothPeripheral.class.getDeclaredField("bondStateReceiver");
    field.setAccessible(true);
    BroadcastReceiver broadcastReceiver = (BroadcastReceiver) field.get(peripheral);

    Intent intent = mock(Intent.class);
    when(intent.getAction()).thenReturn(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
    when(intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR)).thenReturn(BOND_BONDED);
    when(intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)).thenReturn(device);

    broadcastReceiver.onReceive(context, intent);

    verify(gatt).discoverServices();
}
 
Example 3
Source File: BluetoothPeripheralTest.java    From blessed-android with MIT License 6 votes vote down vote up
@Test
public void onBondStateChangedNone() throws Exception {
    connectAndGetCallback();

    Field field = BluetoothPeripheral.class.getDeclaredField("bondStateReceiver");
    field.setAccessible(true);
    BroadcastReceiver broadcastReceiver = (BroadcastReceiver) field.get(peripheral);

    Intent intent = mock(Intent.class);
    when(intent.getAction()).thenReturn(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
    when(intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR)).thenReturn(BluetoothDevice.BOND_NONE);
    when(intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)).thenReturn(device);

    broadcastReceiver.onReceive(context, intent);

    verify(gatt).disconnect();
}
 
Example 4
Source File: VClientImpl.java    From container with GNU General Public License v3.0 6 votes vote down vote up
private void handleReceiver(ReceiverData data) {
    BroadcastReceiver.PendingResult result = data.resultData.build();
    try {
        Context context = createPackageContext(data.component.getPackageName());
        Context receiverContext = ContextImpl.getReceiverRestrictedContext.call(context);
        String className = data.component.getClassName();
        BroadcastReceiver receiver = (BroadcastReceiver) context.getClassLoader().loadClass(className).newInstance();
        mirror.android.content.BroadcastReceiver.setPendingResult.call(receiver, result);
        data.intent.setExtrasClassLoader(context.getClassLoader());
        receiver.onReceive(receiverContext, data.intent);
        if (mirror.android.content.BroadcastReceiver.getPendingResult.call(receiver) != null) {
            result.finish();
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(
                "Unable to start receiver " + data.component
                        + ": " + e.toString(), e);
    }
    VActivityManager.get().broadcastFinish(data.resultData);
}
 
Example 5
Source File: LaunchAnalyzerReceiverTest.java    From analyzer-of-android-for-Apache-Weex with Apache License 2.0 6 votes vote down vote up
@Test
public void onReceive() throws Exception {

    //one
    ShadowApplication application = ShadowApplication.getInstance();
    Intent intent = new Intent(ACTION);
    boolean result = application.hasReceiverForIntent(intent);
    assertTrue(result);

    //only one
    List<BroadcastReceiver> receivers = application.getReceiversForIntent(intent);
    assertEquals(1,receivers.size());

    //test onReceive
    intent.putExtra("c","off");
    BroadcastReceiver targetReceiver = receivers.get(0);
    targetReceiver.onReceive(application.getApplicationContext(),intent);

    Intent serviceIntent = application.getNextStoppedService();
    assertEquals(serviceIntent.getComponent().getClassName(),AnalyzerService.class.getCanonicalName());
}
 
Example 6
Source File: GaService.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
public void onBound(final Context ctx) {
    // Update our state when network connectivity changes.
    final BroadcastReceiver netConnectivityReceiver = new BroadcastReceiver() {
        public void onReceive(final Context context, final Intent intent) {
            onNetConnectivityChanged();
        }
    };
    ctx.registerReceiver(netConnectivityReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    // Fire a fake connectivity change to kick start the state machine
    netConnectivityReceiver.onReceive(null, null);
}
 
Example 7
Source File: GaService.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
public void onBound(final GreenAddressApplication app) {
    // Update our state when network connectivity changes.
    mNetConnectivityReceiver = new BroadcastReceiver() {
        public void onReceive(final Context context, final Intent intent) {
            onNetConnectivityChanged();
        }
    };
    app.registerReceiver(mNetConnectivityReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    // Fire a fake connectivity change to kick start the state machine
    mNetConnectivityReceiver.onReceive(null, null);
}
 
Example 8
Source File: InstallReferrerReceiver.java    From tlplib with MIT License 5 votes vote down vote up
private void broadcastEvent(Context context, Intent intent) {
    List<BroadcastReceiver> proxyClasses = getBroadcastReceivers(context, "TLPLibInstallReferrerReceiver");

    for (BroadcastReceiver r : proxyClasses) {
        try {
            r.onReceive(context, intent);
            Log.i(TAG, "Called onReceive on: " + r.getClass().getName());
        }
        catch (Exception e) {
            Log.e(TAG, "Exception calling onReceive: " + e.getMessage());
        }
    }
}
 
Example 9
Source File: LoadedApk.java    From AndroidComponentPlugin with Apache License 2.0 4 votes vote down vote up
public final Runnable getRunnable() {
    return () -> {
        final BroadcastReceiver receiver = mReceiver;
        final boolean ordered = mOrdered;

        if (ActivityThread.DEBUG_BROADCAST) {
            int seq = mCurIntent.getIntExtra("seq", -1);
            Slog.i(ActivityThread.TAG, "Dispatching broadcast " + mCurIntent.getAction()
                    + " seq=" + seq + " to " + mReceiver);
            Slog.i(ActivityThread.TAG, "  mRegistered=" + mRegistered
                    + " mOrderedHint=" + ordered);
        }

        final IActivityManager mgr = ActivityManager.getService();
        final Intent intent = mCurIntent;
        if (intent == null) {
            Log.wtf(TAG, "Null intent being dispatched, mDispatched=" + mDispatched
                    + ": run() previously called at "
                    + Log.getStackTraceString(mPreviousRunStacktrace));
        }

        mCurIntent = null;
        mDispatched = true;
        mPreviousRunStacktrace = new Throwable("Previous stacktrace");
        if (receiver == null || intent == null || mForgotten) {
            if (mRegistered && ordered) {
                if (ActivityThread.DEBUG_BROADCAST) Slog.i(ActivityThread.TAG,
                        "Finishing null broadcast to " + mReceiver);
                sendFinished(mgr);
            }
            return;
        }

        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "broadcastReceiveReg");
        try {
            ClassLoader cl = mReceiver.getClass().getClassLoader();
            intent.setExtrasClassLoader(cl);
            intent.prepareToEnterProcess();
            setExtrasClassLoader(cl);
            receiver.setPendingResult(this);
            receiver.onReceive(mContext, intent);
        } catch (Exception e) {
            if (mRegistered && ordered) {
                if (ActivityThread.DEBUG_BROADCAST) Slog.i(ActivityThread.TAG,
                        "Finishing failed broadcast to " + mReceiver);
                sendFinished(mgr);
            }
            if (mInstrumentation == null ||
                    !mInstrumentation.onException(mReceiver, e)) {
                Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                throw new RuntimeException(
                        "Error receiving broadcast " + intent
                                + " in " + mReceiver, e);
            }
        }

        if (receiver.getPendingResult() != null) {
            finish();
        }
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
    };
}
 
Example 10
Source File: LoadedApk.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
public final Runnable getRunnable() {
    return () -> {
        final BroadcastReceiver receiver = mReceiver;
        final boolean ordered = mOrdered;

        if (ActivityThread.DEBUG_BROADCAST) {
            int seq = mCurIntent.getIntExtra("seq", -1);
            Slog.i(ActivityThread.TAG, "Dispatching broadcast " + mCurIntent.getAction()
                    + " seq=" + seq + " to " + mReceiver);
            Slog.i(ActivityThread.TAG, "  mRegistered=" + mRegistered
                    + " mOrderedHint=" + ordered);
        }

        final IActivityManager mgr = ActivityManager.getService();
        final Intent intent = mCurIntent;
        if (intent == null) {
            Log.wtf(TAG, "Null intent being dispatched, mDispatched=" + mDispatched
                    + ": run() previously called at "
                    + Log.getStackTraceString(mPreviousRunStacktrace));
        }

        mCurIntent = null;
        mDispatched = true;
        mPreviousRunStacktrace = new Throwable("Previous stacktrace");
        if (receiver == null || intent == null || mForgotten) {
            if (mRegistered && ordered) {
                if (ActivityThread.DEBUG_BROADCAST) Slog.i(ActivityThread.TAG,
                        "Finishing null broadcast to " + mReceiver);
                sendFinished(mgr);
            }
            return;
        }

        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "broadcastReceiveReg");
        try {
            ClassLoader cl = mReceiver.getClass().getClassLoader();
            intent.setExtrasClassLoader(cl);
            intent.prepareToEnterProcess();
            setExtrasClassLoader(cl);
            receiver.setPendingResult(this);
            receiver.onReceive(mContext, intent);
        } catch (Exception e) {
            if (mRegistered && ordered) {
                if (ActivityThread.DEBUG_BROADCAST) Slog.i(ActivityThread.TAG,
                        "Finishing failed broadcast to " + mReceiver);
                sendFinished(mgr);
            }
            if (mInstrumentation == null ||
                    !mInstrumentation.onException(mReceiver, e)) {
                Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                throw new RuntimeException(
                        "Error receiving broadcast " + intent
                                + " in " + mReceiver, e);
            }
        }

        if (receiver.getPendingResult() != null) {
            finish();
        }
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
    };
}
 
Example 11
Source File: CondomCore.java    From condom with Apache License 2.0 4 votes vote down vote up
void proceedBroadcast(final Context context, final Intent intent, final WrappedValueProcedure<Boolean> procedure,
					  final @Nullable BroadcastReceiver resultReceiver) {
	if (proceed(OutboundType.BROADCAST, intent, Boolean.FALSE, procedure) == Boolean.FALSE && resultReceiver != null)
		resultReceiver.onReceive(new ReceiverRestrictedContext(context), intent);
}
 
Example 12
Source File: DeviceBatteryMetricsCollectorTest.java    From Battery-Metrics with MIT License 4 votes vote down vote up
@Test
public void testSnapshotAfterValidBroadcasts() {
  // Set up the collector
  ShadowSystemClock.setElapsedRealtime(5000);
  when(mContext.registerReceiver(
          Matchers.isNull(BroadcastReceiver.class), Matchers.any(IntentFilter.class)))
      .thenReturn(createBatteryIntent(BatteryManager.BATTERY_STATUS_CHARGING, 50, 100));
  when(mContext.registerReceiver(
          Matchers.isNotNull(BroadcastReceiver.class), Matchers.any(IntentFilter.class)))
      .thenReturn(null);
  DeviceBatteryMetrics metrics = new DeviceBatteryMetrics();
  DeviceBatteryMetricsCollector collector = new DeviceBatteryMetricsCollector(mContext);

  // Get a handle of the receiver
  ArgumentCaptor<BroadcastReceiver> captor = ArgumentCaptor.forClass(BroadcastReceiver.class);
  verify(mContext, times(2)).registerReceiver(captor.capture(), Matchers.any(IntentFilter.class));
  final List<BroadcastReceiver> receivers = captor.getAllValues();
  assertThat(receivers.size()).isEqualTo(2);
  BroadcastReceiver receiver = receivers.get(1);
  assertThat(receiver).isNotNull();

  // Simulate connecting and disconnecting power
  ShadowSystemClock.setElapsedRealtime(9000);
  receiver.onReceive(mContext, new Intent(Intent.ACTION_POWER_DISCONNECTED));
  ShadowSystemClock.setElapsedRealtime(15000);
  receiver.onReceive(mContext, new Intent(Intent.ACTION_POWER_CONNECTED));
  ShadowSystemClock.setElapsedRealtime(22000);
  receiver.onReceive(mContext, new Intent(Intent.ACTION_POWER_DISCONNECTED));

  // Get snapshot
  ShadowSystemClock.setElapsedRealtime(28000);
  when(mContext.registerReceiver(
          Matchers.isNull(BroadcastReceiver.class), Matchers.any(IntentFilter.class)))
      .thenReturn(createBatteryIntent(BatteryManager.BATTERY_STATUS_CHARGING, 20, 100));
  collector.getSnapshot(metrics);
  verifySnapshot(metrics, 20, 12000, 11000);

  // Power Connected and test getSnapshot
  ShadowSystemClock.setElapsedRealtime(30000);
  receiver.onReceive(mContext, new Intent(Intent.ACTION_POWER_CONNECTED));
  ShadowSystemClock.setElapsedRealtime(42000);
  when(mContext.registerReceiver(
          Matchers.isNull(BroadcastReceiver.class), Matchers.any(IntentFilter.class)))
      .thenReturn(createBatteryIntent(BatteryManager.BATTERY_STATUS_CHARGING, 30, 100));
  collector.getSnapshot(metrics);
  verifySnapshot(metrics, 30, 14000, 23000);

  // PowerConnected and testGetSnapshot (Check for two consecutive CONNECTED intents)
  ShadowSystemClock.setElapsedRealtime(50000);
  receiver.onReceive(mContext, new Intent(Intent.ACTION_POWER_CONNECTED));
  ShadowSystemClock.setElapsedRealtime(51000);
  when(mContext.registerReceiver(
          Matchers.isNull(BroadcastReceiver.class), Matchers.any(IntentFilter.class)))
      .thenReturn(createBatteryIntent(BatteryManager.BATTERY_STATUS_CHARGING, 40, 100));
  collector.getSnapshot(metrics);
  verifySnapshot(metrics, 40, 14000, 32000);

  // Test for 2 consecutive powerdisconnected intents
  ShadowSystemClock.setElapsedRealtime(55000);
  receiver.onReceive(mContext, new Intent(Intent.ACTION_POWER_DISCONNECTED));
  ShadowSystemClock.setElapsedRealtime(59000);
  receiver.onReceive(mContext, new Intent(Intent.ACTION_POWER_DISCONNECTED));
  ShadowSystemClock.setElapsedRealtime(65000);
  when(mContext.registerReceiver(
          Matchers.isNull(BroadcastReceiver.class), Matchers.any(IntentFilter.class)))
      .thenReturn(createBatteryIntent(BatteryManager.BATTERY_STATUS_CHARGING, 60, 100));
  collector.getSnapshot(metrics);
  verifySnapshot(metrics, 60, 24000, 36000);
}
 
Example 13
Source File: FakeApplication.java    From RxAppState with MIT License 4 votes vote down vote up
public void notifyReceivers(@NonNull Intent intent) {
  for (BroadcastReceiver receiver : receivers) {
    receiver.onReceive(this, intent);
  }
}