wangzhibo
4 天以前 ae6f40460dcd56af6c5f60ba52c883854c3bac55
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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
/*  Copyright (C) 2016-2024 Andreas Shimokawa, Andrzej Surowiec, Arjan
    Schrijver, Carsten Pfeiffer, Daniel Dakhno, Daniele Gobbetti, Ganblejs,
    gfwilliams, Gordon Williams, Johannes Tysiak, José Rebelo, marco.altomonte,
    Petr Vaněk, Taavi Eomäe
 
    This file is part of Gadgetbridge.
 
    Gadgetbridge is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published
    by the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
 
    Gadgetbridge is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.
 
    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>. */
package nodomain.freeyourgadget.gadgetbridge.activities;
 
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
 
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
 
import com.google.android.material.floatingactionbutton.FloatingActionButton;
 
import java.io.Serializable;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
 
import nodomain.freeyourgadget.gadgetbridge.GBApplication;
import nodomain.freeyourgadget.gadgetbridge.R;
import nodomain.freeyourgadget.gadgetbridge.activities.devicesettings.DeviceSettingsPreferenceConst;
import nodomain.freeyourgadget.gadgetbridge.activities.discovery.DiscoveryActivityV2;
import nodomain.freeyourgadget.gadgetbridge.adapter.GBDeviceAdapterv2;
import nodomain.freeyourgadget.gadgetbridge.database.DBAccess;
import nodomain.freeyourgadget.gadgetbridge.database.DBHandler;
import nodomain.freeyourgadget.gadgetbridge.devices.DeviceCoordinator;
import nodomain.freeyourgadget.gadgetbridge.devices.DeviceManager;
import nodomain.freeyourgadget.gadgetbridge.impl.GBDevice;
import nodomain.freeyourgadget.gadgetbridge.model.ActivitySample;
import nodomain.freeyourgadget.gadgetbridge.model.DailyTotals;
import nodomain.freeyourgadget.gadgetbridge.model.DeviceService;
import nodomain.freeyourgadget.gadgetbridge.util.GB;
 
public class DevicesFragment extends Fragment {
 
