У меня проблемы с получением данных из bluetooth и сохранением их в разных списках.
У меня есть 3 действия (SplashScreen, BluetoothDevices, TabbedActivity) и 3 фрагмента для отображения данных.
В TabbedActivity у меня есть методы Bluetooth для получения и хранения данных.Но похоже, что не работает ручка Bluetooth.
Я пытаюсь сохранить данные, чтобы показать последние полученные графики показа.
Вот мой код:
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 имеет с шаблоном, и я использую его для проверки получения данных.
Спасибо