Sony Smartwatch 2 и push-уведомления

Я пытаюсь подписаться на пример уведомления + управления в Google Cloud Messaging, чтобы получать push-уведомления непосредственно на часы.

я добавил разрешения:


<permission android:name="com.example.myapp.permission.C2D_MESSAGE"
    android:protectionLevel="signature" />
<uses-permission android:name="com.sonymobile.smartconnect.extension.notificationsample.permission.C2D_MESSAGE" />

Добавлен приемник обновление и служба:

    <receiver android:name=".MyReceiver"
        android:permission="com.google.android.c2dm.permission.SEND">
      <!-- Receive the actual message -->
      <intent-filter>
          <action android:name="com.google.android.c2dm.intent.RECEIVE" />
          <category android:name="com.sonymobile.smartconnect.extension.notificationsample" />
      </intent-filter>
      <!-- Receive the registration id -->
      <intent-filter>
          <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
          <category android:name="com.sonymobile.smartconnect.extension.notificationsample" />
      </intent-filter>
  </receiver>

And implemented the MyReceiver class with methods as in this link

Метод onReceive вызывается только при первой регистрации. Он возвращает мне идентификатор токена, но не получает уведомления и не вызывается, когда я активирую пример приложения.

Я протестировал Sender Server с обычным приложением для Android, и он успешно отправляет уведомление.

Какой-нибудь намек на отправку push-уведомлений на умные часы?

Спасибо!

ОБНОВЛЕНИЕ: теперь я продвинулся вперед в своей проблеме, я изменил MyReceiver.java на:

открытый класс MyReceiver расширяет GCMBroadcastReceiver {

@Override
protected String getGCMIntentServiceClassName(Context context)
{
    return RemoteNotificationIntentService.class.getName();
}

}

И я реализовал класс RemoteNotificationIntentService:

открытый класс RemoteNotificationIntentService расширяет GCMBaseIntentService {общедоступное статическое перечисление RemoteNotificationFields {RN_TITLE, RN_BODY, RN_TICKER, RN_SOUND, RN_SMALL_ICON, RN_LARGE_ICON, RN_LED_COLOR_ARGB}; частная статическая HashMap FIELD_MAP;

private static final String APPLICATION_NAME = "Appverse Bank 4 Sw2";


public RemoteNotificationIntentService(String senderId) {
    super(senderId);
    System.out.println("init");
    // TODO Auto-generated constructor stub
}

public RemoteNotificationIntentService() {
    super("PUSH_NOTIFICATION_SERVICE");
    // TODO Auto-generated constructor stub
    System.out.println("init");
}

private HashMap<String, String> storeIntentExtras(Context context, Intent intent) {
    try{

        HashMap<String, String> returnValue = new HashMap<String, String>();
        HashMap<String, String> JSONSerializable = new HashMap<String, String>();

        for(String sFieldName:intent.getExtras().keySet()){
            if(FIELD_MAP.containsKey(sFieldName)){
                String sFieldType = FIELD_MAP.get(sFieldName);
                returnValue.put(sFieldType, intent.getStringExtra(sFieldName));
                JSONSerializable.put(sFieldType, intent.getStringExtra(sFieldName));
            }else{
                JSONSerializable.put(sFieldName, intent.getStringExtra(sFieldName));
            }
        }
        //fill mandatory fields
        if(!returnValue.containsKey(RemoteNotificationFields.RN_TITLE.toString())||returnValue.get(RemoteNotificationFields.RN_TITLE.toString()).trim().equals("")){returnValue.put(RemoteNotificationFields.RN_TITLE.toString(), APPLICATION_NAME);}
        if(!returnValue.containsKey(RemoteNotificationFields.RN_TICKER.toString())||returnValue.get(RemoteNotificationFields.RN_TICKER.toString()).trim().equals("")){returnValue.put(RemoteNotificationFields.RN_TICKER.toString(), returnValue.get(RemoteNotificationFields.RN_TITLE.toString()));}
        if(!returnValue.containsKey(RemoteNotificationFields.RN_SMALL_ICON.toString())||returnValue.get(RemoteNotificationFields.RN_SMALL_ICON.toString()).trim().equals("")){returnValue.put(RemoteNotificationFields.RN_SMALL_ICON.toString(), "icon");}
        if(!returnValue.containsKey(RemoteNotificationFields.RN_LED_COLOR_ARGB.toString())||returnValue.get(RemoteNotificationFields.RN_LED_COLOR_ARGB.toString()).trim().equals("")){returnValue.put(RemoteNotificationFields.RN_LED_COLOR_ARGB.toString(), String.valueOf(Color.BLUE));}

        JSONSerializable = null;
        return returnValue;
    }catch(Exception ex){}
    return null;
}

@Override
protected void onMessage(Context context, Intent intent) {
    try{
        System.out.println("message!!!");
    }catch(Exception ex){/*CANNOT LOG CAUSE CALLING LOGGER WILL PROMPT NULL POINTER EXCEPTION*/}        
}

@Override
protected void onRegistered(Context context, String registrationId) {
    try{
        System.out.println("Register K");
    }catch(Exception ex){
        System.out.println("onRegistered "+ex.getMessage());
    }
}

@Override
protected void onUnregistered(Context context, String registrationId) {
    try{
        System.out.println("Unregister K");

    } catch(Exception ex){
        System.out.println("onUnregistered "+ex.getMessage());
    }
}

@Override
protected void onError(Context context, String error) {
    System.out.println("error");
}

}

но он не входит ни в какой метод этого метода, и я получаю это сообщение:
V/GCMBroadcastReceiver(4052): onReceive: com.google.android.c2dm.intent.RECEIVE
V/GCMBroadcastReceiver(4052): GCM IntentService класс: com.sonymobile.smartconnect.extension.notificationsample.RemoteNotificationIntentService
V/GCMBaseIntentService(1825): Получение wakelock

ОБНОВЛЕНИЕ 2

Я, наконец, получаю данные в своем классе, мне нужно добавить службу в манифест


person Kechis    schedule 12.03.2014    source источник
comment
Оно работает! если кому-то нужна помощь с этим постом здесь   -  person Kechis    schedule 14.03.2014


Ответы (1)


В вашем обычном приложении для Android вы можете успешно получать сообщения C2DM? Получение уведомлений C2DM должно быть одинаковым, независимо от того, создаете ли вы стандартное приложение для Android или расширение Control для SW2. Единственное отличие состоит в том, что для SW2 после получения уведомления C2DM вы затем добавляете его в Content Provider для SW2, чтобы отправить уведомление с телефона на часы.

person mldeveloper    schedule 12.03.2014