android 无线蓝牙模块自定义

android 无线蓝牙模块自定义

蓝牙板块初始化

public class showDatasMapActivity extends GosBaseActivity {
    private MapView mMapView;
    private BaiduMap mBaiduMap;
    ImageView requestLocButton;
    private SensorManager mSensorManager;
    //温度曲线
    private DynamicLineChartManager dynamicLineChartManager1;
//	private List<Integer> list = new ArrayList<>(); //数据集合
    private List<String> names = new ArrayList<>(); //折线名字集合
    private List<Integer> colour = new ArrayList<>();//折线颜色集合
    String proNo="";
    @BindView( R.id.resher)
    Button resher;
    @BindView( R.id.wenben)
    TextView wenben;
    @BindView( R.id.titleName)
    TextView title;
    @BindView( R.id.back)
    ImageView back;
    @BindView( R.id.ed_code)
    EditText code;
    @BindView( R.id.tv2)
    TextView tv2;
    @BindView( R.id.tv3)
    TextView tv3;
    @BindView( R.id.tv4)
    TextView tv4;
    @BindView( R.id.tv1)
    TextView tv1;
    @BindView( R.id.ed_name)
    EditText proname;
    @BindView(R.id.bwait)
    ImageView bwait;
    @BindView( R.id.ed_handlername)
    EditText handlername;
    @BindView( R.id.ed_startpoint)
    EditText startpoint;
    @BindView( R.id.ed_destination)
    EditText destination;
    LatLng startPoint;
    String currentMahineMap="";
    String address = "";
    int btdevice = 0;
    private Dialog mWeiboDialog;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    WeiboDialogUtils.closeDialog(mWeiboDialog);
                    com.qs.helper.printer.PrintService.pl.write(new byte[]{0x1d, 0x0c});
                    //将str转为UTF-8字节
              
                        byte[] seb = {0x1B, 0x33, 0x20};
                        PrintService.pl.write(seb);
                        PrintService.pl.printText(s);
                    }catch (Exception e)
                    {

                    }


                    break;
                case 2:
                    btdevice = 1;
                    mWeiboDialog = WeiboDialogUtils.createLoadingDialog(showDatasMapActivity.this, "初始化地址...");
                    com.qs.helper.printer.PrintService.pl.connect(SharedPreferencesUtils.getParam(showDatasMapActivity.this, "btdevice", "") + "");
                    back.setClickable(false);
                    break;
            }
        }
    };
    public static List<Device> deviceList = new ArrayList<Device>();
    public static final int MESSAGE_STATE_CHANGE = 1;
    public static final int MESSAGE_READ = 2;
    public static final int MESSAGE_WRITE = 3;
    public Handler mhandler = null;
    public Handler handler = null;
    LinearLayout main;
    ListView listView1;
    int t = 0;
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.myactivity_showdatas_map);
        initprint();
        Glide
                .with(this)
                .load(R.drawable.bwait)
                .asGif()
                .into(bwait);
        mSchedule = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1);
        listView1 = (ListView) findViewById(R.id.po_list6);
        main=(LinearLayout)findViewById(R.id.main);
        listView1.setAdapter(mSchedule);

        listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position,
                                    long id) {
                String cmd = Boothaddress.get(position);;
                address = cmd;
                mWeiboDialog = WeiboDialogUtils.createLoadingDialog(showDatasMapActivity.this, "初始化地址...");
                com.qs.helper.printer.PrintService.pl.connect(cmd);
            }
        });
        setToolBar(false, currentMahineMap);
        //left=(ImageView)findViewById(R.id.)
        final Drawable add = getResources().getDrawable(R.drawable.common_setting_more);
        int color = GosDeploy.appConfig_Contrast();
        add.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
        mToolbar.setOverflowIcon(add);
        IntentFilter filter = new IntentFilter();
//发现设备
        filter.addAction(BluetoothDevice.ACTION_FOUND);
//设备连接状态改变
        filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
