diff --git a/.github/workflows/android-validation.yml b/.github/workflows/android-validation.yml new file mode 100644 index 0000000..946c887 --- /dev/null +++ b/.github/workflows/android-validation.yml @@ -0,0 +1,94 @@ +name: Android validation + +on: + push: + pull_request: + workflow_dispatch: + schedule: + - cron: '30 8 * * 1' + +permissions: + contents: read + +concurrency: + group: android-validation-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + verify: + runs-on: ubuntu-latest + timeout-minutes: 35 + steps: + - name: Check out source + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Make Gradle wrapper executable + run: chmod +x gradlew + - name: Set up JDK 21 + uses: actions/setup-java@03ad4de0992f5dab5e18fcb136590ce7c4a0ac95 # v5.6.0 + with: + distribution: temurin + java-version: '21' + check-latest: false + - name: Configure Gradle + uses: gradle/actions/setup-gradle@3f131e8634966bd73d06cc69884922b02e6faf92 # v6.2.0 + - name: Verify build, lint, tests, and coverage + run: >- + ./gradlew --no-daemon --stacktrace + :camera-view:lintDebug + :app:lintDebug + :app-compose:lintDebug + :camera-view:testDebugUnitTest + :app:testDebugUnitTest + :app-compose:testDebugUnitTest + :camera-view:jacocoCoreCoverageVerification + :camera-view:assembleRelease + :app:assembleDebug + :app-compose:assembleDebug + - name: Upload verification reports + if: always() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: verification-reports + if-no-files-found: ignore + path: | + **/build/reports/lint-results-*.html + **/build/reports/tests/** + camera-view/build/reports/jacoco/** + + managed-device: + needs: verify + runs-on: ubuntu-latest + timeout-minutes: 90 + steps: + - name: Check out source + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Make Gradle wrapper executable + run: chmod +x gradlew + - name: Set up JDK 21 + uses: actions/setup-java@03ad4de0992f5dab5e18fcb136590ce7c4a0ac95 # v5.6.0 + with: + distribution: temurin + java-version: '21' + check-latest: false + - name: Configure Gradle + uses: gradle/actions/setup-gradle@3f131e8634966bd73d06cc69884922b02e6faf92 # v6.2.0 + - name: Enable KVM + run: | + if [ -e /dev/kvm ]; then + sudo chmod 666 /dev/kvm + fi + - name: Run API 30 and API 37 managed-device tests + run: >- + ./gradlew --no-daemon --stacktrace + :camera-view:cameraMatrixGroupDebugAndroidTest + -Pandroid.testoptions.manageddevices.emulator.gpu=swiftshader_indirect + - name: Upload device-test results + if: always() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: managed-device-results + if-no-files-found: ignore + path: | + camera-view/build/reports/androidTests/** + camera-view/build/outputs/androidTest-results/** + camera-view/build/outputs/code_coverage/** diff --git a/.gitignore b/.gitignore index 637d11e..b8a3847 100644 --- a/.gitignore +++ b/.gitignore @@ -6,8 +6,5 @@ /build /.idea *.iml -/gradle -gradlew -gradlew.bat -*.apk -.vscode/settings.json +*.apk +.vscode/settings.json diff --git a/README.md b/README.md index 05a4885..8ac540c 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ Camera View ==================== CameraView provides a simple wrapper around the Android camera APIs, with backwards compatibility -to API 14. Rather than directly manipulating the camera, here you have an Android View that can be +to API 21. Rather than directly manipulating the camera, here you have an Android View that can be placed within your app. This View displays a preview and has the methods takePicture(File), startRecording(File) and stopRecording(). For simple use cases, CameraFragment exists as well. If you inflate a CameraFragment with Views that have the correct ids (eg. @id/capture), @@ -38,7 +38,7 @@ Camera Camera is a Composable that simplifies the Android Camera APIs. Camera includes the optional attributes quality [max, high, medium, low], -maxVideoDuration [milliseconds], and maxVideoSize [bytes]. +lensFacing [back, front], maxVideoDuration [milliseconds], and maxVideoSize [bytes]. ```kotlin val cameraController = remember { mutableStateOf(null) } Camera( @@ -47,7 +47,6 @@ Camera( lensFacing = Camera.LensFacing.BACK, maxVideoDuration = 10000, maxVideoSize = 10000000, - controller = cameraController, controller = cameraController ) ``` @@ -168,7 +167,9 @@ CameraFragment, then this will happen for free. CameraView includes the optional attributes quality [max, high, medium, low], -maxVideoDuration [milliseconds], and maxVideoSize [bytes]. +flash [auto, on, off], lensFacing [back, front], maxVideoDuration [milliseconds], +maxVideoSize [bytes], confirmImages [boolean], confirmVideos [boolean], +pinchToZoomEnabled [boolean] and matchPreviewAspectRatio [boolean]. ```xml ``` +The following attributes are also accepted, but the Camera2 backend that ships enabled today +ignores all of them. They are read by the CameraX backend, which is still opt-in: +dynamicRange [sdr, hdr], extension [none, bokeh, hdr, night, faceRetouch, auto], +frontVideoMirroringEnabled [boolean], previewStabilizationEnabled [boolean], +videoStabilizationEnabled [boolean], exposureCompensation [integer], torchEnabled [boolean] +and lowLightBoostEnabled [boolean]. Each has a matching setter, and a companion that reports +whether the active camera supports it, for example isDynamicRangeSupported(DynamicRange) or +isLowLightBoostSupported(). Query support before relying on one; an unsupported request is +logged and dropped rather than applied. + CameraView's methods are rather straight forward. Again, if you're using CameraFragment, it will handle binding the Views to the appropriate methods on CameraView. @@ -204,6 +215,117 @@ Toggles between the various cameras on the device (typically the front and back ```java mCameraView.toggleCamera(); ``` +Reports when the camera opens and closes. CameraFragment already implements this. +```java +mCameraView.setOnCameraStateChangedListener(listener); +``` +With confirmation enabled, a capture is shown in CameraView's own preview and onImageConfirmation() +or onVideoConfirmation() fires instead of onImageCaptured(File) or onVideoCaptured(File). Accept or +discard it to continue; rejecting also deletes the file. Enable matchPreviewAspectRatio alongside +this so the capture and the preview are framed the same. +```java +mCameraView.setImageConfirmationEnabled(true); +mCameraView.confirmPicture(); // or rejectPicture() +mCameraView.confirmVideo(); // or rejectVideo() +``` +Scans the preview for barcodes while the camera is open, reporting each batch of results to the +listener. Formats come from Barcode.Format, and the camera must already be open. +```java +mCameraView.enterBarcodeScanner(listener, Barcode.Format.QR_CODE); +mCameraView.exitBarcodeScanner(); +``` + +Wide gamut +----------------- +Pictures are sRGB unless you ask otherwise. A modern sensor sees more than sRGB can describe, +which is why manufacturers' camera apps save wide-gamut stills, but a viewer that ignores the +colour profile shows them oversaturated - so it is opt-in, and refused on a camera or a platform +that cannot honour it rather than quietly producing sRGB. +```java +if (mCameraView.isColorSpaceSupported(CameraView.ColorSpace.DISPLAY_P3)) { + mCameraView.setColorSpace(CameraView.ColorSpace.DISPLAY_P3); +} +``` + +Video snapshot +----------------- +takePicture works during a recording, where the camera can hold a preview, a recording and a still +at once - which is most of them, but not a LEGACY camera2 device. Ask before showing the button; +where it is false the picture is refused and the recording carries on. +```java +if (mCameraView.isSnapshotWhileRecordingSupported()) { + mCameraView.takePicture(file); +} +``` + +Faces +----------------- +The camera finds faces on its own, to decide what to focus and expose for. setFaceDetectionListener +reports them, with a matrix that maps a face's bounds onto the view so you can draw over the +preview. It returns false on a camera that cannot report faces. +```java +mCameraView.setFaceDetectionListener((faces, faceToView) -> { + for (Face face : faces) { + RectF onScreen = new RectF(face.getBounds()); + faceToView.mapRect(onScreen); + } +}); +mCameraView.setFaceDetectionListener(null); +``` + +Frames +----------------- +startFrameAnalysis hands every frame to your own analyzer, on a background thread, for detection +CameraView does not do itself. Only the newest frame is kept, so a slow analyzer drops frames +rather than falling behind, and the image is recycled when onFrame returns. Params.setMaxSize asks +for smaller frames than the preview, which most detectors are no worse at. +```java +mCameraView.startFrameAnalysis(frame -> { + InputImage image = InputImage.fromMediaImage(frame.getImage(), frame.getRotationDegrees()); + // ... and frame.getFrameToViewTransform() maps a result onto the view +}, new FrameStream.Params().setMaxSize(new Size(640, 480))); +mCameraView.stopFrameAnalysis(); +``` + +Wear companion +----------------- +The sample has a watch half, in `app-wear`: the phone streams its camera to the watch and the +watch's button asks the phone for a picture. Both halves share one application id, which is how +the Data Layer pairs them, so they have to be built and signed together. + +Nothing in the library is Wear-specific. The watch reads the phone's stream with the same +VideoView.setStream the phone sample uses locally; what the sample adds is the transport, and the +numbers that make it work over a watch link - 480p, a megabit, and a key frame every second, +since a stream can only be joined at a key frame. +```java +mCameraView.stream(new VideoStream.Params.Builder() + .setAudioEnabled(false) + .setMaxSize(new Size(640, 480)) + .setBitRate(1_000_000) + .setIFrameInterval(1) + .setIsLossy(true) + .build()); +``` + +Backends +----------------- +CameraView drives camera2 by default. CameraX is opt-in: it carries a database of per-device +quirks and is the only backend that can reach a manufacturer's Extensions, but it has had less +validation here. The legacy android.hardware.Camera backend is there for devices that predate +camera2. +```java +CameraView.setDefaultBackend(CameraView.Backend.CAMERA_X); +``` +```xml + +``` +If your minSdk is older than androidx.camera supports, build with `-Pcameraview.core=true` to +leave the CameraX backend, the Compose wrapper and their dependencies out. What is left covers +API 21 and up. This is not hypothetical: `camera-camera2` pulls in `camera-camera2-pipe`, which +declares a minSdk of 24, and a dependency's floor becomes your app's floor whatever this library +declares. The sample reads the same flag, so `-Pcameraview.core=true :app:assembleDebug` builds +it at 23. Exif ----------------- diff --git a/app-compose/build.gradle b/app-compose/build.gradle index 809c2a2..aa80c1c 100644 --- a/app-compose/build.gradle +++ b/app-compose/build.gradle @@ -1,11 +1,10 @@ plugins { id 'com.android.application' - id 'org.jetbrains.kotlin.android' id 'org.jetbrains.kotlin.plugin.compose' version '2.3.21' } android { - namespace 'com.xlythe.sample.camera' + namespace = 'com.xlythe.sample.camera' compileSdk 37 defaultConfig { @@ -25,14 +24,15 @@ android { } } compileOptions { - sourceCompatibility JavaVersion.VERSION_11 - targetCompatibility JavaVersion.VERSION_11 - } - kotlinOptions { - jvmTarget = '11' + sourceCompatibility JavaVersion.VERSION_17 + targetCompatibility JavaVersion.VERSION_17 } buildFeatures { - compose true + compose = true + } + lint { + abortOnError = true + checkReleaseBuilds = true } testOptions { unitTests.includeAndroidResources = true @@ -44,20 +44,20 @@ android { dependencies { implementation project(':camera-view') - implementation 'androidx.core:core-ktx:+' - implementation 'androidx.lifecycle:lifecycle-runtime-ktx:+' - implementation 'androidx.activity:activity-compose:+' - implementation platform('androidx.compose:compose-bom:+') + implementation 'androidx.core:core-ktx:1.19.0' + implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.11.1' + implementation 'androidx.activity:activity-compose:1.13.0' + implementation platform('androidx.compose:compose-bom:2026.06.01') implementation 'androidx.compose.ui:ui' implementation 'androidx.compose.ui:ui-graphics' implementation 'androidx.compose.ui:ui-tooling-preview' implementation 'androidx.compose.material3:material3' implementation 'androidx.compose.material:material-icons-extended' - testImplementation 'junit:junit:+' - testImplementation 'org.robolectric:robolectric:+' - androidTestImplementation 'androidx.test.ext:junit:+' - androidTestImplementation 'androidx.test.espresso:espresso-core:+' - androidTestImplementation platform('androidx.compose:compose-bom:+') + testImplementation 'junit:junit:4.13.2' + testImplementation 'org.robolectric:robolectric:4.18.1' + androidTestImplementation 'androidx.test.ext:junit:1.3.0' + androidTestImplementation 'androidx.test.espresso:espresso-core:3.7.0' + androidTestImplementation platform('androidx.compose:compose-bom:2026.06.01') androidTestImplementation 'androidx.compose.ui:ui-test-junit4' debugImplementation 'androidx.compose.ui:ui-tooling' debugImplementation 'androidx.compose.ui:ui-test-manifest' diff --git a/app-compose/src/main/java/com/xlythe/sample/camera/MainActivity.kt b/app-compose/src/main/java/com/xlythe/sample/camera/MainActivity.kt index 0969f2e..0cc6518 100644 --- a/app-compose/src/main/java/com/xlythe/sample/camera/MainActivity.kt +++ b/app-compose/src/main/java/com/xlythe/sample/camera/MainActivity.kt @@ -200,6 +200,7 @@ private fun createImageFile(context: Context): File { return File.createTempFile("JPEG_${timeStamp}_", ".jpg", storageDir) } +@SuppressLint("MissingPermission") @Composable fun SimpleDemoScreen() { val context = LocalContext.current @@ -363,6 +364,7 @@ fun StreamDemoScreen() { } } +@SuppressLint("MissingPermission") @Composable fun ResizingDemoScreen() { val cameraController = remember { mutableStateOf(null) } @@ -417,6 +419,7 @@ fun ResizingDemoScreen() { } } +@SuppressLint("MissingPermission") @Composable fun QrCodeDemoScreen() { val context = LocalContext.current diff --git a/app-compose/src/main/res/values-v31/themes.xml b/app-compose/src/main/res/values-v31/themes.xml new file mode 100644 index 0000000..9eefc1a --- /dev/null +++ b/app-compose/src/main/res/values-v31/themes.xml @@ -0,0 +1,7 @@ + + + \ No newline at end of file diff --git a/app-compose/src/main/res/values/themes.xml b/app-compose/src/main/res/values/themes.xml index 0464542..667ec8c 100644 --- a/app-compose/src/main/res/values/themes.xml +++ b/app-compose/src/main/res/values/themes.xml @@ -3,7 +3,5 @@ \ No newline at end of file diff --git a/app-compose/src/test/java/com/xlythe/sample/camera/MainActivityTest.kt b/app-compose/src/test/java/com/xlythe/sample/camera/MainActivityTest.kt index 0dd57f9..d8a1917 100644 --- a/app-compose/src/test/java/com/xlythe/sample/camera/MainActivityTest.kt +++ b/app-compose/src/test/java/com/xlythe/sample/camera/MainActivityTest.kt @@ -8,7 +8,7 @@ import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config @RunWith(RobolectricTestRunner::class) -@Config(minSdk = 24) +@Config(sdk = [37]) class MainActivityTest { @Test diff --git a/app-wear/.gitignore b/app-wear/.gitignore new file mode 100644 index 0000000..796b96d --- /dev/null +++ b/app-wear/.gitignore @@ -0,0 +1 @@ +/build diff --git a/app-wear/build.gradle b/app-wear/build.gradle new file mode 100644 index 0000000..dfcb542 --- /dev/null +++ b/app-wear/build.gradle @@ -0,0 +1,32 @@ +apply plugin: 'com.android.application' + +android { + compileSdkVersion 37 + enableKotlin = false + + defaultConfig { + // The Data Layer pairs a watch app with a phone app by application id and signature, so + // this has to be the id of the phone sample rather than one of its own. + applicationId "com.xlythe.sample.camera" + minSdkVersion 30 + targetSdkVersion 37 + versionCode 1 + versionName "1.0.0" + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_17 + targetCompatibility JavaVersion.VERSION_17 + } + lint { + abortOnError = true + checkReleaseBuilds = true + } + namespace = 'com.xlythe.sample.camera.wear' +} + +dependencies { + // Only the pieces that read a stream and show a picture; the watch never opens a camera. + implementation project(':camera-view') + implementation 'com.google.android.gms:play-services-wearable:19.0.0' + implementation 'androidx.appcompat:appcompat:1.7.1' +} diff --git a/app-wear/src/main/AndroidManifest.xml b/app-wear/src/main/AndroidManifest.xml new file mode 100644 index 0000000..2fbd396 --- /dev/null +++ b/app-wear/src/main/AndroidManifest.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/app-wear/src/main/java/com/xlythe/sample/camera/wear/MainActivity.java b/app-wear/src/main/java/com/xlythe/sample/camera/wear/MainActivity.java new file mode 100644 index 0000000..1e51d0c --- /dev/null +++ b/app-wear/src/main/java/com/xlythe/sample/camera/wear/MainActivity.java @@ -0,0 +1,220 @@ +package com.xlythe.sample.camera.wear; + +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.os.Bundle; +import android.util.Log; +import android.view.View; +import android.widget.Button; +import android.widget.ImageView; +import android.widget.TextView; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.appcompat.app.AppCompatActivity; + +import com.google.android.gms.wearable.CapabilityClient; +import com.google.android.gms.wearable.ChannelClient; +import com.google.android.gms.wearable.Node; +import com.google.android.gms.wearable.Wearable; +import com.xlythe.view.camera.VideoStream; +import com.xlythe.view.camera.VideoView; + +import java.io.File; +import java.util.Set; +import java.util.concurrent.Executors; + +/** + * The watch end of the companion sample: the phone's camera on your wrist, and a shutter button. + * + *

