Ваше приложение Wearable полностью отличается от портативного приложения, при этом единственным каналом связи является использование API сообщений/данных, поэтому, к сожалению, нет способа напрямую инициировать действие на карманном компьютере из уведомления, созданного на Wearable.
Вы правильны в подходе, который должен быть взят, однако:
- Создать PendingIntent для действия, которое запускает службу (мысленный IntentService работает отлично)
- В этой службе:
- Подключитесь к GoogleApiClient
- Если подключенное устройство найдено, запустите ConfirmationActivity, используя
OPEN_ON_PHONE_ANIMATION
(это отображает видимый знак для вашего пользователя, что ваше приложение открывает что-то на их КПК)
- Отправить сообщение для подключенного устройства с использованием набора пути (скажем,
notification/open
)
- В вашем портативном приложении, осуществлять WearableListenerService, который получит ваше сообщение в фоновом режиме:
- В вызове onMessageReceived() проверьте путь принятого сообщения для заданного вами пути (то есть
messageEvent.getPath().equals("notification/open")
)
- Если оно соответствует, начните соответствующую операцию на своем КПК.
Этот подход используется в Muzei при запуске циферблата, имеющего никогда не активировал живые обои в портативном приложении. Код по каждому из этих разделов может быть найден на Github repository.
В частности, шаги 1 и 2 может быть найден в ActivateMuzeiIntentService:
public static void showNotification(Context context) {
Notification.Builder builder = new Notification.Builder(context);
// Set up your notification as normal
// Create the launch intent, in this case setting it as the content action
Intent launchMuzeiIntent = new Intent(context,
ActivateMuzeiIntentService.class);
PendingIntent pendingIntent = PendingIntent.getService(context, 0,
launchMuzeiIntent, 0);
builder.addAction(new Notification.Action.Builder(R.drawable.ic_open_on_phone,
context.getString(R.string.common_open_on_phone), pendingIntent)
.extend(new Notification.Action.WearableExtender()
.setAvailableOffline(false))
.build());
builder.extend(new Notification.WearableExtender()
.setContentAction(0));
// Send the notification with notificationManager.notify as usual
}
protected void onHandleIntent(Intent intent) {
// Open on Phone action
GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this)
.addApi(Wearable.API)
.build();
ConnectionResult connectionResult =
googleApiClient.blockingConnect(30, TimeUnit.SECONDS);
if (!connectionResult.isSuccess()) {
Log.e(TAG, "Failed to connect to GoogleApiClient.");
return;
}
List<Node> nodes = Wearable.NodeApi.getConnectedNodes(googleApiClient)
.await().getNodes();
// Ensure there is a connected device
if (!nodes.isEmpty()) {
// Show the open on phone animation
Intent openOnPhoneIntent = new Intent(this, ConfirmationActivity.class);
openOnPhoneIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
openOnPhoneIntent.putExtra(ConfirmationActivity.EXTRA_ANIMATION_TYPE,
ConfirmationActivity.OPEN_ON_PHONE_ANIMATION);
startActivity(openOnPhoneIntent);
// Clear the notification
NotificationManager notificationManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
notificationManager.cancel(NOTIFICATION_ID);
// Send the message to the phone to open Muzei
for (Node node : nodes) {
Wearable.MessageApi.sendMessage(googleApiClient, node.getId(),
"notification/open", null).await();
}
}
googleApiClient.disconnect();
}
А затем шаг 3 на портативной стороне обрабатывается MuzeiWearableListenerService:
public void onMessageReceived(MessageEvent messageEvent) {
String path = messageEvent.getPath();
if (path.equals("notification/open")) {
// In this case, we launch the launch intent for the application
// but it could be anything
PackageManager packageManager = getPackageManager();
Intent mainIntent = packageManager.getLaunchIntentForPackage(
getPackageName());
startActivity(mainIntent);
}
}
Вы создаете уведомление из своего портативного приложения или из вашего приложения Wearable? – ianhanniballake
@ianhanniballake Я создаю уведомление в пригодном для носки приложении –