SimpleJobIntentService.java revision f27b1ffc67228d73326ec3426fef4c9db75cd6fd
1/*
2 * Copyright (C) 2017 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.example.android.supportv4.app;
18
19//BEGIN_INCLUDE(complete)
20import android.content.Context;
21import android.content.Intent;
22import android.os.Handler;
23import android.os.SystemClock;
24import android.support.v4.app.JobIntentService;
25import android.util.Log;
26import android.widget.Toast;
27
28/**
29 * Example implementation of a JobIntentService.
30 */
31public class SimpleJobIntentService extends JobIntentService {
32    /**
33     * Unique job ID for this service.
34     */
35    static final int JOB_ID = 1000;
36
37    /**
38     * Convenience method for enqueuing work in to this service.
39     */
40    static void enqueueWork(Context context, Intent work) {
41        enqueueWork(context, SimpleJobIntentService.class, JOB_ID, work);
42    }
43
44    @Override
45    protected void onHandleWork(Intent intent) {
46        // We have received work to do.  The system or framework is already
47        // holding a wake lock for us at this point, so we can just go.
48        Log.i("SimpleJobIntentService", "Executing work: " + intent);
49        String label = intent.getStringExtra("label");
50        if (label == null) {
51            label = intent.toString();
52        }
53        toast("Executing: " + label);
54        for (int i = 0; i < 5; i++) {
55            Log.i("SimpleJobIntentService", "Running service " + (i + 1)
56                    + "/5 @ " + SystemClock.elapsedRealtime());
57            try {
58                Thread.sleep(1000);
59            } catch (InterruptedException e) {
60            }
61        }
62        Log.i("SimpleJobIntentService", "Completed service @ " + SystemClock.elapsedRealtime());
63    }
64
65    @Override
66    public void onDestroy() {
67        super.onDestroy();
68        toast("All work complete");
69    }
70
71    final Handler mHandler = new Handler();
72
73    // Helper for showing tests
74    void toast(final CharSequence text) {
75        mHandler.post(new Runnable() {
76            @Override public void run() {
77                Toast.makeText(SimpleJobIntentService.this, text, Toast.LENGTH_SHORT).show();
78            }
79        });
80    }
81}
82//END_INCLUDE(complete)
83