Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.example.cartouch;
- import android.app.Activity;
- import android.bluetooth.BluetoothAdapter;
- import android.bluetooth.BluetoothDevice;
- import android.bluetooth.BluetoothSocket;
- import android.content.Intent;
- import android.os.Bundle;
- import android.os.Handler;
- import android.util.Log;
- import android.view.MotionEvent;
- import android.view.View;
- import android.view.View.OnTouchListener;
- import android.widget.TextView;
- import android.widget.Toast;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.util.UUID;
- public class MainActivity extends Activity implements OnTouchListener {
- private static final int REQUEST_ENABLE_BT = 1;
- final int ArduinoData = 1;
- final String LOG_TAG = "MyLogs";
- private BluetoothAdapter btAdapter = null;
- private BluetoothSocket btSocket = null;
- private static String MacAddress = "20:16:06:28:19:52";
- private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
- private ConnectedThred MyThred = null;
- public TextView point;
- Handler h;
- private StringBuilder sb = new StringBuilder();
- private static final String TAG = "bluetooth2";
- int x;
- int y;
- int xi;
- int yi;
- int xii;
- int yii;
- String sDown;
- String sMove;
- String sUp;
- String sCar;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- btAdapter = BluetoothAdapter.getDefaultAdapter();
- point = (TextView) findViewById(R.id.textView);
- if (btAdapter != null){
- if (btAdapter.isEnabled()){
- point.setText("Bluetooth включен. Все отлично.");
- }else
- {
- Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
- startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
- }
- }else
- {
- MyError("Fatal Error", "Bluetooth ОТСУТСТВУЕТ");
- }
- point = new TextView(this);
- point.setOnTouchListener(this);
- setContentView(point);
- h = new Handler() {
- public void handleMessage(android.os.Message msg) {
- switch (msg.what) {
- case ArduinoData:
- byte[] readBuf = (byte[]) msg.obj;
- String strIncom = new String(readBuf, 0, msg.arg1);
- sb.append(strIncom);// формируем строку
- int beginOfLineIndex = sb.indexOf("*");//определяем символы начала строки
- int endOfLineIndex = sb.indexOf("#");//определяем символы конца строки
- //Если блок данных соотвествует маске *данные# то выполняем код
- if ((endOfLineIndex > 0) && (beginOfLineIndex == 0)) { // если встречаем конец строки,
- String sbprint = sb.substring(beginOfLineIndex+1, endOfLineIndex-3); // то извлекаем строку
- point.setText("Данные от Arduino: " + sbprint);
- }
- sb.delete(0, sb.length());
- break;
- }
- };
- };
- }
- @Override
- public boolean onTouch(View v, MotionEvent event) {
- int x = (int) event.getX();
- int y = (int) event.getY();
- switch (event.getAction()) {
- case MotionEvent.ACTION_DOWN: // нажатие
- sDown = "Down: " + x + "," + y;
- sMove = "";
- sUp = "";
- xi = x;
- xii = 0;
- yi = y;
- yii = 0;
- break;
- case MotionEvent.ACTION_MOVE: // движение
- sMove = "Move: " + (x - xi) + "," + (yi - y);
- xii = x - xi;
- yii = y - yi;
- sCar = xii + ":" + yii;
- break;
- case MotionEvent.ACTION_UP: // отпускание
- case MotionEvent.ACTION_CANCEL:
- sMove = "";
- sUp = "Up: " + (x - xi) + "," + (yi - y);
- xii = 0;
- yii = 0;
- sCar = xii + ":" + yii;
- break;
- }
- point.setText(sDown + "\n" + sMove + "\n" + sUp);
- MyThred.sendData("5");
- return true;
- }
- @Override
- public void onResume() {
- super.onResume();
- if (btAdapter != null){
- if (btAdapter.isEnabled()){
- BluetoothDevice device = btAdapter.getRemoteDevice(MacAddress);
- Log.d(LOG_TAG, "***Получили удаленный Device***"+device.getName());
- try {
- btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
- Log.d(LOG_TAG, "...Создали сокет...");
- } catch (IOException e) {
- MyError("Fatal Error", "В onResume() Не могу создать сокет: " + e.getMessage() + ".");
- }
- btAdapter.cancelDiscovery();
- Log.d(LOG_TAG, "***Отменили поиск других устройств***");
- Log.d(LOG_TAG, "***Соединяемся...***");
- try {
- btSocket.connect();
- Log.d(LOG_TAG, "***Соединение успешно установлено***");
- } catch (IOException e) {
- try {
- btSocket.close();
- } catch (IOException e2) {
- MyError("Fatal Error", "В onResume() не могу закрыть сокет" + e2.getMessage() + ".");
- }
- }
- MyThred = new ConnectedThred(btSocket);
- MyThred.start();
- }
- }
- }
- @Override
- public void onPause() {
- super.onPause();
- Log.d(LOG_TAG, "...In onPause()...");
- if (btAdapter != null){
- if (btAdapter.isEnabled()){
- if (MyThred.status_OutStream() != null) {
- MyThred.cancel();
- }
- try {
- btSocket.close();
- } catch (IOException e2) {
- MyError("Fatal Error", "В onPause() Не могу закрыть сокет" + e2.getMessage() + ".");
- }
- }
- }
- }//OnPause
- private void MyError(String title, String message){
- Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
- finish();
- }
- //Отдельный поток для передачи данных
- private class ConnectedThred extends Thread{
- private final BluetoothSocket copyBtSocket;
- private final OutputStream OutStream;
- private final InputStream InStream;
- public ConnectedThred(BluetoothSocket socket){
- copyBtSocket = socket;
- OutputStream tmpOut = null;
- InputStream tmpIn = null;
- try{
- tmpOut = socket.getOutputStream();
- tmpIn = socket.getInputStream();
- } catch (IOException e){}
- OutStream = tmpOut;
- InStream = tmpIn;
- }
- public void run()
- {
- btAdapter.cancelDiscovery();
- byte[] buffer = new byte[1024];
- int bytes;
- while(true){
- try{
- bytes = InStream.read(buffer);
- h.obtainMessage(ArduinoData, bytes, -1, buffer).sendToTarget();
- }catch(IOException e){break;}
- }
- }
- public void sendData(String message) {
- byte[] msgBuffer = message.getBytes();
- Log.d(LOG_TAG, "***Отправляем данные: " + message + "***" );
- try {
- OutStream.write(msgBuffer);
- } catch (IOException e) {}
- }
- public void cancel(){
- try {
- copyBtSocket.close();
- }catch(IOException e){}
- }
- public Object status_OutStream(){
- if (OutStream == null){return null;
- }else{return OutStream;}
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement