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