MainActivity.java 15.1 KB
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 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465

package com.metroapp;

import android.Manifest;
import android.annotation.TargetApi;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.widget.Toast;

import com.allenliu.versionchecklib.core.AllenChecker;
import com.allenliu.versionchecklib.core.VersionParams;
import com.facebook.react.ReactActivity;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.WritableMap;
import com.mehcode.reactnative.splashscreen.SplashScreen;
import com.metroapp.bean.ScanResultBean;
import com.metroapp.constant.Constant;
import com.metroapp.nativemodules.BluetoothModule;
import com.metroapp.utils.XNVersionService;
import com.pgyersdk.update.PgyUpdateManager;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import pub.devrel.easypermissions.EasyPermissions;

@TargetApi(22)
public class MainActivity extends ReactActivity implements EasyPermissions.PermissionCallbacks {

    /**
     * Returns the name of the main component registered from JavaScript.
     * This is used to schedule rendering of the component.
     */
    @Override
    protected String getMainComponentName() {
        return "metroApp";
    }


    // 本地蓝牙适配器
    private BluetoothAdapter mBluetoothAdapter;
    private static ScanResultBean scanResultBean = null;
    public static  String mobilePhone =null;
    public static String isFromOtherApp = "0";
    public static   boolean isCameraDenied;
    public  boolean isSdcardDenied;

    //wifi相关
    private static  WifiManager wifiManager;




    private static  MainActivity _this;


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        SplashScreen.show(this, getReactInstanceManager());

        super.onCreate(savedInstanceState);
        _this = this;

        //获取从别的应用跳转过来时传的手机号码
        {
            Intent intent = getIntent();
            String scheme = intent.getScheme();
            Uri uri = intent.getData();
            System.out.println("scheme:"+scheme);
            if (uri != null && scheme.equals("subwayEscort")) {
                //获得参数值
                isFromOtherApp = "1";
                mobilePhone = uri.getQueryParameter("mobilePhone");
            }else {
                isFromOtherApp = "0";
            }

        }


        //忽略电池优化
        try {
            Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
            intent.setData(Uri.parse("package:com.metroapp"));
            startActivity(intent);
        }catch (Exception e){

        }
        //所要申请的权限
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA,
                Manifest.permission.BLUETOOTH,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.ACCESS_WIFI_STATE,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.CHANGE_WIFI_STATE
        };
        easyPermission(perms);



        acquireWakeLock(this);

        //检测版本更新
        VersionParams.Builder builder = new VersionParams.Builder()
                .setRequestUrl(Constant.GET_APP_VERSION_URL)
                .setService(XNVersionService.class);
        AllenChecker.startVersionCheck(MainActivity.this, builder.build());


        //蒲公英版本更新
        PgyUpdateManager.setIsForced(false); //设置是否强制更新。true为强制更新;false为不强制更新(默认值)。
        PgyUpdateManager.register(this);


        wifiManager = (WifiManager)getApplicationContext().getSystemService(WIFI_SERVICE); //获得系统wifi服务

        initBluetooth();//初始化蓝牙

        registerReceiver(mReceiver, makeFilter());   //注册蓝牙开关咋状态变化的广播
    }

    @TargetApi(22)
    public void initBluetooth(){

        BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);//这里与标准蓝牙略有不同
        mBluetoothAdapter = bluetoothManager.getAdapter();

        if (mBluetoothAdapter == null){
            Toast.makeText(MainActivity.this,"该手机暂无蓝牙设备",Toast.LENGTH_SHORT).show();
            return;
        }
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {//小于18
            Toast.makeText(MainActivity.this,"该手机暂不支持蓝牙4.0",Toast.LENGTH_SHORT).show();
            return;
        }

        if (!mBluetoothAdapter.isEnabled()) {
            mBluetoothAdapter.enable();
        }
