张海江
2018-01-26 04b72977be56e9cca1eb66883d7217237fb8ab9a
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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
package com.moral.yunfushao;
 
import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Looper;
import android.support.v4.app.FragmentTabHost;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
 
import com.clj.fastble.data.ScanResult;
import com.lzy.okgo.cache.CacheMode;
import com.moral.andbrickslib.utils.FastJsonTools;
import com.moral.andbrickslib.utils.NetworkUtil;
import com.moral.yunfushao.base.BaseActivity;
import com.moral.yunfushao.ble.BluetoothService;
import com.moral.yunfushao.common.API;
import com.moral.yunfushao.common.AppConfig;
import com.moral.yunfushao.fragment.FragmentMonitor;
import com.moral.yunfushao.fragment.FragmentSettings;
import com.moral.yunfushao.fragment.FragmentShoppongMall;
import com.moral.yunfushao.httputils.HttpCallBack;
import com.moral.yunfushao.httputils.HttpUtils;
import com.moral.yunfushao.model.EventMessage;
import com.moral.yunfushao.model.User;
import com.moral.yunfushao.update.UpdateManager;
 
import org.greenrobot.eventbus.EventBus;
 
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;
 
 
public class MainActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks {
    //定义FragmentTabHost对象
    private FragmentTabHost mTabHost;
    //定义一个布局
    private LayoutInflater mLayoutInfater;
    //定义fragments
    private Class fragments[] = {FragmentMonitor.class, FragmentShoppongMall.class, FragmentSettings.class};
    //定义底部按钮图标数组
    private int mIcons[] = {R.drawable.menu1, R.drawable.menu2,R.drawable.menu3};
    //Tab选项卡文字
    private String mTextArray[] = {"辐射监测", "商城","设置"};
    private int index = 0;
    private boolean islogin = false;
 
