SliceBroadcastReceiver.java revision def582a5836579a3fadabfdbe4413cb1652bf098
1/*
2 * Copyright 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.androidx.slice.demos;
18
19import static android.app.slice.Slice.EXTRA_TOGGLE_STATE;
20
21import static androidx.slice.core.SliceHints.EXTRA_RANGE_VALUE;
22
23import static com.example.androidx.slice.demos.SampleSliceProvider.getUri;
24
25import android.content.BroadcastReceiver;
26import android.content.Context;
27import android.content.Intent;
28import android.net.wifi.WifiManager;
29import android.os.Handler;
30import android.widget.Toast;
31
32/**
33 * Responds to actions performed on slices and notifies slices of updates in state changes.
34 */
35public class SliceBroadcastReceiver extends BroadcastReceiver {
36
37    @Override
38    public void onReceive(Context context, Intent i) {
39        String action = i.getAction();
40        switch (action) {
41            case SampleSliceProvider.ACTION_WIFI_CHANGED:
42                WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
43                boolean newState = i.getBooleanExtra(EXTRA_TOGGLE_STATE, wm.isWifiEnabled());
44                wm.setWifiEnabled(newState);
45                // Wait a bit for wifi to update (TODO: is there a better way to do this?)
46                Handler h = new Handler();
47                h.postDelayed(() -> {
48                    context.getContentResolver().notifyChange(getUri("wifi", context), null);
49                }, 1000);
50                break;
51            case SampleSliceProvider.ACTION_TOAST:
52                String message = i.getExtras().getString(SampleSliceProvider.EXTRA_TOAST_MESSAGE,
53                        "no message");
54                Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
55                break;
56            case SampleSliceProvider.ACTION_TOAST_RANGE_VALUE:
57                int range = i.getExtras().getInt(EXTRA_RANGE_VALUE, 0);
58                Toast.makeText(context, "value: " + range, Toast.LENGTH_SHORT).show();
59                break;
60        }
61    }
62}
63