summaryrefslogtreecommitdiff
path: root/android/sdl_android/src/main/java/com/smartdevicelink/transport/SdlRouterStatusProvider.java
blob: 078fe104cb1dfc30e95c4a1ecfb220c870f0b0f7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
/*
 * Copyright (c) 2019, Livio, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following
 * disclaimer in the documentation and/or other materials provided with the
 * distribution.
 *
 * Neither the name of the Livio Inc. nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
package com.smartdevicelink.transport;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;

import com.smartdevicelink.util.AndroidTools;
import com.smartdevicelink.util.DebugTool;

import java.lang.ref.WeakReference;

import static com.smartdevicelink.transport.TransportConstants.FOREGROUND_EXTRA;

public class SdlRouterStatusProvider {

    private static final String TAG = "SdlRouterStateProvider";

    private Context context;
    private boolean isBound = false;
    ConnectedStatusCallback cb;
    Messenger routerServiceMessenger = null;
    private ComponentName routerService;
    private int flags = 0;

    final Messenger clientMessenger;

    private final ServiceConnection routerConnection = new ServiceConnection() {

        public void onServiceConnected(ComponentName className, IBinder service) {
            DebugTool.logInfo(TAG, "Bound to service " + className.toString());
            routerServiceMessenger = new Messenger(service);
            isBound = true;
            //So we just established our connection
            //Register with router service
            Message msg = Message.obtain();
            msg.what = TransportConstants.ROUTER_STATUS_CONNECTED_STATE_REQUEST;
            msg.arg1 = flags;
            msg.replyTo = clientMessenger;
            try {
                routerServiceMessenger.send(msg);
            } catch (RemoteException e) {
                e.printStackTrace();
                if (cb != null) {
                    cb.onConnectionStatusUpdate(false, routerService, context);
                }
            }
        }

        public void onServiceDisconnected(ComponentName className) {
            DebugTool.logInfo(TAG, "UN-Bound from service " + className.getClassName());
            routerServiceMessenger = null;
            isBound = false;
        }
    };

    public SdlRouterStatusProvider(Context context, ComponentName service, ConnectedStatusCallback callback) {
        if (context == null || service == null || callback == null) {
            throw new IllegalStateException("Supplied params are not correct. Context == null? " + (context == null) + " ComponentName == null? " + (service == null) + " ConnectedStatusListener == null? " + callback);
        }
        this.context = context;
        this.routerService = service;
        this.cb = callback;
        this.clientMessenger = new Messenger(new ClientHandler(this));

    }

    public void setFlags(int flags) {
        this.flags = flags;
    }

    public void checkIsConnected() {
        if (!AndroidTools.isServiceExported(context, routerService) || !bindToService()) {
            //We are unable to bind to service
            cb.onConnectionStatusUpdate(false, routerService, context);
            unBindFromService();
        }
    }

    public void cancel() {
        if (isBound) {
            unBindFromService();
        }
    }

    private boolean bindToService() {
        if (isBound) {
            return true;
        }
        if (clientMessenger == null) {
            return false;
        }
        Intent bindingIntent = new Intent();
        bindingIntent.setClassName(this.routerService.getPackageName(), this.routerService.getClassName());//This sets an explicit intent
        //Quickly make sure it's just up and running
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
            context.startService(bindingIntent);
        } else {
            bindingIntent.putExtra(FOREGROUND_EXTRA, true);
            SdlBroadcastReceiver.setForegroundExceptionHandler(); //Prevent ANR in case the OS takes too long to start the service
            try {
                context.startForegroundService(bindingIntent);
            } catch (SecurityException | IllegalStateException e) {
                SdlBroadcastReceiver.handleStartServiceException(e);
            }

        }
        bindingIntent.setAction(TransportConstants.BIND_REQUEST_TYPE_STATUS);
        boolean didBind = false;
        try {
            didBind = context.bindService(bindingIntent, routerConnection, Context.BIND_AUTO_CREATE);
        } catch (SecurityException | IllegalStateException e) {
            SdlBroadcastReceiver.handleStartServiceException(e);
        }
        return didBind;
    }

    private void unBindFromService() {
        try {
            if (context != null && routerConnection != null) {
                context.unbindService(routerConnection);
            } else {
                DebugTool.logWarning(TAG, "Unable to unbind from router service, context was null");
            }

        } catch (IllegalArgumentException e) {
            //This is ok
        }
    }

    private void handleRouterStatusConnectedResponse(int connectedStatus) {
        if (cb != null) {
            cb.onConnectionStatusUpdate(connectedStatus == 1, routerService, context);
        }
        unBindFromService();
        routerServiceMessenger = null;
    }

    static class ClientHandler extends Handler {
        final WeakReference<SdlRouterStatusProvider> provider;

        public ClientHandler(SdlRouterStatusProvider provider) {
            super(Looper.getMainLooper());
            this.provider = new WeakReference<>(provider);
        }

        @Override
        public void handleMessage(Message msg) {
            if (provider.get() == null) {
                return;
            }
            switch (msg.what) {
                case TransportConstants.ROUTER_STATUS_CONNECTED_STATE_RESPONSE:
                    provider.get().handleRouterStatusConnectedResponse(msg.arg1);
                    break;
                default:
                    break;
            }
        }
    }

    public interface ConnectedStatusCallback {
        void onConnectionStatusUpdate(boolean connected, ComponentName service, Context context);
    }

}