//
//        //再次弹出蓝牙确认框
//        if (!mBluetoothAdapter.isEnabled()){
//            alertSetBluetooth();
//        }

        mBluetoothAdapter.startLeScan(mLeScanCallback);
    }


    private static  int lastRSS =-9999;//上一个rss值
    private static String UUID ="E2C56DB5-DFFB-48D2-B060-D0F5A71096E0";
    private static String UUID1="FDA50693-A4E2-4FB1-AFCF-C6EB07647825";

    private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {

        @Override
        public void onLeScan(final BluetoothDevice device, final int rssi,
                             final byte[] scanRecord) {
            onLeScanParse(device,rssi,scanRecord);
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
//        VersionParams.Builder builder = new VersionParams.Builder()
//                .setRequestUrl(Constant.GET_APP_VERSION_URL)
//                .setService(XNVersionService.class);
//        AllenChecker.startVersionCheck(MainActivity.this, builder.build());
    }

    /**
     * 扫描结果处理
     */
    public void onLeScanParse(final BluetoothDevice device, final int rssi,
                              final byte[] scanRecord){

        String  scanRecordhex=bytesToHex(scanRecord);
        String hexString = scanRecordhex.substring(18,50);
        // ibeacon的UUID值
        String uuid = hexString.substring(0, 8) + "-"
                + hexString.substring(8, 12) + "-"
                + hexString.substring(12, 16) + "-"
                + hexString.substring(16, 20) + "-"
                + hexString.substring(20, 32);
        int major = Integer.valueOf(scanRecordhex.substring(50,54),16);
        int minor = Integer.valueOf(scanRecordhex.substring(54,58),16);
        if ((uuid.equalsIgnoreCase(UUID) || uuid.equalsIgnoreCase(UUID1)) && rssi!=0 ){//扫描到了
            if (rssi >=lastRSS){
                if (scanResultBean == null){
                    scanResultBean = new ScanResultBean();
                }
                scanResultBean.setDeviceCode(uuid+"|"+major+"|"+minor);
                scanResultBean.setRss(rssi+"");

                lastRSS = rssi;
            }
            System.out.println("rssi"+rssi+"===>uuid"+uuid+"major"+major+"minor"+minor);
        }
    }

    static final char[] hexArray = "0123456789ABCDEF".toCharArray();

    private static String bytesToHex(byte[] bytes) {
        char[] hexChars = new char[bytes.length * 2];
        for (int j = 0; j < bytes.length; j++) {
            int v = bytes[j] & 0xFF;
            hexChars[j * 2] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        }
        return new String(hexChars);
    }





    private static Timer timer = new Timer();
    private static Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // 要做的事情
            super.handleMessage(msg);
            if (msg.what == 1){

                //蓝牙信息获取
                if (scanResultBean ==null){
                    scanResultBean = new ScanResultBean();
                    scanResultBean.setRss("");
                    scanResultBean.setDeviceCode("");
                }
                WritableMap et= Arguments.createMap();
                String devicecode =  scanResultBean.getDeviceCode();
                String rss = scanResultBean.getRss();
                System.out.println("===>deviceCode"+devicecode);
                et.putString("deviceCode",devicecode);
                et.putString("rss",rss);
                //wifi信息获取
                 WifiInfo  wifiInfo = wifiManager.getConnectionInfo();
                if (wifiInfo !=null
                        && wifiInfo.getSSID() !=null
                        && (wifiInfo.getSSID().equals("\""+"花生地铁WiFi" +"\"") || wifiInfo.getSSID().equals("花生地铁WiFi"))){
                    et.putString("wRSS",wifiInfo.getRssi()+"");
                    et.putString("wBSSID",wifiInfo.getBSSID()+"");
                    et.putString("wIP",getWifiIP(wifiInfo.getIpAddress()));

                }else {
                    et.putString("wRSS","");
                    et.putString("wBSSID","");
                    et.putString("wIP","");
                }

                BluetoothModule.sendEvent("BlueToolData",et);
                resetData();


            }

        }
    };

    public static String  getWifiIP (int  i){
        String ip;
        ip = (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF)
                + "." + (i >> 24 & 0xFF);
        return ip;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer !=null){
            timer.cancel();
            timer = null;
            lastRSS =-9999;
            scanResultBean =null;
        }

        isFromOtherApp = "0";
        releaseWakeLock();
        if (mReceiver !=null){
            unregisterReceiver(mReceiver);
            mReceiver =null;
        }
    }

    public static void resetData(){
        lastRSS =-9999;
        scanResultBean = null;
    }

    /**
     * 开启定时器
     * @param s 秒
     */
    public static void startTimer(String s){
        if (s == null || s.equals("")){
            return;
        }
        if (timer ==null){
            timer = new Timer();
        }
        System.out.println("===s"+s);
        try {//防止重复开定时器时报错
            timer.schedule(new task(), 0, Integer.parseInt(s)*1000);
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    /**
     * 关闭定时器
     */
    public static void stopTimer(){
        if (timer !=null){
            timer.cancel();
            timer.purge();
            timer = null;
        }

    }

//    private static TimerTask task = new TimerTask() {
//        @Override
//        public void run() {
//            Message message = new Message();
//            message.what = 1;
//            handler.sendMessage(message);
//        }
//    };

    static  class task extends TimerTask {
        public void run() {
            Message message = new Message();
            message.what = 1;
            handler.sendMessage(message);

        }
    }

    /**
     * 监听蓝牙开关状态
     * @return
     */
    private IntentFilter makeFilter() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        return filter;
    }


    private BroadcastReceiver mReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()) {
                case BluetoothAdapter.ACTION_STATE_CHANGED:
                    int blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
                    switch (blueState) {
                        case BluetoothAdapter.STATE_ON:
                            //当蓝牙重新开启式必须重新设置mLeScanCallback,要不然不会重新扫描
                            if (mBluetoothAdapter.isEnabled()){
                                mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
                                    @Override
                                    public void onLeScan(BluetoothDevice bluetoothDevice, int i, byte[] bytes) {
                                        onLeScanParse(bluetoothDevice,i,bytes);
                                    }
                                };
                                mBluetoothAdapter.startLeScan(mLeScanCallback);
                            }

                            break;

                        case BluetoothAdapter.STATE_OFF:
                            mBluetoothAdapter.stopLeScan(mLeScanCallback);
                            mLeScanCallback =null;

                            break;
                    }
                    break;
            }
        }
    };

    //android 电源管理
    private PowerManager.WakeLock wakeLock;
    private void acquireWakeLock(Context context) {
        if (wakeLock == null) {
            PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            wakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, context.getClass().getCanonicalName());
            wakeLock.acquire();

        }

    }


    private void releaseWakeLock() {
        if (wakeLock != null && wakeLock.isHeld()) {
            wakeLock.release();
            wakeLock = null;
        }

    }

    /**
     * android6.0运行时权限处理
     */
    public static void easyPermission( String[] perms){


        if (EasyPermissions.hasPermissions(_this, perms)) {//检查是否获取该权限
        } else {
            //第二个参数是被拒绝后再次申请该权限的解释
            //第三个参数是请求码
            //第四个参数是要申请的权限
            EasyPermissions.requestPermissions(_this, "平安地铁需要获取必要的权限才能正常使用哦", 0, perms);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //把申请权限的回调交由EasyPermissions处理
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    //下面两个方法是实现EasyPermissions的EasyPermissions.PermissionCallbacks接口
    //分别返回授权成功和失败的权限
    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        if (perms.contains(Manifest.permission.CAMERA) && perms.contains(Manifest.permission.WRITE_EXTERNAL_STORAGE)){
            isCameraDenied = false;
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
      if (perms.contains(Manifest.permission.CAMERA) || perms.contains(Manifest.permission.WRITE_EXTERNAL_STORAGE)){
            isCameraDenied = true;
        }
    }

}