MainActivity.java 9.55 KB
package com.metroapp;

import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

import com.facebook.react.ReactActivity;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.WritableMap;
import com.metroapp.bean.ScanResultBean;
import com.metroapp.nativemodules.BluetoothModule;

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

@TargetApi(22)
public class MainActivity extends ReactActivity {

    /**
     * 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;
    private static  MainActivity _this;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        _this = this;


//
//        {
//            Intent intent = getIntent();
//            String scheme = intent.getScheme();
//            Uri uri = intent.getData();
//            System.out.println("scheme:"+scheme);
//            if (uri != null) {
//                String host = uri.getHost();
//                String dataString = intent.getDataString();
//                //获得参数值
//                String mobile = uri.getQueryParameter("mobile");
//            }
//
//        }
//

        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);
    }


    public void alertSetBluetooth(){

        new AlertDialog.Builder(MainActivity.this)
                .setTitle("提示")
                .setMessage("平安地铁需要打开蓝牙功能才能正常使用,是否打开?")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        mBluetoothAdapter.enable();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        finish();
                    }
                }).show();

    }


    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);
        }
    };

    /**
     * 扫描结果处理
     */
    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) ){//扫描到了
            if (rssi >=lastRSS){
                if (scanResultBean == null){
                    scanResultBean = new ScanResultBean();
                }
                scanResultBean.setDeviceCode(uuid+"|"+major+"|"+minor);
                scanResultBean.setRss(rssi+"");

                lastRSS = rssi;
            }

        }
    }

    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();
                System.out.println("===>deviceCode"+scanResultBean.getDeviceCode());
                et.putString("deviceCode",scanResultBean.getDeviceCode());
                et.putString("rss",scanResultBean.getRss());
                BluetoothModule.sendEvent("BlueToolData",et);
                resetData();

            }

        }
    };

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

        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();
        }
        try {//防止重复开定时器时报错
            timer.schedule(task, 0, Integer.parseInt(s)*1000);
        }catch (Exception e){

        }

    }

    /**
     * 关闭定时器
     */
    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);
        }
    };

    /**
     * 监听蓝牙开关状态
     * @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;
            }
        }
    };



}