Nothing here opens a camera. The phone does that, and CameraView's own streaming encodes the + * preview; all the watch does is hand the bytes coming off a Data Layer channel to a + * {@link VideoView}, which is the same thing the phone sample does with a local pipe. That is why + * none of this lives in the library: the only part that is specific to a watch is the transport. + *

+ */ +public class MainActivity extends AppCompatActivity { + private static final String TAG = "CameraViewWear"; + + /** Declared by the phone app in wear.xml, and how the watch finds it. */ + private static final String CAPABILITY_PHONE_CAMERA = "camera_view_sample"; + + private VideoView mPreview; + private ImageView mPicture; + private Button mShutter; + private TextView mStatus; + + @Nullable private Node mPhone; + @Nullable private VideoStream mStream; + + private final ChannelClient.ChannelCallback mChannelCallback = + new ChannelClient.ChannelCallback() { + @Override + public void onChannelOpened(@NonNull ChannelClient.Channel channel) { + if (WearProtocol.PATH_PREVIEW.equals(channel.getPath())) { + showPreview(channel); + } else if (WearProtocol.PATH_PICTURE.equals(channel.getPath())) { + showPicture(channel); + } + } + + @Override + public void onChannelClosed(@NonNull ChannelClient.Channel channel, + int closeReason, int appSpecificErrorCode) { + if (WearProtocol.PATH_PREVIEW.equals(channel.getPath())) { + runOnUiThread(() -> setStatus(R.string.status_preview_ended)); + } + } + }; + + @Override + protected void onCreate(@Nullable Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_main); + + mPreview = findViewById(R.id.preview); + mPicture = findViewById(R.id.picture); + mShutter = findViewById(R.id.shutter); + mStatus = findViewById(R.id.status); + + mShutter.setOnClickListener(view -> takePicture()); + mPicture.setOnClickListener(view -> mPicture.setVisibility(View.GONE)); + } + + @Override + protected void onStart() { + super.onStart(); + Wearable.getChannelClient(this).registerChannelCallback(mChannelCallback); + findPhone(); + } + + @Override + protected void onStop() { + Wearable.getChannelClient(this).unregisterChannelCallback(mChannelCallback); + tell(WearProtocol.PATH_STOP_PREVIEW); + closeStream(); + super.onStop(); + } + + /** + * Finds the phone by the capability it advertises rather than by picking a connected node. + * + *

A watch can be connected to more than one thing, and only the node running the phone + * half of this sample can answer.

+ */ + private void findPhone() { + setStatus(R.string.status_looking_for_phone); + Wearable.getCapabilityClient(this) + .getCapability(CAPABILITY_PHONE_CAMERA, CapabilityClient.FILTER_REACHABLE) + .addOnSuccessListener(this, info -> { + Set nodes = info.getNodes(); + mPhone = nodes.isEmpty() ? null : nodes.iterator().next(); + if (mPhone == null) { + setStatus(R.string.status_no_phone); + mShutter.setEnabled(false); + return; + } + mShutter.setEnabled(true); + setStatus(R.string.status_asking_for_preview); + tell(WearProtocol.PATH_START_PREVIEW); + }) + .addOnFailureListener(this, error -> { + Log.w(TAG, "Could not look for the phone", error); + setStatus(R.string.status_no_phone); + }); + } + + private void takePicture() { + if (mPhone == null) { + findPhone(); + return; + } + setStatus(R.string.status_capturing); + tell(WearProtocol.PATH_TAKE_PICTURE); + } + + /** Sends a one-shot message, which is all the watch ever needs to send. */ + private void tell(String path) { + Node phone = mPhone; + if (phone == null) { + return; + } + Wearable.getMessageClient(this) + .sendMessage(phone.getId(), path, new byte[0]) + .addOnFailureListener(error -> Log.w(TAG, "Could not send " + path, error)); + } + + /** + * Plays the phone's preview. + * + *

The channel's input stream is H.264 exactly as CameraView's encoder produced it, which is + * what VideoView.setStream expects, so there is nothing to decode here.

+ */ + private void showPreview(ChannelClient.Channel channel) { + ChannelClient channels = Wearable.getChannelClient(this); + channels.getInputStream(channel).addOnSuccessListener(this, inputStream -> { + closeStream(); + mStream = new VideoStream.Builder().withVideoStream(inputStream).build(); + mPreview.setStream(mStream); + mPreview.play(); + setStatus(R.string.status_streaming); + }).addOnFailureListener(this, error -> { + Log.w(TAG, "Could not read the preview", error); + setStatus(R.string.status_preview_failed); + }); + } + + /** + * Shows a picture the phone just took. + * + *

Received to a file rather than read from the stream, because a full-size JPEG over a + * watch link takes long enough that holding it in memory while it arrives is the wrong + * trade.

+ */ + private void showPicture(ChannelClient.Channel channel) { + File file = new File(getCacheDir(), "from-phone.jpg"); + Wearable.getChannelClient(this) + .receiveFile(channel, android.net.Uri.fromFile(file), false /* append */) + .addOnSuccessListener(this, ignored -> decode(file)) + .addOnFailureListener(this, error -> { + Log.w(TAG, "Could not receive the picture", error); + setStatus(R.string.status_capture_failed); + }); + } + + private void decode(File file) { + Executors.newSingleThreadExecutor().execute(() -> { + // Decoded small: a watch screen is a few hundred pixels across and the phone's + // picture is thousands. + BitmapFactory.Options options = new BitmapFactory.Options(); + options.inSampleSize = 4; + Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options); + runOnUiThread(() -> { + if (bitmap == null) { + setStatus(R.string.status_capture_failed); + return; + } + mPicture.setImageBitmap(bitmap); + mPicture.setVisibility(View.VISIBLE); + setStatus(R.string.status_streaming); + }); + }); + } + + private void closeStream() { + VideoStream stream = mStream; + mStream = null; + if (stream == null) { + return; + } + try { + stream.close(); + } catch (RuntimeException error) { + Log.w(TAG, "Could not close the preview stream", error); + } + } + + private void setStatus(int message) { + mStatus.setText(message); + } +} diff --git a/app-wear/src/main/java/com/xlythe/sample/camera/wear/WearProtocol.java b/app-wear/src/main/java/com/xlythe/sample/camera/wear/WearProtocol.java new file mode 100644 index 0000000..65cdacd --- /dev/null +++ b/app-wear/src/main/java/com/xlythe/sample/camera/wear/WearProtocol.java @@ -0,0 +1,52 @@ +package com.xlythe.sample.camera.wear; + +import android.util.Size; + +/** + * What the phone and the watch say to each other. + * + *

Mirrored in the phone module on purpose: they are separate applications that happen to live + * in one repository, and a shared Gradle module for a handful of constants would be more + * machinery than it saves. A change has to be made in both copies.

+ * + *

The split between messages and channels is the Data Layer's own: a message is a small + * one-shot notification, and a channel is a socket, which is what a preview or a photo needs. + * What a channel is not is fast. The Data Layer prefers Bluetooth and only uses Wi-Fi when there + * is no Bluetooth at all, so a realistic budget is a couple of megabits - which is why the + * preview is asked for at a size and bit rate a watch link can carry rather than whatever the + * phone's camera would like to send.

+ */ +final class WearProtocol { + /** The watch asking the phone to start sending a preview. */ + static final String PATH_START_PREVIEW = "/camera-view/start-preview"; + + /** The watch asking the phone to stop. */ + static final String PATH_STOP_PREVIEW = "/camera-view/stop-preview"; + + /** The watch asking the phone to take a picture and send it back. */ + static final String PATH_TAKE_PICTURE = "/camera-view/take-picture"; + + /** The channel the phone streams the preview over. */ + static final String PATH_PREVIEW = "/camera-view/preview"; + + /** The channel the phone sends a captured picture over. */ + static final String PATH_PICTURE = "/camera-view/picture"; + + /** + * The preview the watch asks for. + * + *

480p at a megabit is about what a Bluetooth link will carry without the stream falling + * behind, and a watch screen cannot show more than that anyway. The key frame interval is the + * part that is easy to get wrong: a stream can only be joined at a key frame, so a long + * interval means the watch stares at black for that long after it connects.

+ */ + static final Size PREVIEW_SIZE = new Size(640, 480); + + static final int PREVIEW_BIT_RATE = 1_000_000; + + static final int PREVIEW_FRAME_RATE = 20; + + static final int PREVIEW_KEY_FRAME_INTERVAL_SECONDS = 1; + + private WearProtocol() {} +} diff --git a/app-wear/src/main/res/layout/activity_main.xml b/app-wear/src/main/res/layout/activity_main.xml new file mode 100644 index 0000000..00113ef --- /dev/null +++ b/app-wear/src/main/res/layout/activity_main.xml @@ -0,0 +1,44 @@ + + + + + + + +