    private DeviceManager deviceManager;
    private GBDeviceAdapterv2 mGBDeviceAdapter;
    private RecyclerView deviceListView;
    private FloatingActionButton fab;
    List<GBDevice> deviceList;
    private  HashMap<String, DailyTotals> deviceActivityHashMap = new HashMap();
 
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            final GBDevice device = intent.getParcelableExtra(GBDevice.EXTRA_DEVICE);
            switch (Objects.requireNonNull(action)) {
                case DeviceManager.ACTION_DEVICES_CHANGED:
                case GBApplication.ACTION_NEW_DATA:
                    if (action.equals(GBApplication.ACTION_NEW_DATA)) {
                        createRefreshTask("get activity data", requireContext(), device).execute();
                    }
                    if (device != null) {
                        // Refresh only this device
                        refreshSingleDevice(device);
                    } else {
                        refreshPairedDevices();
                    }
 
                    break;
                case DeviceService.ACTION_REALTIME_SAMPLES:
                    handleRealtimeSample(device, intent.getSerializableExtra(DeviceService.EXTRA_REALTIME_SAMPLE));
                    break;
            }
        }
    };
 
    private void handleRealtimeSample(GBDevice device, Serializable extra) {
        if (extra instanceof ActivitySample) {
            ActivitySample sample = (ActivitySample) extra;
            if (HeartRateUtils.getInstance().isValidHeartRateValue(sample.getHeartRate())) {
                if (device != null) {
                    refreshSingleDevice(device);
                } else {
                    refreshPairedDevices();
                }
            }
        }
    }
 
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View currentView = inflater.inflate(R.layout.fragment_devices, container, false);
 
        deviceManager = ((GBApplication) getActivity().getApplication()).getDeviceManager();
 
        deviceListView = currentView.findViewById(R.id.deviceListView);
        deviceListView.setHasFixedSize(true);
        deviceListView.setLayoutManager(new LinearLayoutManager(currentView.getContext()));
 
        deviceList = deviceManager.getDevices();
        mGBDeviceAdapter = new GBDeviceAdapterv2(currentView.getContext(), deviceList, deviceActivityHashMap);
        mGBDeviceAdapter.setHasStableIds(true);
 
        deviceListView.setAdapter(this.mGBDeviceAdapter);
 
        // get activity data asynchronously, this fills the deviceActivityHashMap
        // and calls refreshPairedDevices() → notifyDataSetChanged
        deviceListView.post(new Runnable() {
            @Override
            public void run() {
                if (getContext() != null) {
                    createRefreshTask("get activity data", getContext(), null).execute();
                }
            }
        });
 
        fab = currentView.findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                launchDiscoveryActivity();
            }
        });
 
        showFabIfNeccessary();
 
        /* uncomment to enable fixed-swipe to reveal more actions
 
        ItemTouchHelper swipeToDismissTouchHelper = new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(
                ItemTouchHelper.LEFT , ItemTouchHelper.RIGHT) {
            @Override
            public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
                if(dX>50)
                    dX = 50;
                super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
 
            }
 
            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                GB.toast(getBaseContext(), "onMove", Toast.LENGTH_LONG, GB.ERROR);
 
                return false;
            }
 
            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
                GB.toast(getBaseContext(), "onSwiped", Toast.LENGTH_LONG, GB.ERROR);
 
            }
 
            @Override
            public void onChildDrawOver(Canvas c, RecyclerView recyclerView,
                                        RecyclerView.ViewHolder viewHolder, float dX, float dY,
                                        int actionState, boolean isCurrentlyActive) {
            }
        });
 
        swipeToDismissTouchHelper.attachToRecyclerView(deviceListView);
        */
 
        registerForContextMenu(deviceListView);
 
        IntentFilter filterLocal = new IntentFilter();
        filterLocal.addAction(GBApplication.ACTION_NEW_DATA);
        filterLocal.addAction(DeviceManager.ACTION_DEVICES_CHANGED);
        filterLocal.addAction(DeviceService.ACTION_REALTIME_SAMPLES);
        LocalBroadcastManager.getInstance(requireContext()).registerReceiver(mReceiver, filterLocal);
 
        refreshPairedDevices();
 
        if (GB.isBluetoothEnabled() && deviceList.isEmpty() && Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            startActivity(new Intent(getActivity(), DiscoveryActivityV2.class));
        }
 
        return currentView;
    }
 
    private void launchDiscoveryActivity() {
        startActivity(new Intent(getActivity(), DiscoveryActivityV2.class));
    }
 
    private void showFabIfNeccessary() {
        if (GBApplication.getPrefs().getBoolean("display_add_device_fab", true)) {
            fab.show();
        } else {
            if (deviceManager.getDevices().size() < 1) {
                fab.show();
            } else {
                fab.hide();
            }
        }
    }
 
    @Override
    public void onDestroy() {
        if (deviceListView != null) unregisterForContextMenu(deviceListView);
        LocalBroadcastManager.getInstance(requireContext()).unregisterReceiver(mReceiver);
        super.onDestroy();
    }
 
    private DailyTotals getSteps(GBDevice device, DBHandler db) {
        Calendar day = GregorianCalendar.getInstance();
 
        return DailyTotals.getDailyTotalsForDevice(device, day, db);
    }
 
    public void refreshPairedDevices() {
        if (mGBDeviceAdapter != null) {
            mGBDeviceAdapter.rebuildFolders();
            mGBDeviceAdapter.notifyDataSetChanged();
        }
    }
 
    public void refreshSingleDevice(final GBDevice device) {
        if (mGBDeviceAdapter != null) {
            mGBDeviceAdapter.refreshSingleDevice(device);
        }
    }
 
    public RefreshTask createRefreshTask(String task, Context context, GBDevice device) {
        return new RefreshTask(task, context, device);
    }
 
    public class RefreshTask extends DBAccess {
        private final GBDevice device;
 
        public RefreshTask(final String task, final Context context, final GBDevice device) {
            super(task, context);
            this.device = device;
        }
 
        @Override
        protected void doInBackground(final DBHandler db) {
            if (device != null) {
                updateDevice(db, device);
            } else {
                for (GBDevice gbDevice : deviceList) {
                    updateDevice(db, gbDevice);
                }
            }
        }
 
        private void updateDevice(final DBHandler db, final GBDevice gbDevice) {
            final DeviceCoordinator coordinator = gbDevice.getDeviceCoordinator();
            final boolean showActivityCard = GBApplication.getDevicePrefs(gbDevice).getBoolean(DeviceSettingsPreferenceConst.PREFS_ACTIVITY_IN_DEVICE_CARD, true);
            if (coordinator.supportsActivityTracking() && showActivityCard) {
                final DailyTotals stepsAndSleepData = getSteps(gbDevice, db);
                deviceActivityHashMap.put(gbDevice.getAddress(), stepsAndSleepData);
            }
        }
 
        @Override
        protected void onPostExecute(final Object o) {
            if (device != null) {
                refreshSingleDevice(device);
            } else {
                refreshPairedDevices();
            }
        }
    }
}