2014-12-18 2 views
2

Я хочу начать работу в переносном приложении и отправить некоторые данные, когда пользователь нажимает кнопку уведомления в изнашивании. Я использую ниже код для создания уведомления в изнашивании.Android Wear: запуск активности в карманном компьютере при нажатии кнопки действия уведомления об изнашивании

public Notification buildNotification(Context context) { 
     PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, 
       new Intent(context, MainActivity.class), 0); 

     return buildBasicNotification(context).extend(new Notification.WearableExtender() 
       .setContentIcon(R.drawable.content_icon_small) 
       .setContentIconGravity(Gravity.START)) 
       .addAction(new Notification.Action(R.drawable.ic_launcher, 
         "Action A", pendingIntent)) 


       .build(); 
    } 

Можно ли начать свою деятельность в КПК через ожидание намерения только или мы должны начать обслуживание/деятельность в изнашивания нажав кнопку действия и с этого отправить сообщение активности/услуг к устройству через сообщение апи. Любая помощь будет оценена!

+0

Вы создаете уведомление из своего портативного приложения или из вашего приложения Wearable? – ianhanniballake

+0

@ianhanniballake Я создаю уведомление в пригодном для носки приложении –

ответ

10

Ваше приложение Wearable полностью отличается от портативного приложения, при этом единственным каналом связи является использование API сообщений/данных, поэтому, к сожалению, нет способа напрямую инициировать действие на карманном компьютере из уведомления, созданного на Wearable.

Вы правильны в подходе, который должен быть взят, однако:

  1. Создать PendingIntent для действия, которое запускает службу (мысленный IntentService работает отлично)
  2. В этой службе:
    1. Подключитесь к GoogleApiClient
    2. Если подключенное устройство найдено, запустите ConfirmationActivity, используя OPEN_ON_PHONE_ANIMATION (это отображает видимый знак для вашего пользователя, что ваше приложение открывает что-то на их КПК)
    3. Отправить сообщение для подключенного устройства с использованием набора пути (скажем, notification/open)
  3. В вашем портативном приложении, осуществлять WearableListenerService, который получит ваше сообщение в фоновом режиме:
    1. В вызове onMessageReceived() проверьте путь принятого сообщения для заданного вами пути (то есть messageEvent.getPath().equals("notification/open"))
    2. Если оно соответствует, начните соответствующую операцию на своем КПК.

Этот подход используется в 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); 
    } 
} 
+0

Большое спасибо за разъяснение. –