1/*
2 * Copyright (C) 2013 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
17package com.android.example.notificationshowcase;
18
19import android.app.IntentService;
20import android.app.PendingIntent;
21import android.content.Context;
22import android.content.Intent;
23import android.os.Handler;
24import android.util.Log;
25import android.widget.Toast;
26
27public class ToastService extends IntentService {
28
29    private static final String TAG = "ToastService";
30
31    private static final String ACTION_TOAST = "toast";
32
33    private Handler handler;
34
35    public ToastService() {
36        super(TAG);
37    }
38    public ToastService(String name) {
39        super(name);
40    }
41
42    @Override
43    public int onStartCommand(Intent intent, int flags, int startId) {
44        handler = new Handler();
45        return super.onStartCommand(intent, flags, startId);
46    }
47
48    @Override
49    protected void onHandleIntent(Intent intent) {
50        Log.v(TAG, "clicked a thing! intent=" + intent.toString());
51        if (intent.hasExtra("text")) {
52            final String text = intent.getStringExtra("text");
53            handler.post(new Runnable() {
54                @Override
55                public void run() {
56                    Toast.makeText(ToastService.this, text, Toast.LENGTH_LONG).show();
57                    Log.v(TAG, "toast " + text);
58                }
59            });
60        }
61    }
62
63    public static PendingIntent getPendingIntent(Context context, int resId) {
64        String text = context.getString(resId);
65        Intent toastIntent = new Intent(context, ToastService.class);
66        toastIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
67        toastIntent.setAction(ACTION_TOAST + ":" + resId); // one per toast message
68        toastIntent.putExtra("text", text);
69        PendingIntent pi = PendingIntent.getService(
70                context, 58, toastIntent, PendingIntent.FLAG_UPDATE_CURRENT);
71        return pi;
72    }
73}
74