summaryrefslogtreecommitdiffstats
path: root/samples/browseable/LNotifications/src/com.example.android.lnotifications/OtherMetadataFragment.java
blob: 51616e700f495ecda467e9803850fa9a4ebfaff4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
/*
* Copyright 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.android.lnotifications;

import android.app.Activity;
import android.app.Fragment;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.util.Random;

/**
 * Fragment that demonstrates how to attach metadata introduced in Android L, such as
 * priority data, notification category and person data.
 */
public class OtherMetadataFragment extends Fragment {

    private static final String TAG = OtherMetadataFragment.class.getSimpleName();

    /**
     * Request code used for picking a contact.
     */
    public static final int REQUEST_CODE_PICK_CONTACT = 1;

    /**
     * Incremental Integer used for ID for notifications so that each notification will be
     * treated differently.
     */
    private Integer mIncrementalNotificationId = Integer.valueOf(0);

    private NotificationManager mNotificationManager;

    /**
     * Button to show a notification.
     */
    private Button mShowNotificationButton;

    /**
     *  Spinner that holds possible categories used for a notification as
     *  {@link Notification.Builder#setCategory(String)}.
     */
    private Spinner mCategorySpinner;

    /**
     * Spinner that holds possible priorities used for a notification as
     * {@link Notification.Builder#setPriority(int)}.
     */
    private Spinner mPrioritySpinner;

    /**
     * Holds a URI for the person to be attached to the notification.
     */
    //@VisibleForTesting
    Uri mContactUri;

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment NotificationFragment.
     */
    public static OtherMetadataFragment newInstance() {
        OtherMetadataFragment fragment = new OtherMetadataFragment();
        fragment.setRetainInstance(true);
        return fragment;
    }

