summaryrefslogtreecommitdiffhomepage
path: root/app/src/main/java/com/wireguard/android/ServiceClientFragment.java
blob: 7377151c725b33da43610080dfd55e7e89f2096e (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
package com.wireguard.android;

import android.app.Fragment;
import android.content.Context;

/**
 * Base class for fragments in activities that maintain a connection to a background service.
 */

abstract class ServiceClientFragment<T> extends Fragment implements ServiceConnectionListener<T> {
    private ServiceConnectionProvider<T> provider;
    private T service;

    protected T getService() {
        return service;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        @SuppressWarnings("unchecked")
        final ServiceConnectionProvider<T> localContext = (ServiceConnectionProvider<T>) context;
        provider = localContext;
        service = provider.getService();
        if (service != null)
            onServiceConnected(service);
    }

    @Override
    public void onDetach() {
        super.onDetach();
        provider = null;
    }

    @Override
    public void onStart() {
        super.onStart();
        provider.addServiceConnectionListener(this);
        // Run the handler if the connection state changed while we were not paying attention.
        final T localService = provider.getService();
        if (localService != service) {
            if (localService != null)
                onServiceConnected(localService);
            else
                onServiceDisconnected();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        provider.removeServiceConnectionListener(this);
    }

    @Override
    public void onServiceConnected(T service) {
        this.service = service;
    }

    @Override
    public void onServiceDisconnected() {
        service = null;
    }
}