//蓝牙设备状态改变
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        registerReceiver(mBluetoothReceiver, filter);

    }
    public boolean isResher=true;
    void initprint() {

        mhandler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case MESSAGE_READ:
                        byte[] readBuf = (byte[]) msg.obj;
                        String readMessage = new String(readBuf, 0, msg.arg1);

                        if (readBuf[0] == 0x13) {
                            com.qs.helper.printer.PrintService.isFUll = true;

                        } else if (readBuf[0] == 0x11) {
                            com.qs.helper.printer.PrintService.isFUll = false;

                        } else {
                            if (readMessage.contains("800"))// 80mm paper
                            {
                                com.qs.helper.printer.PrintService.imageWidth = 72;

                            } else if (readMessage.contains("580"))// 58mm paper
                            {
                                com.qs.helper.printer.PrintService.imageWidth = 48;
                            }
                        }
                        break;
                    case MESSAGE_STATE_CHANGE:
                        switch (msg.arg1) {
                            case PrinterClass.STATE_CONNECTED:
                                break;
                            case PrinterClass.STATE_CONNECTING:
                                break;
                            case PrinterClass.STATE_LISTEN:
                            case PrinterClass.STATE_NONE:
                                break;
                            case PrinterClass.SUCCESS_CONNECT:
                                PrintService.pl.write(new byte[] { 0x1b, 0x2b });
                                btdevice = 0;
                                WeiboDialogUtils.closeDialog(mWeiboDialog);
                                com.qs.helper.printer.PrintService.pl.stopScan();
                                SharedPreferencesUtils.setParam(showDatasMapActivity.this, "btdevice", address);
                                mWeiboDialog = WeiboDialogUtils.createLoadingDialog(showDatasMapActivity.this, "蓝牙连接中...");
                                mHandler.sendEmptyMessageDelayed(1, 2000);
                                t = 1;
                                main.setVisibility(View.VISIBLE);
                                listView1.setVisibility(View.GONE);
                                resher.setVisibility(View.GONE);
                                back.setClickable(true);
                                mBluetoothAdapter.cancelDiscovery();
                                bwait.setVisibility(View.GONE);
                                try {
                                    Thread.sleep(10);
                                } catch (InterruptedException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                                //     PrintService.pl.write(new byte[] { 0x1d, 0x67,0x33 });

                                break;
                            case PrinterClass.FAILED_CONNECT:
                                if (btdevice == 1) {
                                    Toast.makeText(showDatasMapActivity.this, "地址过期,请开启打印机后,选择正确的设备后连接", Toast.LENGTH_LONG).show();
                                }
                                WeiboDialogUtils.closeDialog(mWeiboDialog);
                                main.setVisibility(View.GONE);
                                listView1.setVisibility(View.VISIBLE);
                                resher.setVisibility(View.VISIBLE);
                                try {
                                    com.qs.helper.printer.PrintService.pl.disconnect();
                                }catch (Exception e){}
                                isResher=false;
                                back.setClickable(true);
                                break;
                            case PrinterClass.LOSE_CONNECT:
                                if (btdevice == 1) {
                                    Toast.makeText(showDatasMapActivity.this, "地址过期,请开启打印机后,请选择正确的设备连接", Toast.LENGTH_LONG).show();
                                }
                                WeiboDialogUtils.closeDialog(mWeiboDialog);
                                main.setVisibility(View.GONE);
                                listView1.setVisibility(View.VISIBLE);
                                resher.setVisibility(View.VISIBLE);
                                try {
                                    com.qs.helper.printer.PrintService.pl.disconnect();
                                }catch (Exception e){}
                                isResher=false;
                                back.setClickable(true);
                        }
                        break;
                    case MESSAGE_WRITE:

                        break;
                }
                super.handleMessage(msg);
            }
        };
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 0:
                        break;
                    case 1:
                        Device d = (Device) msg.obj;
                        if (d != null) {
                            if (deviceList == null) {
                                deviceList = new ArrayList<Device>();
                            }
                            if (!checkData(deviceList, d)) {
                                deviceList.add(d);
                            }
                        }
                        break;
                    case 2:
                        break;
                }
            }
        };

        com.qs.helper.printer.PrintService.pl = new BtService(this, mhandler, handler);
    }
    //得到配对的设备列表,清除已配对的设备
    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    public void removePairDevice(){
        if(mBluetoothAdapter!=null){
            Set<BluetoothDevice> bondedDevices = mBluetoothAdapter.getBondedDevices();
            for(BluetoothDevice device : bondedDevices ){
                unpairDevice(device);
            }
        }

    }

    //反射来调用BluetoothDevice.removeBond取消设备的配对
    private void unpairDevice(BluetoothDevice device) {
        try {
            Method m = device.getClass()
                    .getMethod("removeBond", (Class[]) null);
            m.invoke(device, (Object[]) null);
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
    }
    private BroadcastReceiver mBluetoothReceiver = new BroadcastReceiver(){
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.d(TAG,"mBluetoothReceiver action ="+action);
            if(BluetoothDevice.ACTION_FOUND.equals(action)){//每扫描到一个设备,系统都会发送此广播。
                //获取蓝牙设备
                BluetoothDevice scanDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if(scanDevice == null || scanDevice.getName() == null) return;
                Log.d(TAG, "name="+scanDevice.getName()+"address="+scanDevice.getAddress());
                //蓝牙设备名称
                String name = scanDevice.getName();
                ;
                if(name != null&&(!Boothaddress.contains(scanDevice.getAddress()))){
                    mSchedule.add(name);
                    Boothaddress.add(scanDevice.getAddress());
                    mSchedule.notifyDataSetChanged();
                }
            }else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){

            }
        }
    };
    ArrayAdapter<String> mSchedule;
    public List<String> Boothaddress=new ArrayList<>();
 public void connect(){
     if (!SharedPreferencesUtils.getParam(this, "btdevice", "").toString().equals("")) {
         if(isResher) {
             address = SharedPreferencesUtils.getParam(this, "btdevice", "") + "";
             mHandler.sendEmptyMessageDelayed(2, 500);
         }
     } else {

     }

     if (!com.qs.helper.printer.PrintService.pl.IsOpen()) {
         com.qs.helper.printer.PrintService.pl.open(this);
     }
     listView1.setVisibility(View.VISIBLE);
     resher.setVisibility(View.VISIBLE);
     main.setVisibility(View.GONE);
     mBluetoothAdapter.startDiscovery();

 }
    private boolean checkData(List<Device> list, Device d) {
        for (Device device : list) {
            if (device.deviceAddress.equals(d.deviceAddress)) {
                return true;
            }
        }
        return false;
    }


    @Override
    protected void onResume() {
        mMapView.onResume();
        super.onResume();
    }
    @Override
    protected void onStop() {
        super.onStop();
    }
    @Override
    protected void onPause() {
        mMapView.onPause();

        super.onPause();
    }
    @Override
    protected void onDestroy() {
    
        try {
            PrintService.pl.disconnect();
            unregisterReceiver(mBluetoothReceiver);
        }catch (Exception e){}
        super.onDestroy();
    }
  

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值