Skip to content

Location and Sensors

Device signals come from two places. Location and motion sensors need extra permissions and SDKs, so they ship as official plugins; battery, network, device metrics, and haptics are in the core.

Signal API Package
Location (one fix, last known, watch) Location\Location pushinbr/pam-native-location
Accelerometer, gyroscope, magnetometer, device motion Sensors\Sensors pushinbr/pam-native-sensors
Battery, charging, power-save mode, network type System\DeviceStatus, useNetwork() core
Window size, density, safe-area insets, appearance, device and app info System\DeviceInfo core
Haptics and vibration System\Haptics, System\Vibration core

Sensors and radios are among the most battery-hungry parts of a phone. The rule on this page is simple: read once when once is enough, and stop every continuous observer as soon as the screen that needs it is hidden.

Terminal window
pam composer require pushinbr/pam-native-location
pam doctor --fix

The plugin declares ACCESS_FINE_LOCATION and ACCESS_COARSE_LOCATION on Android and a default NSLocationWhenInUseUsageDescription on iOS. Give the iOS string your own wording in pam-native.json — see Permissions. Request PermissionKind::LocationWhenInUse right before you read the position.

src/Stores/NearbyStores.php
<?php
declare(strict_types=1);
namespace App\Stores;
use Pam\Native\Attributes\State;
use Pam\Native\Component;
use Pam\Native\Element;
use Pam\Native\Location\Location;
use Pam\Native\Location\LocationPosition;
use Pam\Native\PermissionDecision;
use Pam\Native\PermissionKind;
use Pam\Native\System\Permissions;
use Pam\Native\UI\Button;
use Pam\Native\UI\Column;
use Pam\Native\UI\Text;
final class NearbyStores extends Component
{
#[State]
public string $status = 'Tap to find stores near you.';
#[State]
public bool $loading = false;
public function render(): Element
{
return Column::make(
Text::make($this->status),
Button::make($this->loading ? 'Locating…' : 'Use my location')
->onPress($this->locate(...)),
);
}
public function locate(): void
{
if ($this->loading) {
return;
}
$this->loading = true;
Permissions::requestKind(PermissionKind::LocationWhenInUse, function (PermissionDecision $decision): void {
if (!$decision->granted()) {
$this->loading = false;
$this->status = 'Location is off. You can still search by city.';
return;
}
Location::current(
callback: function (LocationPosition $position): void {
$this->loading = false;
$this->status = sprintf('Within %.0f m of you', $position->accuracy);
// Load stores near $position->latitude, $position->longitude.
},
highAccuracy: false,
timeoutMs: 15_000,
maximumAgeMs: 60_000,
failure: function (string $message): void {
$this->loading = false;
$this->status = 'Location is unavailable right now.';
},
);
});
}
}
Parameter Default Range Notes
highAccuracy true — false lets the platform use network/Wi-Fi location, which is faster and cheaper
timeoutMs 10000 1,000–60,000 When to give up
maximumAgeMs 30000 0–300,000 Accept a cached fix this recent
failure null — Receives "<code>: <detail>"; without it a failure throws

LocationPosition exposes latitude, longitude, accuracy (meters), altitude, speed, bearing, and timestamp.

Turn a failure string into a typed reason with LocationError::fromFailure() — Permission, Disabled (the system location switch is off), Unavailable, or Timeout — and show your own message for each.

Last known position and the location switch

Section titled “Last known position and the location switch”

Location::lastKnown() returns the position the platform already has without turning on GPS — the cheapest way to sort a list “near you”. When location is switched off system-wide, Location::servicesEnabled() tells you, and Location::requestServices() asks the user to turn it on (Android shows the Google Play services dialog; otherwise it resolves Unavailable and you can offer Location::openSettings()).

use Pam\Native\Location\Location;
use Pam\Native\Location\LocationServicesResult;
Location::servicesEnabled(function (bool $enabled): void {
if (!$enabled) {
Location::requestServices(function (LocationServicesResult $result): void {
$this->locationOff = $result !== LocationServicesResult::Enabled;
});
}
});

Location::watch() streams updates until you call Location::clearWatch(). The platform wakes the app only after the device moved distanceFilterMeters, at most every intervalMs on Android. Watch only while the screen that needs it is visible:

src/Screens/RunScreen.php
use Pam\Native\Location\Location;
use Pam\Native\Location\LocationPosition;
private ?int $watch = null;
public function resumed(): void
{
$this->watch ??= Location::watch(
fn (LocationPosition $position) => $this->track($position),
highAccuracy: true,
distanceFilterMeters: 10.0,
intervalMs: 5_000,
failure: fn (string $failure) => $this->watch = null,
);
}
public function paused(): void
{
if ($this->watch !== null) {
Location::clearWatch($this->watch);
$this->watch = null;
}
}

Call the same cleanup in unmount(). Use the largest distance filter and interval your feature tolerates; for a “you are here” dot on a map, the user-location layer of Maps does this for you.

Install pushinbr/pam-native-sensors. SensorType covers Accelerometer, Gyroscope, Magnetometer, and DeviceMotion (rotation vector).

