陈奇
2018-11-15 47f5d71a81a528aff225805d28bf181ce4d6f55d
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
package com.moral.yunfushao.activity;
 
import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v13.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
 
import com.clj.fastble.data.ScanResult;
import com.moral.andbrickslib.baseadapter.headandfooter.DividerItemDecoration;
import com.moral.andbrickslib.baseadapter.recyclerview.MultiItemTypeAdapter;
import com.moral.andbrickslib.utils.ActivityManager;
import com.moral.yunfushao.MainActivity;
import com.moral.yunfushao.MainApp;
import com.moral.yunfushao.R;
import com.moral.yunfushao.adapter.BleDeviceAdapter;
import com.moral.yunfushao.base.BaseActivity;
import com.moral.yunfushao.ble.BluetoothService;
import com.moral.yunfushao.common.AppConfig;
import com.moral.yunfushao.imageload.ImageLoader;
import com.moral.yunfushao.model.EventMessage;
 
import org.greenrobot.eventbus.EventBus;
 
import java.util.ArrayList;
 
/**
 * 蓝牙搜索
 * Created by haijiang on 2017/7/5.
 */
 
public class BLESearchActivity extends BaseActivity {
    private ImageView iv_searchpic, iv_search;
    private LinearLayout ll_tishi;
    private RecyclerView rv_ble;
    private BluetoothService mBluetoothService;
    private boolean isScan = false;
    private ArrayList<ScanResult> scanResultList = new ArrayList<>();
    private BleDeviceAdapter adapter;
 
    @Override
    protected void getBundleExtras(Bundle extras) {
 
    }
 
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        bindService();
    }
 
 
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mBluetoothService != null)
            unbindService();
        EventMessage msg = new EventMessage();
        msg.setType(AppConfig.SET_MAIN_CALL);
        EventBus.getDefault().postSticky(msg);
    }
 
    @Override
    protected int getLayoutId() {
        return R.layout.ac_ble_search_layout;
    }
 
    @Override
    protected void initViews() {
        initTopBar();
        tv_title.setText("设备搜索");
        iv_searchpic = findView(R.id.iv_searchpic);
        iv_search = findView(R.id.iv_search);
        ll_tishi = findView(R.id.ll_tishi);
        rv_ble = findView(R.id.rv_ble);
 
        adapter = new BleDeviceAdapter(rv_ble, R.layout.list_item_deviceble, scanResultList);
        DividerItemDecoration line = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST);
        rv_ble.addItemDecoration(line);
        rv_ble.setLayoutManager(new LinearLayoutManager(rv_ble.getContext()));
        rv_ble.setAdapter(adapter);
        adapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                /**
                 * 连接蓝牙设备
                 */
                if (mBluetoothService != null) {
                    mBluetoothService.cancelScan();
                    /**
                     * 如果连接状态,断开重新连接
                     */
                    if (MainApp.theApp.bleManager != null) {
                        MainApp.theApp.bleManager.closeBluetoothGatt();
                    }
                    sendEventMessage(AppConfig.BLUETOOCH_CHANGE_CONNECT);
                    mBluetoothService.connectDevice(scanResultList.get(position));
                }
            }
 
            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
    }
 
    @Override
    protected void initListener() {
        iv_search.setOnClickListener(this);
        iv_searchpic.setOnClickListener(this);
    }
 
    @Override
    protected void initData() {
 
    }
 
    @Override
    protected void processClick(View view) {
        switch (view.getId()) {
            case R.id.iv_searchpic:
                mBluetoothService.openBlueTooth();
                if (isScan) {
                    if (mBluetoothService != null) {
                        mBluetoothService.cancelScan();
                    }
                    iv_search.setImageResource(R.mipmap.bt_start);
                    iv_searchpic.setImageResource(R.mipmap.bg_end);
                } else {
                    ImageLoader.setGIFByUrl(this, R.mipmap.bg_searching, iv_searchpic);
                    iv_search.setImageResource(R.mipmap.bt_stop);
                    checkPermissions();
                }
                isScan = !isScan;
                break;
            case R.id.tv_left:
                finishA();
                break;
        }
 
    }
 
    @Override
    protected void onErrorPageClick() {
 
    }
 
    private void bindService() {
        Intent bindIntent = new Intent(this, BluetoothService.class);
        this.bindService(bindIntent, mFhrSCon, Context.BIND_AUTO_CREATE);
    }
 
    private void unbindService() {
//        mBluetoothService.setScanCallback(null);
        this.unbindService(mFhrSCon);
    }
 
    private ServiceConnection mFhrSCon = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mBluetoothService = ((BluetoothService.BluetoothBinder) service).getService();
            mBluetoothService.setScanCallback(callback);
            mBluetoothService.openBlueTooth();
