1/*
2 * Copyright (C) 2011 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.content;
18
19import android.app.Activity;
20import android.app.Service;
21import android.content.BroadcastReceiver;
22import android.content.Context;
23import android.content.Intent;
24import android.content.IntentFilter;
25import android.os.Bundle;
26import android.os.Handler;
27import android.os.IBinder;
28import android.os.Message;
29import android.view.View;
30import android.view.View.OnClickListener;
31import android.widget.Button;
32import android.widget.TextView;
33
34import androidx.core.app.ServiceCompat;
35import androidx.localbroadcastmanager.content.LocalBroadcastManager;
36
37import com.example.android.supportv4.R;
38
39/**
40 * Demonstrates the use of a LocalBroadcastManager to easily communicate
41 * data from a service to any other interested code.
42 */
43public class LocalServiceBroadcaster extends Activity {
44    static final String ACTION_STARTED = "com.example.android.supportv4.STARTED";
45    static final String ACTION_UPDATE = "com.example.android.supportv4.UPDATE";
46    static final String ACTION_STOPPED = "com.example.android.supportv4.STOPPED";
47
48    LocalBroadcastManager mLocalBroadcastManager;
49    BroadcastReceiver mReceiver;
50
51    @Override
52    protected void onCreate(Bundle savedInstanceState) {
53        super.onCreate(savedInstanceState);
54
55        setContentView(R.layout.local_service_broadcaster);
56
57        // This is where we print the data we get back.
58        final TextView callbackData = (TextView)findViewById(R.id.callback);
59
60        // Put in some initial text.
61        callbackData.setText("No broadcast received yet");
62
63        // We use this to send broadcasts within our local process.
64        mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
65
66        // We are going to watch for interesting local broadcasts.
67        IntentFilter filter = new IntentFilter();
68        filter.addAction(ACTION_STARTED);
69        filter.addAction(ACTION_UPDATE);
70        filter.addAction(ACTION_STOPPED);
71        mReceiver = new BroadcastReceiver() {
72            @Override
73            public void onReceive(Context context, Intent intent) {
74                if (intent.getAction().equals(ACTION_STARTED)) {
75                    callbackData.setText("STARTED");
76                } else if (intent.getAction().equals(ACTION_UPDATE)) {
77                    callbackData.setText("Got update: " + intent.getIntExtra("value", 0));
78                } else if (intent.getAction().equals(ACTION_STOPPED)) {
79                    callbackData.setText("STOPPED");
80                }
81            }
82        };
83        mLocalBroadcastManager.registerReceiver(mReceiver, filter);
84
85        // Watch for button clicks.
86        Button button = (Button)findViewById(R.id.start);
87        button.setOnClickListener(mStartListener);
88        button = (Button)findViewById(R.id.stop);
89        button.setOnClickListener(mStopListener);
90    }
91
92    @Override
93    protected void onDestroy() {
94        super.onDestroy();
95        mLocalBroadcastManager.unregisterReceiver(mReceiver);
96    }
97
98    private OnClickListener mStartListener = new OnClickListener() {
99        @Override
100        public void onClick(View v) {
101            startService(new Intent(LocalServiceBroadcaster.this, LocalService.class));
102        }
103    };
104
105    private OnClickListener mStopListener = new OnClickListener() {
106        @Override
107        public void onClick(View v) {
108            stopService(new Intent(LocalServiceBroadcaster.this, LocalService.class));
109        }
110    };
111
112    public static class LocalService extends Service {
113        LocalBroadcastManager mLocalBroadcastManager;
114        int mCurUpdate;
115
116        static final int MSG_UPDATE = 1;
117
118        Handler mHandler = new Handler() {
119            @Override
120            public void handleMessage(Message msg) {
121                switch (msg.what) {
122                    case MSG_UPDATE: {
123                        mCurUpdate++;
124                        Intent intent = new Intent(ACTION_UPDATE);
125                        intent.putExtra("value", mCurUpdate);
126                        mLocalBroadcastManager.sendBroadcast(intent);
127                        Message nmsg = mHandler.obtainMessage(MSG_UPDATE);
128                        mHandler.sendMessageDelayed(nmsg, 1000);
129                    } break;
130                    default:
131                        super.handleMessage(msg);
132                }
133            }
134        };
135
136        @Override
137        public void onCreate() {
138            super.onCreate();
139            mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
140        }
141
142        @Override
143        public int onStartCommand(Intent intent, int flags, int startId) {
144            // Tell any local interested parties about the start.
145            mLocalBroadcastManager.sendBroadcast(new Intent(ACTION_STARTED));
146
147            // Prepare to do update reports.
148            mHandler.removeMessages(MSG_UPDATE);
149            Message msg = mHandler.obtainMessage(MSG_UPDATE);
150            mHandler.sendMessageDelayed(msg, 1000);
151            return ServiceCompat.START_STICKY;
152        }
153
154        @Override
155        public void onDestroy() {
156            super.onDestroy();
157
158            // Tell any local interested parties about the stop.
159            mLocalBroadcastManager.sendBroadcast(new Intent(ACTION_STOPPED));
160
161            // Stop doing updates.
162            mHandler.removeMessages(MSG_UPDATE);
163        }
164
165        @Override
166        public IBinder onBind(Intent intent) {
167            return null;
168        }
169    }
170}
171