Terminal window
pam composer require pushinbr/pam-native-sensors
use Pam\Native\Sensors\SensorReading;
use Pam\Native\Sensors\SensorType;
use Pam\Native\Sensors\Sensors;
Sensors::read(
SensorType::Accelerometer,
function (?SensorReading $reading): void {
if ($reading === null) {
return; // Sensor unavailable or timed out.
}
$this->tilt = [$reading->x, $reading->y, $reading->z];
},
timeoutMs: 2_000,
);

Continuous readings tied to the screen lifecycle

Section titled “Continuous readings tied to the screen lifecycle”

Sensors::watch() returns a subscription ID. Start it when the component is mounted and visible, stop it when the app goes to the background or the component unmounts:

src/Screens/LevelScreen.php
<?php
declare(strict_types=1);
namespace App\Screens;
use Pam\Native\Attributes\State;
use Pam\Native\Component;
use Pam\Native\Element;
use Pam\Native\Sensors\SensorReading;
use Pam\Native\Sensors\SensorType;
use Pam\Native\Sensors\Sensors;
use Pam\Native\UI\Text;
final class LevelScreen extends Component
{
#[State]
public float $angle = 0.0;
private ?int $watch = null;
public function mount(): void
{
$this->start();
}
public function resumed(): void
{
$this->start();
}
public function paused(): void
{
$this->stop();
}
public function unmount(): void
{
$this->stop();
}
public function render(): Element
{
return Text::make(sprintf('%.1f°', $this->angle));
}
private function start(): void
{
$this->watch ??= Sensors::watch(
SensorType::Accelerometer,
function (SensorReading $reading): void {
$this->angle = round(rad2deg(atan2($reading->x, $reading->y)), 1);
},
intervalMs: 100,
);
}
private function stop(): void
{
if ($this->watch !== null) {
Sensors::unwatch($this->watch);
$this->watch = null;
}
}
}
  • intervalMs defaults to 100 and is clamped to 16–60,000 ms. Pick the slowest rate the feature tolerates — a level or compass UI rarely needs more than 10 Hz.
  • Delivery is pull-driven through a four-value native queue. If PHP is busy, older samples are dropped in favor of the newest, so memory never grows.
  • Round values before writing them to state. Assigning an unchanged value does not re-render; assigning a noisy float on every sample does.
use Pam\Native\DeviceStatus as DeviceStatusValue;
use Pam\Native\NetworkType;
use Pam\Native\System\DeviceStatus;
DeviceStatus::read(function (DeviceStatusValue $status): void {
$this->offline = $status->networkType === NetworkType::None;
$this->saveData = $status->expensiveNetwork || $status->lowPowerMode;
});

Pam\Native\DeviceStatus (the value) has batteryLevel, charging, networkType (None, Wifi, Cellular, Ethernet, Other), expensiveNetwork, and lowPowerMode (plus powerSaveMode()).

DeviceStatus::watch($callback, $intervalMs, $fields) observes changes (interval clamped to 250–60,000 ms, default 1,000) and returns an ID for DeviceStatus::unwatch(). Pass DeviceStatusField::Network, Battery, or PowerSave in $fields to watch only what you use. Apply the same paused()/unmount() pattern as for sensors.

In components built with setup(), the useNetwork() composable gives a reactive ->online, ->type, and ->expensive that PAM releases with the component:

use Pam\Native\Component;
use Pam\Native\Composables\NetworkState;
use function Pam\Native\useNetwork;
final class FeedScreen extends Component
{
public NetworkState $network;
public function setup(): void
{
$this->network = useNetwork(); // $this->network->online
}
}

Use these signals to be a good citizen: skip prefetching large media on expensiveNetwork, defer non-urgent sync while lowPowerMode is on, and show an offline banner instead of retrying in a loop.

use Pam\Native\System\DeviceInfo;
DeviceInfo::get(function (DeviceInfo $info): void {
$this->compact = $info->width < 600;
$this->timeZone = $info->timeZone;
});

DeviceInfo reports width, height, density, appearance (UserInterfaceAppearance::Light or Dark), appState, the four safeAreaTop/Right/Bottom/Left insets, timeZone, locale, appVersion, buildNumber, manufacturer, model, memoryClassMb, lowRamDevice, and powerSaveMode. $info->constrained() is a quick check for a low-memory or power-saving device where you should scale back prefetching and effects. For layout, prefer SafeAreaView and responsive styles over manual inset math — see Safe areas and Responsive layout.

use Pam\Native\HapticFeedback;
use Pam\Native\System\Haptics;
use Pam\Native\System\Vibration;
Haptics::trigger(HapticFeedback::Success);
Vibration::vibrate(80); // milliseconds, clamped to 1–10,000

Semantic haptics are Selection, Light, Medium, Heavy, Success, Warning, and Error. Prefer them to raw vibration. Vibration::vibrate() needs android.permission.VIBRATE in pam-native.json on Android; semantic haptics use the view’s built-in haptic feedback.

Need Package
Interactive maps, markers, user location Maps
Bluetooth LE peripherals Bluetooth LE
NFC tags NFC
Health Connect / HealthKit Health
QR and barcode scanning Scanner