private boolean tryToRegisterForNetworkStatusNotifications(Context context) { synchronized (lock) { if (hasRegisteredReceiver) { return true; } try { if (context == null) { return false; } context = context.getApplicationContext(); context.registerReceiver(this, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); hasRegisteredReceiver = true; return true; } catch (ReceiverCallNotAllowedException e) { return false; } } }
public void getCurrentStatus(final Context context) { IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); try { Intent batteryStatus = context.registerReceiver(null, ifilter); if (batteryStatus != null) { level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1); scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1); mHealth = batteryStatus.getIntExtra(BatteryManager.EXTRA_HEALTH, 0); plugged = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0); present = batteryStatus.getExtras().getBoolean(BatteryManager.EXTRA_PRESENT); status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, 0); technology = batteryStatus.getExtras().getString(BatteryManager.EXTRA_TECHNOLOGY); temperature = (float) (batteryStatus.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0) / 10); voltage = (float) (batteryStatus.getIntExtra(BatteryManager.EXTRA_VOLTAGE, 0) / 1000); } } catch (ReceiverCallNotAllowedException e) { LOGE(TAG, "ReceiverCallNotAllowedException from Notification Receiver?"); e.printStackTrace(); } }
@Override public Intent registerReceiver(final BroadcastReceiver receiver, final IntentFilter filter, final @Nullable String broadcastPermission, final @Nullable Handler scheduler) { if (receiver == null) { // Allow retrieving current sticky broadcast; this is safe since we // aren't actually registering a receiver. return super.registerReceiver(null, filter, broadcastPermission, scheduler); } else { throw new ReceiverCallNotAllowedException( "BroadcastReceiver components are not allowed to register to receive intents"); } }
@Override public void onReceive(Context context, Intent intent) { LOGI(TAG, "onReceive called!"); try { Notifier.updateStatusBar(context); } catch (ReceiverCallNotAllowedException e) { e.printStackTrace(); } }
@Override public boolean bindService(final Intent service, final ServiceConnection conn, final int flags) { throw new ReceiverCallNotAllowedException( "BroadcastReceiver components are not allowed to bind to services"); }