Android Wear: пользовательская страница в уведомлении

Я новичок в Android Wear (разработка). Я начал читать и внедрять документацию.

Однако я не уверен, что то, что я хочу реализовать, возможно "überhaupt". Я могу прикреплять пользовательские «действия» к получаемым push-уведомлениям, но, похоже, он может открывать только активность телефона. Почему я не могу открыть износ-активность?

Пуш-уведомления содержат текст, который отображается изначально, и данные о футбольном матче (вторая страница?). Я хочу отображать названия команд и счет без вмешательства телефона.

Так это возможно?

Плюс какое поведение по умолчанию? Прикрепить это к действию или через дополнительную страницу в уведомлении?

NotificationCompat.Builder notificationBuilder =
    new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_stat_notification_icon3)
            .setContentTitle(this.getString(R.string.notifications_title))
            .setContentText(message)
            .setStyle(new NotificationCompat.BigTextStyle().bigText(message))
            .setContentIntent(matchDetailPendingIntent)
            .setAutoCancel(true)
            .extend(new NotificationCompat.WearableExtender()
                            .addPage(CustomDesignedPage) //Is this possible?
                            .addAction(action)
                            .setBackground(BitmapFactory.decodeResource(getResources(), R.drawable.soccer_background_big))
            );

РЕДАКТИРОВАТЬ

Глядя на Messenger Wear-app кажется возможным? Приложение Messenger для Android Wear

Например, на втором экране отображается список сообщений.


person tim    schedule 24.09.2015    source источник
comment
Почему вы не показываете данные на первой странице? Насколько мне известно, в уведомлениях об износе нет второй страницы.   -  person Psytho    schedule 24.09.2015
comment
Вы можете добавить страницы, если хотите, в соответствии с документацией. Однако это ограничивает вас определенным дизайном. Я хочу реализовать свой собственный дизайн.   -  person tim    schedule 24.09.2015


Ответы (1)


У меня была такая же проблема. Мое решение состояло в том, чтобы реализовать действие и добавить к этому действию пользовательский макет. Выполните этот шаг.

Шаг 1. Создайте собственный макет в модуле одежды. Пример: customlayout.xml

Шаг 2: Создайте действие в модуле износа:

    public class WearNotificationActivity extends Activity{

    private ImageView mSomeButton;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.customlayout);

        mSomeButton= (ImageView) this.findViewById(R.id.somebutton);



        mSomeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //do something here
            }
        });

    }

}

Шаг 3. Отправьте нужные данные со своего телефона на часы:

    public class MainActivity extends Activity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{

     private GoogleApiClient mGoogleApiClient;
     private Button mSomeButton;

    @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.mainlayout);
            mSomeButton=(Button) findViewById(R.id.somebutton);

            mGoogleApiClient = new GoogleApiClient.Builder(this)
                            .addApi(AppIndex.APP_INDEX_API)
                            .addApi(Wearable.API)
                            .addConnectionCallbacks(this)
                            .addOnConnectionFailedListener(this)
                            .build();
            mSomeButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
               sendToWear("title","description");
            }
        });

    }
    @Override
        public void onStart() {
            // TODO Auto-generated method stub
            super.onStart();
            if(!mGoogleApiClient.isConnected()) {
                mGoogleApiClient.connect();
            }

        }
    @Override
    public void onDestroy() {
        super.onDestroy();
        if(mGoogleApiClient!=null) {
            mGoogleApiClient.disconnect();
        }    

    }
    public void sendToWear(String title, String description){        
        PutDataMapRequest putDataMapReq = PutDataMapRequest.create("/wear");
        putDataMapReq.getDataMap().putString("title", title);
        putDataMapReq.getDataMap().putString("description", description);                
        Wearable.DataApi.putDataItem(mGoogleApiClient, putDataRequest);
    }

}

Шаг 4. Получите данные в своей одежде и сделайте уведомление. Для этого вам нужно создать класс в модуле износа, который расширяется для WearableListenerService, и добавить этот класс в свой манифест износа.

 public class NotificationUpdateService extends WearableListenerService
        implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,
        ResultCallback<DataApi.DeleteDataItemsResult> {

    private GoogleApiClient mGoogleApiClient;

    @Override
    public void onCreate() {
        super.onCreate();
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(Wearable.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
    }


    @Override
    public void onDataChanged(DataEventBuffer dataEvents) {
        for (DataEvent dataEvent : dataEvents) {
            if (dataEvent.getType() == DataEvent.TYPE_CHANGED) {
                DataItem item = dataEvent.getDataItem();
                if (item.getUri().getPath().compareTo("/wear") == 0) {
                    DataMap dataMap = DataMapItem.fromDataItem(item).getDataMap();
                    String title = dataMap.getString("title");
                    String description=dataMap.getString("description");
                    buildWearableOnlyNotification(title, description)

                }
            } else if (dataEvent.getType() == DataEvent.TYPE_DELETED) {

            }
        }
    }

    /**
     * Builds a simple notification on the wearable.
     */
    private void buildWearableOnlyNotification(String title, String content) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.ic_launcher)
                    .setOngoing(true)
                    .setPriority(NotificationCompat.PRIORITY_MAX)
                    .setVibrate(new long[]{10, 10, 10, 10, 10})
                    .setContentTitle(title)
                    .setContentText(content);
            Intent notificationIntent = new Intent(this, WearNotificationActivity.class);
            PendingIntent pendingNotificationIntent =
                    PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

            NotificationCompat.Builder secondpage =
                    new NotificationCompat.Builder(this)
                            .setSmallIcon(R.drawable.ic_launcher)
                            .extend(new NotificationCompat.WearableExtender()
                                            .setDisplayIntent(pendingNotificationIntent)
                                            .setCustomSizePreset(NotificationCompat.WearableExtender.SIZE_FULL_SCREEN)
                            );            
            mNotificationBuilder = new NotificationCompat.WearableExtender()
                    .addPage(secondpage.build()).extend(builder);
            Notification notification=mNotificationBuilder.build();
            ((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
                    .notify(Constants.WATCH_ONLY_ID, notification);
    }

    @Override
    public void onConnected(Bundle bundle) {

    }

    @Override
    public void onConnectionSuspended(int i) {
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
    }


}

И в вашем манифесте:

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@android:style/Theme.DeviceDefault" >
    <meta-data android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".WearNotificationActivity"
        android:exported="true"
        android:allowEmbedded="true"
        android:taskAffinity=""
        android:theme="@android:style/Theme.DeviceDefault.Light"
        >
    </activity>
    <service android:name=".NotificationUpdateService">
        <intent-filter>
            <action
                android:name="com.google.android.gms.wearable.BIND_LISTENER" />
        </intent-filter>
    </service>
</application>

Наконец, вам нужно добавить все зависимости в свой телефон и носить Gradle.

Телефон:

compile 'com.google.android.gms:play-services-wearable:7.5.0'
compile 'com.android.support:support-v4:23.1.0'
wearApp project(':wearmodule')

Носить:

compile 'com.google.android.support:wearable:1.3.0'
provided 'com.google.android.wearable:wearable:+'
compile 'com.google.android.gms:play-services-wearable:8.1.0'

Я надеюсь, что это было полезно для вас.

person OscarBudo    schedule 29.10.2015