|
| 1 | +/* |
| 2 | + * Copyright 2025 The Android Open Source Project |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * https://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package com.example.wear.snippets.hardwarebuttons |
| 18 | + |
| 19 | +import android.app.Activity |
| 20 | +import android.content.Context |
| 21 | +import android.util.Log |
| 22 | +import android.view.KeyEvent |
| 23 | +import androidx.activity.ComponentActivity |
| 24 | +import androidx.wear.input.WearableButtons |
| 25 | + |
| 26 | +class HardwareButtonsActivity : ComponentActivity() { |
| 27 | + // [START android_wear_hardware_buttons_events] |
| 28 | + override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean { |
| 29 | + return if (event?.repeatCount == 0) { |
| 30 | + when (keyCode) { |
| 31 | + KeyEvent.KEYCODE_STEM_1 -> { |
| 32 | + Log.d(TAG, "KEYCODE_STEM_1 pressed") |
| 33 | + true |
| 34 | + } |
| 35 | + KeyEvent.KEYCODE_STEM_2 -> { |
| 36 | + Log.d(TAG, "KEYCODE_STEM_2 pressed") |
| 37 | + true |
| 38 | + } |
| 39 | + else -> { |
| 40 | + super.onKeyDown(keyCode, event) |
| 41 | + } |
| 42 | + } |
| 43 | + } else { |
| 44 | + super.onKeyDown(keyCode, event) |
| 45 | + } |
| 46 | + } |
| 47 | + // [END android_wear_hardware_buttons_events] |
| 48 | + |
| 49 | + fun hardwareButtonsCount(context: Context, activity: Activity) { |
| 50 | + // [START android_wear_hardware_buttons_count] |
| 51 | + val count = WearableButtons.getButtonCount(context) |
| 52 | + |
| 53 | + if (count > 1) { |
| 54 | + Log.d(TAG, "More than one button available") |
| 55 | + } |
| 56 | + |
| 57 | + val buttonInfo = WearableButtons.getButtonInfo( |
| 58 | + activity, |
| 59 | + KeyEvent.KEYCODE_STEM_1 |
| 60 | + ) |
| 61 | + |
| 62 | + if (buttonInfo == null) { |
| 63 | + // KEYCODE_STEM_1 is unavailable |
| 64 | + Log.d(TAG, "KEYCODE_STEM_1 not available") |
| 65 | + } else { |
| 66 | + // KEYCODE_STEM_1 is present on the device |
| 67 | + Log.d(TAG, "KEYCODE_STEM_1 is present on the device") |
| 68 | + } |
| 69 | + // [END android_wear_hardware_buttons_count] |
| 70 | + } |
| 71 | +} |
| 72 | +private const val TAG = "HardwareButtons" |
0 commit comments