این وبسایت یک نسخه آزمایشی از سایت developer android می‌باشد که در حال ترجمه می‌باشد.
برای پیوستن به تیم ترجمه و خواندن مستندات اینجا کلیک کنید.
SynchronizedNotifications / Wearable / src / com.example.android.wearable.synchronizednotifications /

NotificationUpdateService.java

1
/*
2
 * Copyright (C) 2014 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
 *      http://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.android.wearable.synchronizednotifications;
18
 
19
import static com.google.android.gms.wearable.PutDataRequest.WEAR_URI_SCHEME;
20
 
21
import android.app.Notification;
22
import android.app.NotificationManager;
23
import android.app.PendingIntent;
24
import android.content.Intent;
25
import android.net.Uri;
26
import android.os.Bundle;
27
import android.util.Log;
28
 
29
import com.example.android.wearable.synchronizednotifications.common.Constants;
30
import com.google.android.gms.common.ConnectionResult;
31
import com.google.android.gms.common.api.GoogleApiClient;
32
import com.google.android.gms.common.api.ResultCallback;
33
import com.google.android.gms.wearable.DataApi;
34
import com.google.android.gms.wearable.DataEvent;
35
import com.google.android.gms.wearable.DataEventBuffer;
36
import com.google.android.gms.wearable.DataMap;
37
import com.google.android.gms.wearable.DataMapItem;
38
import com.google.android.gms.wearable.PutDataMapRequest;
39
import com.google.android.gms.wearable.Wearable;
40
import com.google.android.gms.wearable.WearableListenerService;
41
 
42
/**
43
 * A {@link com.google.android.gms.wearable.WearableListenerService} that will be invoked when a
44
 * DataItem is added or deleted. The creation of a new DataItem will be interpreted as a request to
45
 * create a new notification and the removal of that DataItem is interpreted as a request to
46
 * dismiss that notification.
47
 */
48
public class NotificationUpdateService extends WearableListenerService
49
        implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,
50
        ResultCallback<DataApi.DeleteDataItemsResult> {
51
 
52
    private static final String TAG = "NotificationUpdate";
53
    private GoogleApiClient mGoogleApiClient;
54
 
55
    @Override
56
    public void onCreate() {
57
        super.onCreate();
58
        mGoogleApiClient = new GoogleApiClient.Builder(this)
59
                .addApi(Wearable.API)
60
                .addConnectionCallbacks(this)
61
                .addOnConnectionFailedListener(this)
62
                .build();
63
    }
64
 
65
    @Override
66
    public int onStartCommand(Intent intent, int flags, int startId) {
67
        if (null != intent) {
68
            String action = intent.getAction();
69
            if (Constants.ACTION_DISMISS.equals(action)) {
70
                // We need to dismiss the wearable notification. We delete the data item that
71
                // created the notification and that is how we inform the phone
72
                int notificationId = intent.getIntExtra(Constants.KEY_NOTIFICATION_ID, -1);
73
                if (notificationId == Constants.BOTH_ID) {
74
                    dismissPhoneNotification(notificationId);
75
                }
76
            }
77
        }
78
        return super.onStartCommand(intent, flags, startId);
79
    }
80
 
81
    /**
82
     * Dismisses the phone notification, via a {@link android.app.PendingIntent} that is triggered
83
     * when the user dismisses the local notification. Deleting the corresponding data item notifies
84
     * the {@link com.google.android.gms.wearable.WearableListenerService} on the phone that the
85
     * matching notification on the phone side should be removed.
86
     */
87
    private void dismissPhoneNotification(int id) {
88
        mGoogleApiClient.connect();
89
    }
90
 
91
    @Override
92
    public void onDataChanged(DataEventBuffer dataEvents) {
93
        for (DataEvent dataEvent : dataEvents) {
94
            if (dataEvent.getType() == DataEvent.TYPE_CHANGED) {
95
                DataMap dataMap = DataMapItem.fromDataItem(dataEvent.getDataItem()).getDataMap();
96
                String content = dataMap.getString(Constants.KEY_CONTENT);
97
                String title = dataMap.getString(Constants.KEY_TITLE);
98
                if (Constants.WATCH_ONLY_PATH.equals(dataEvent.getDataItem().getUri().getPath())) {
99
                    buildWearableOnlyNotification(title, content, false);
100
                } else if (Constants.BOTH_PATH.equals(dataEvent.getDataItem().getUri().getPath())) {
101
                    buildWearableOnlyNotification(title, content, true);
102
                }
103
            } else if (dataEvent.getType() == DataEvent.TYPE_DELETED) {
104
                if (Log.isLoggable(TAG, Log.DEBUG)) {
105
                    Log.d(TAG, "DataItem deleted: " + dataEvent.getDataItem().getUri().getPath());
106
                }
107
                if (Constants.BOTH_PATH.equals(dataEvent.getDataItem().getUri().getPath())) {
108
                    // Dismiss the corresponding notification
109
                    ((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
110
                            .cancel(Constants.WATCH_ONLY_ID);
111
                }
112
            }
113
        }
114
    }
115
 
116
    /**
117
     * Builds a simple notification on the wearable.
118
     */
119
    private void buildWearableOnlyNotification(String title, String content,
120
            boolean withDismissal) {
121
        Notification.Builder builder = new Notification.Builder(this)
122
                .setSmallIcon(R.drawable.ic_launcher)
123
                .setContentTitle(title)
124
                .setContentText(content);
125
 
126
        if (withDismissal) {
127
            Intent dismissIntent = new Intent(Constants.ACTION_DISMISS);
128
            dismissIntent.putExtra(Constants.KEY_NOTIFICATION_ID, Constants.BOTH_ID);
129
            PendingIntent pendingIntent = PendingIntent
130
                    .getService(this, 0, dismissIntent, PendingIntent.FLAG_UPDATE_CURRENT);
131
            builder.setDeleteIntent(pendingIntent);
132
        }
133
 
134
        ((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
135
                .notify(Constants.WATCH_ONLY_ID, builder.build());
136
    }
137
 
138
    @Override
139
    public void onConnected(Bundle bundle) {
140
        final Uri dataItemUri =
141
                new Uri.Builder().scheme(WEAR_URI_SCHEME).path(Constants.BOTH_PATH).build();
142
        if (Log.isLoggable(TAG, Log.DEBUG)) {
143
            Log.d(TAG, "Deleting Uri: " + dataItemUri.toString());
144
        }
145
        Wearable.DataApi.deleteDataItems(
146
                mGoogleApiClient, dataItemUri).setResultCallback(this);
147
    }
148
 
149
    @Override
150
    public void onConnectionSuspended(int i) {
151
    }
152
 
153
    @Override
154
    public void onConnectionFailed(ConnectionResult connectionResult) {
155
    }
156
 
157
    @Override
158
    public void onResult(DataApi.DeleteDataItemsResult deleteDataItemsResult) {