    public OtherMetadataFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mNotificationManager = (NotificationManager) getActivity().getSystemService(Context
                .NOTIFICATION_SERVICE);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_other_metadata, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mShowNotificationButton = (Button) view.findViewById(R.id.show_notification_button);
        mShowNotificationButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Priority selectedPriority = (Priority) mPrioritySpinner.getSelectedItem();
                Category selectedCategory = (Category) mCategorySpinner.getSelectedItem();
                showNotificationClicked(selectedPriority, selectedCategory, mContactUri);
            }
        });

        mCategorySpinner = (Spinner) view.findViewById(R.id.category_spinner);
        ArrayAdapter<Category> categoryArrayAdapter = new ArrayAdapter<Category>(getActivity(),
                android.R.layout.simple_spinner_item, Category.values());
        categoryArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mCategorySpinner.setAdapter(categoryArrayAdapter);

        mPrioritySpinner = (Spinner) view.findViewById(R.id.priority_spinner);
        ArrayAdapter<Priority> priorityArrayAdapter = new ArrayAdapter<Priority>(getActivity(),
                android.R.layout.simple_spinner_item, Priority.values());
        priorityArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mPrioritySpinner.setAdapter(priorityArrayAdapter);

        view.findViewById(R.id.attach_person).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                findContact();
            }
        });

        view.findViewById(R.id.contact_entry).setVisibility(View.GONE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_CODE_PICK_CONTACT:
                if (resultCode == Activity.RESULT_OK) {
                    Uri contactUri = data.getData();
                    mContactUri = contactUri;
                    updateContactEntryFromUri(contactUri);
                }
                break;
        }
    }

    /**
     * Invoked when {@link #mShowNotificationButton} is clicked.
     * Creates a new notification and sets metadata passed as arguments.
     *
     * @param priority   The priority metadata.
     * @param category   The category metadata.
     * @param contactUri The URI to be added to the new notification as metadata.
     *
     * @return A Notification instance.
     */
    //@VisibleForTesting
    Notification createNotification(Priority priority, Category category, Uri contactUri) {
        Notification.Builder notificationBuilder = new Notification.Builder(getActivity())
                .setContentTitle("Notification with other metadata")
                .setSmallIcon(R.drawable.ic_launcher_notification)
                .setPriority(priority.value)
                .setCategory(category.value)
                .setContentText(String.format("Category %s, Priority %s", category.value,
                        priority.name()));
        if (contactUri != null) {
            notificationBuilder.addPerson(contactUri.toString());
            Bitmap photoBitmap = loadBitmapFromContactUri(contactUri);
            if (photoBitmap != null) {
                notificationBuilder.setLargeIcon(photoBitmap);
            }
        }
        return notificationBuilder.build();
    }

    /**
     * Invoked when {@link #mShowNotificationButton} is clicked.
     * Creates a new notification and sets metadata passed as arguments.
     *
     * @param priority   The priority metadata.
     * @param category   The category metadata.
     * @param contactUri The URI to be added to the new notification as metadata.
     */
    private void showNotificationClicked(Priority priority, Category category, Uri contactUri) {
        // Assigns a unique (incremented) notification ID in order to treat each notification as a
        // different one. This helps demonstrate how a priority flag affects ordering.
        mIncrementalNotificationId = new Integer(mIncrementalNotificationId + 1);
        mNotificationManager.notify(mIncrementalNotificationId, createNotification(priority,
                category, contactUri));
        Toast.makeText(getActivity(), "Show Notification clicked", Toast.LENGTH_SHORT).show();
    }

    private void findContact() {
        Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
        startActivityForResult(intent, REQUEST_CODE_PICK_CONTACT);
    }

    /**
     * Returns a {@link Bitmap} from the Uri specified as the argument.
     *
     * @param contactUri The Uri from which the result Bitmap is created.
     * @return The {@link Bitmap} instance retrieved from the contactUri.
     */
    private Bitmap loadBitmapFromContactUri(Uri contactUri) {
        if (contactUri == null) {
            return null;
        }
        Bitmap result = null;
        Cursor cursor = getActivity().getContentResolver().query(contactUri, null, null, null,
                null);
        if (cursor != null && cursor.moveToFirst()) {
            int idx = cursor.getColumnIndex(ContactsContract.Contacts.PHOTO_ID);
            String hasPhoto = cursor.getString(idx);
            Uri photoUri = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo
                    .CONTENT_DIRECTORY);
            if (hasPhoto != null) {
                try {
                    result = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver()
                            , photoUri);
                } catch (IOException e) {
                    Log.e(TAG, String.format("Failed to load resource. Uri %s", photoUri), e);
                }
            } else {
                Drawable defaultContactDrawable = getActivity().getResources().getDrawable(R
                        .drawable.ic_contact_picture);
                result = ((BitmapDrawable) defaultContactDrawable).getBitmap();
            }
        }
        return result;
    }

    /**
     * Updates the Contact information on the screen when a contact is picked.
     *
     * @param contactUri The Uri from which the contact is retrieved.
     */
    private void updateContactEntryFromUri(Uri contactUri) {
        Cursor cursor = getActivity().getContentResolver().query(contactUri, null, null, null,
                null);
        if (cursor != null && cursor.moveToFirst()) {
            int idx = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
            String name = cursor.getString(idx);
            idx = cursor.getColumnIndex(ContactsContract.Contacts.PHOTO_ID);
            String hasPhoto = cursor.getString(idx);

            Uri photoUri = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo
                    .CONTENT_DIRECTORY);
            ImageView contactPhoto = (ImageView) getActivity().findViewById(R.id.contact_photo);
            if (hasPhoto != null) {
                contactPhoto.setImageURI(photoUri);
            } else {
                Drawable defaultContactDrawable = getActivity().getResources().getDrawable(R
                        .drawable.ic_contact_picture);
                contactPhoto.setImageDrawable(defaultContactDrawable);
            }
            TextView contactName = (TextView) getActivity().findViewById(R.id.contact_name);
            contactName.setText(name);

            getActivity().findViewById(R.id.contact_entry).setVisibility(View.VISIBLE);
            getActivity().findViewById(R.id.attach_person).setVisibility(View.GONE);
            getActivity().findViewById(R.id.click_to_change).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    findContact();
                }
            });
            Log.i(TAG, String.format("Contact updated. Name %s, PhotoUri %s", name, photoUri));
        }
    }

    /**
     * Enum indicating possible categories in {@link Notification} used from
     * {@link #mCategorySpinner}.
     */
    //@VisibleForTesting
    static enum Category {
        ALARM("alarm"),
        CALL("call"),
        EMAIL("email"),
        ERROR("err"),
        EVENT("event"),
        MESSAGE("msg"),
        PROGRESS("progress"),
        PROMO("promo"),
        RECOMMENDATION("recommendation"),
        SERVICE("service"),
        SOCIAL("social"),
        STATUS("status"),
        SYSTEM("sys"),
        TRANSPORT("transport");

        private final String value;

        Category(String value) {
            this.value = value;
        }

        @Override
        public String toString() {
            return value;
        }
    }

    /**
     * Enum indicating possible priorities in {@link Notification} used from
     * {@link #mPrioritySpinner}.
     */
    //@VisibleForTesting
    static enum Priority {
        DEFAULT(Notification.PRIORITY_DEFAULT),
        MAX(Notification.PRIORITY_MAX),
        HIGH(Notification.PRIORITY_HIGH),
        LOW(Notification.PRIORITY_LOW),
        MIN(Notification.PRIORITY_MIN);

        private final int value;

        Priority(int value) {
            this.value = value;
        }
    }
}