//            mBluetoothService.scanDevice();
        }
 
        @Override
        public void onServiceDisconnected(ComponentName name) {
            if (mBluetoothService != null) {
                mBluetoothService.cancelScan();
                mBluetoothService.closeConnect();
                mBluetoothService = null;
            }
        }
    };
 
    private BluetoothService.Callback callback = new BluetoothService.Callback() {
        @Override
        public void onStartScan() {
            scanResultList.clear();
            adapter.notifyDataSetChanged();
            ll_tishi.setVisibility(View.GONE);
            rv_ble.setVisibility(View.VISIBLE);
        }
 
        @Override
        public void onScanning(ScanResult result) {
            System.out.println("chenqi ScanResule " + result.getDevice().getName());
            if (!TextUtils.isEmpty(result.getDevice().getName())) {
                if (result.getDevice().getName().equals("孕妇哨") ||
                        result.getDevice().getName().equals("yunfushao") ||
                        result.getDevice().getName().equals("7drlb") ||
                        result.getDevice().getName().contains("FEI-D")) {
                    scanResultList.add(result);
                    adapter.notifyDataSetChanged();
                }
            }
        }
 
        @Override
        public void onScanComplete() {
            System.out.println("chenqi onScanComplete ");
            iv_search.setImageResource(R.mipmap.bt_start);
            iv_searchpic.setImageResource(R.mipmap.bg_end);
        }
 
        @Override
        public void onConnecting() {
            if (ActivityManager.getActivityManager().isActivityExist(BLESearchActivity.this.getClass().getName())) {
                progressDialog.setTitleText("正在连接...");
                progressDialog.show();
            }
        }
 
        @Override
        public void onConnectFail() {
            if (ActivityManager.getActivityManager().isActivityExist(BLESearchActivity.this.getClass().getName())) {
                progressDialog.dismiss();
            }
            mToatUtils.showSingletonToast("连接失败");
            sendEventMessage(AppConfig.GET_BLE_DISCONNECT);
        }
 
        @Override
        public void onDisConnected() {
            if (ActivityManager.getActivityManager().isActivityExist(BLESearchActivity.this.getClass().getName())) {
                progressDialog.dismiss();
            }
            Log.d("chonglian", "孕妇哨连接断开");
            mToatUtils.showSingletonToast("孕妇哨连接断开");
 
        }
 
        @Override
        public void onServicesDiscovered() {
            Log.d("chonglian", "孕妇哨连接成功");
            sendEventMessage(AppConfig.GET_BLE_SERVICE);
            if (ActivityManager.getActivityManager().isActivityExist(BLESearchActivity.this.getClass().getName())) {
                progressDialog.dismiss();
                finish();
            }
 
        }
    };
 
    private void sendEventMessage(int type) {
        EventMessage msg = new EventMessage();
        msg.setType(type);
        EventBus.getDefault().postSticky(msg);
    }
 
    @Override
    public final void onRequestPermissionsResult(int requestCode,
                                                 @NonNull String[] permissions,
                                                 @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 200:
                onPermissionGranted();
                break;
        }
    }
 
    private void checkPermissions() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {//未开启定位权限
            //开启定位权限,200是标识码
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 200);
        } else {
            if (!isLocationEnable(this)) {
                Intent locationIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                this.startActivityForResult(locationIntent, 2);
            }
            onPermissionGranted();
        }
    }
 
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 2) {
            if (isLocationEnable(this)) {
                //定位已打开的处理
                return;
            } else {
                Intent locationIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                this.startActivityForResult(locationIntent, 2);
                //定位依然没有打开的处理
            }
        } else super.onActivityResult(requestCode, resultCode, data);
    }
 
    /**
     * 判断是否打开定位服务(不是权限)
     *
     * @param context
     * @return
     */
    public static final boolean isLocationEnable(Context context) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        boolean networkProvider = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        boolean gpsProvider = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if (networkProvider || gpsProvider) return true;
        return false;
    }
 
 
    private void onPermissionGranted() {
        if (mBluetoothService == null) {
            bindService();
        } else {
            mBluetoothService.scanDevice();
        }
    }
 
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finishA();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
 
    public void finishA(){
        Intent i = new Intent(this, MainActivity.class);
        ActivityOptionsCompat optionsCompat = ActivityOptionsCompat.makeSceneTransitionAnimation(this, iv_searchpic, "dddd");
        startActivity(i, optionsCompat.toBundle());
        finish();
    }
}