为什么蓝牙在选项卡式活动中不起作用

时间:2018-12-07 17:49:50

标签: android android-studio bluetooth tabactivity android-tabactivity

我从蓝牙接收数据并将它们存储在不同的列表中遇到问题

我有3个活动(SplashScreen,BluetoothDevices,TabbedActivity)和3个片段来显示数据。

在TabbedActivity中,我具有蓝牙方法来接收和存储数据。但是似乎无法使用蓝牙手柄。

我尝试存储数据以便显示最后收到的显示图。

这是我的代码:

public class TabbedInterfaz extends AppCompatActivity {

private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;

/******************VARIABLES BLUETOOTH************************/
Handler bluetoothIn;
final int handlerState = 0;
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private StringBuilder DataStringIN = new StringBuilder();
private ConnectedThread MyConexionBT;

private String dataInPrint = null;

private static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

private static String address = null;
public int num;
/*************************************************************/

/*LISTAS PARA GUARDAR LOS DATOS RECIBIDOS*/
private List<String> LHum = new ArrayList<String>();
private List<String> LTem = new ArrayList<String>();
private List<String> LDoA = new ArrayList<String>();
private List<String> LDoB = new ArrayList<String>();
private List<String> LDoP = new ArrayList<String>();
/*****************************************/

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_tabbed_interfaz);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);


    /********************BLUETOOTH EVENTOS*********************/

    bluetoothIn = new Handler() {
        public void handleMessage(android.os.Message msg) {

            if (msg.what == handlerState) {
                String readMessage = (String) msg.obj;
                DataStringIN.append(readMessage);

                int startOfLineIndex, endOfLineIndex, IndexHum, IndexTemp, IndexA, IndexB, IndexP;
                endOfLineIndex = DataStringIN.indexOf("#");

                if ( endOfLineIndex > 0) {
                    startOfLineIndex = DataStringIN.indexOf("&");
                    IndexHum = DataStringIN.indexOf("H");
                    IndexTemp = DataStringIN.indexOf("T");
                    IndexA = DataStringIN.indexOf("A");
                    IndexB = DataStringIN.indexOf("B");
                    IndexP = DataStringIN.indexOf("P");


                    /*GUARDAR VARIABLES*/

                    dataInPrint = DataStringIN.substring(2, IndexHum);
                    LHum.add(dataInPrint);

                    dataInPrint = DataStringIN.substring(IndexHum+1, IndexTemp);
                    LTem.add(dataInPrint);

                    dataInPrint = DataStringIN.substring(IndexTemp+1, IndexA);
                    LDoA.add(dataInPrint);

                    dataInPrint = DataStringIN.substring(IndexA+1, IndexB);
                    LDoB.add(dataInPrint);

                    dataInPrint = DataStringIN.substring(IndexB+1, IndexP);
                    LDoP.add(dataInPrint);                        

                    DataStringIN.delete(0, DataStringIN.length());
                }
            }
        }
    };

    btAdapter = BluetoothAdapter.getDefaultAdapter();
    //VerificarEstadoBT();
    /**********************************************************/

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
   getMenuInflater().inflate(R.menu.menu_tabbed_interfaz, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

public Integer convertStringToInt(String numero) {
    Integer parse_numero = 0;
    try
    {
        parse_numero = Integer.parseInt(numero);
        num = parse_numero;

    } catch (ParseException e) {
        num = 0;
    }
    return parse_numero;
}




public static class PlaceholderFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    public PlaceholderFragment() {
    }

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static PlaceholderFragment newInstance(String sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putString(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_tabbed_interfaz, container, false);
        TextView textView = (TextView) rootView.findViewById(R.id.section_label);
        textView.setText(getArguments().getString(ARG_SECTION_NUMBER));
        return rootView;
    }
}




public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        return PlaceholderFragment.newInstance(LHum.get(0));
    }

    @Override
    public int getCount() { return 3;   }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "SECTION 1";
            case 1:
                return "SECTION 2";
            case 2:
                return "SECTION 3";
        }
        return null;
    }
}


/*METODOS DEL BLUETOOTH*/
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException
{
    return device.createRfcommSocketToServiceRecord(BTMODULEUUID);
}

@Override
protected void onResume() {
    super.onResume();
    Intent intent = getIntent();
    address = intent.getStringExtra(DispositivosBT.EXTRA_DEVICE_ADDRESS);//<-<- PARTE A MODIFICAR >->->
    BluetoothDevice device = btAdapter.getRemoteDevice(address);

    try
    {
        btSocket = createBluetoothSocket(device);
    } catch (IOException e) {
        Toast.makeText(getBaseContext(), "La creacción del Socket fallo", Toast.LENGTH_LONG).show();
    }
    // Establece la conexión con el socket Bluetooth.
    try
    {
        btSocket.connect();
    } catch (IOException e) {
        try {
            btSocket.close();
        } catch (IOException e2) {}
    }
    MyConexionBT = new ConnectedThread(btSocket);
    MyConexionBT.start();

}

private void VerificarEstadoBT() {

    if(btAdapter==null) {
        Toast.makeText(getBaseContext(), "El dispositivo no soporta bluetooth", Toast.LENGTH_LONG).show();
    } else {
        if (btAdapter.isEnabled()) {
        } else {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, 1);
        }
    }
}

@Override
public boolean onTouchEvent(MotionEvent event) {    return super.onTouchEvent(event);   }

private class ConnectedThread extends Thread
{
    private final InputStream mmInStream;

    public ConnectedThread(BluetoothSocket socket)
    {
        InputStream tmpIn = null;
        try
        {
            tmpIn = socket.getInputStream();
        } catch (IOException e) { }
        mmInStream = tmpIn;
    }

    public void run()
    {
        byte[] buffer = new byte[256];
        int bytes;

        // Se mantiene en modo escucha para determinar el ingreso de datos
        while (true) {
            try {
                bytes = mmInStream.read(buffer);
                String readMessage = new String(buffer, 0, bytes);
                // Envia los datos obtenidos hacia el evento via handler
                bluetoothIn.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();
            } catch (IOException e) {
                break;
            }
        }
    }
}
/*************************/

}

PlaceholderFragment是Android随模板提供的预定义类,我正在使用它来测试是否获取了数据。

谢谢

0 个答案:

没有答案