    private BluetoothService mBluetoothService;
    @Override
    protected void getBundleExtras(Bundle extras) {
        islogin = extras.getBoolean("islogin", false);
    }
 
    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        bindService();
    }
 
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mBluetoothService != null)
            mBluetoothService.closeConnect();
        unbindService();
    }
 
    @Override
    protected void initViews() {
        //实例化布局对象
        mLayoutInfater = LayoutInflater.from(this);
        //实例化TabHost对象,得到TabHost
        mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
        mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
        mTabHost.setDrawingCacheEnabled(false);
 
        //得到fragment的个数
        int count = fragments.length;
 
        for (int i = 0; i < count; i++) {
            //为每一个Tab按钮设置图标、文字和内容
            TabHost.TabSpec tabSpec = mTabHost.newTabSpec(mTextArray[i]).setIndicator(getTabItemView(i));
            //将Tab按钮添加进Tab选项卡中
            mTabHost.addTab(tabSpec, fragments[i], null);
            //设置Tab按钮的背景
            mTabHost.getTabWidget().getChildAt(i).setBackgroundResource(R.mipmap.bg_bottom);
            mTabHost.getTabWidget().setDividerPadding(0);
            mTabHost.getTabWidget().setDividerDrawable(null);
        }
        mTabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
            @Override
            public void onTabChanged(String s) {
            }
        });
        mTabHost.setCurrentTab(index);
    }
 
    @Override
    protected void initListener() {
//        registerBoradcastReceiver();
//        bleHeart();
    }
 
    @Override
    protected void initData() {
        prepare();
        if(MainApp.theApp.bleManager!=null){
            if(MainApp.theApp.bleManager.isSupportBle()){
                MainApp.theApp.bleManager.enableBluetooth();
            }else{
                mToatUtils.showSingletonToast("对不起,您的手机不支持BLE!");
            }
        }else{
            mToatUtils.showSingletonToast("对不起,您的手机不支持BLE!");
        }
    }
 
    @Override
    protected void processClick(View view) {
 
    }
 
    @Override
    protected void onErrorPageClick() {
 
    }
 
    /**
     * 给Tab按钮设置图标和文字
     */
    private View getTabItemView(int indexs) {
        View view = mLayoutInfater.inflate(R.layout.main_tab_item_view, null);
        ImageView imageView = (ImageView) view.findViewById(R.id.icon);
        TextView textView = (TextView) view.findViewById(R.id.tv_text);
        imageView.setImageResource(mIcons[indexs]);
        textView.setText(mTextArray[indexs]);
        return view;
    }
 
    private long clickTime = 0;
 
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - clickTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次后退键退出程序", Toast.LENGTH_SHORT).show();
                clickTime = System.currentTimeMillis();
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
 
 
    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        if (requestCode == WRITE_EXTERNAL_STORAGE) {
            manager.showNoticeDialog();
        }
    }
 
    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
 
    }
 
    private final static int WRITE_EXTERNAL_STORAGE = 0x01;
 
    @AfterPermissionGranted(WRITE_EXTERNAL_STORAGE)
    public void updateAPP() {
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (EasyPermissions.hasPermissions(this, perms)) {
            // Already have permission, do the thing
            manager.showNoticeDialog();
        } else {
            // Do not have permissions, request them now
            EasyPermissions.requestPermissions(this, "温馨提示,版本升级需要写存储权限!",
                    WRITE_EXTERNAL_STORAGE, perms);
        }
    }
 
    UpdateManager manager = new UpdateManager(MainActivity.this);
 
    private class checkUpdateTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            Looper.prepare();
            // 检查软件更新
            manager.checkUpdate();
            Looper.loop();
            return null;
        }
 
        @Override
        protected void onPostExecute(String result) {
        }
 
        @Override
        protected void onPreExecute() {
        }
 
        @Override
        protected void onProgressUpdate(Void... values) {
        }
    }
 
 
    private void prepare() {
        if (!NetworkUtil.isAvailable(this)) {
            mToatUtils.showSingletonToast("网络连接异常");
        } else {
            /**
             * 版本更新
             */
//            if (Build.VERSION.SDK_INT >= 11) {
//                new checkUpdateTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
//            } else {
//                new checkUpdateTask().execute();
//            }
            if (islogin)
                return;
            String url = API.GET_INFO;
            Map<String, String> params = new HashMap<>();
            params.put("phone",MainApp.theApp.sharedPreferencesUtil.getLoginInfo().getPhone());
            HttpUtils.doPost(url, params, CacheMode.DEFAULT, false, new HttpCallBack() {
                @Override
                public void onSuccess(String res, String msg) {
                    User user = FastJsonTools.getJson(res, User.class);
                    if (user != null) {
                        MainApp.theApp.sharedPreferencesUtil.saveLoginInfo(user);
                        MainApp.theApp.userId = user.get_id();
                    }
                }
 
                @Override
                public void showLoadingDialog() {
 
                }
 
                @Override
                public void onFail(int errno,String s) {
 
                }
            });
        }
    }
    public BluetoothService getBluetoothService() {
        return mBluetoothService;
    }
 
    private void bindService() {
        Intent bindIntent = new Intent(this, BluetoothService.class);
        this.bindService(bindIntent, mFhrSCon, Context.BIND_AUTO_CREATE);
    }
 
    private void unbindService() {
        this.unbindService(mFhrSCon);
    }
 
    private ServiceConnection mFhrSCon = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mBluetoothService = ((BluetoothService.BluetoothBinder) service).getService();
            mBluetoothService.setScanCallback(callback);
            String mac = MainApp.theApp.sharedPreferencesUtil.getBLE();
            if(!TextUtils.isEmpty(mac)){
                mBluetoothService.scanAndConnect5(mac);
            }
        }
 
        @Override
        public void onServiceDisconnected(ComponentName name) {
            mBluetoothService = null;
        }
 
 
    };
 
    private BluetoothService.Callback callback = new BluetoothService.Callback() {
        @Override
        public void onStartScan() {
 
        }
 
        @Override
        public void onScanning(ScanResult result) {
 
        }
 
        @Override
        public void onScanComplete() {
 
        }
 
        @Override
        public void onConnecting() {
            progressDialog.setTitleText("正在连接...");
            progressDialog.show();
        }
 
        @Override
        public void onConnectFail() {
            progressDialog.dismiss();
            mToatUtils.showSingletonToast("连接失败");
 
        }
 
        @Override
        public void onDisConnected() {
            progressDialog.dismiss();
            mToatUtils.showSingletonToast("连接断开");
            EventMessage msg = new EventMessage();
            msg.setType(AppConfig.GET_BLE_DISCONNECT);
            EventBus.getDefault().post(msg);
        }
 
        @Override
        public void onServicesDiscovered() {
            progressDialog.dismiss();
            EventMessage msg = new EventMessage();
            msg.setType(AppConfig.GET_BLE_SERVICE);
            EventBus.getDefault().postSticky(msg);
        }
    };
 
//    private void registerBoradcastReceiver() {
//        IntentFilter stateChangeFilter = new IntentFilter(
//                BluetoothAdapter.ACTION_STATE_CHANGED);
//        IntentFilter connectedFilter = new IntentFilter(
//                BluetoothDevice.ACTION_ACL_CONNECTED);
//        IntentFilter disConnectedFilter = new IntentFilter(
//                BluetoothDevice.ACTION_ACL_DISCONNECTED);
//        registerReceiver(stateChangeReceiver, stateChangeFilter);
//        registerReceiver(stateChangeReceiver, connectedFilter);
//        registerReceiver(stateChangeReceiver, disConnectedFilter);
//    }
//
//    private BroadcastReceiver stateChangeReceiver = new BroadcastReceiver() {
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            String action = intent.getAction();
//            if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
//                mToatUtils.showSingletonToast("xxx连接OK");
//            }
//            if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
//                mToatUtils.showSingletonToast("xxx连接断开");
//            }
//            if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
//                mToatUtils.showSingletonToast("xxx连接变化");
//            }
//        }
//    };
 
//    private boolean isFinish = false;
//    Timer timer;
//
//    private void bleHeart() {
//        timer = new Timer();
//        timer.schedule(new TimerTask() {
//            @Override
//            public void run() {
//                if (!isFinish) {
//                    if(!MainApp.theApp.bleManager.isConnected()){
//                        runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                mToatUtils.showSingletonToast("TMD连接断了");
//                            }
//                        });
//                    }
//                }
//            }
//        }, 0, 10000);
//    }
}