0

estoy realizando una aplicación en Android que recibe datos por Bluetooth desde un Arduino. Lo que sucede es que al bloquearse la pantalla, la aplicación deja de recibir los datos y por ende deja de ingresarlos a la base de datos. Lo que necesito es que el servicio que está a la espera de los datos se mantenga funcionando en 2do plano aun que la pantalla esté bloqueada. He intentado implementar lo mismo con Threads y con AssyncTasks pero no lo he conseguido aún, espero me puedan ayudar.

Estoy usando Handlers, mi código es el siguiente:

public class MainActivity extends Activity {

Button btnOn, btnOff;
TextView  txtString, txtStringLength, sensorView0;
TextView txtSendorLDR;
Handler bluetoothIn;

final int handlerState = 0;                      //used to identify handler message
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
public static StringBuilder recDataString = new StringBuilder();
//    public static SharedPreferences sharedPref;
private ConnectedThread mConnectedThread;

// SPP UUID service - this should work for most devices
private static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

// String for MAC address
private static String address = null;
public static String dataInPrint;



@SuppressLint("HandlerLeak")
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    //Link the buttons and textViews to respective views
    btnOn = (Button) findViewById(R.id.buttonOn);
    btnOff = (Button) findViewById(R.id.buttonOff);
    txtString = (TextView) findViewById(R.id.txtString);
    txtStringLength = (TextView) findViewById(R.id.testView1);
    sensorView0 = (TextView) findViewById(R.id.sensorView0);
    txtSendorLDR = (TextView) findViewById(R.id.tv_sendorldr);

//        Context context = this.getApplicationContext();
//        sharedPref = context.getSharedPreferences(
//                getString(R.string.data_key), Context.MODE_PRIVATE);


    bluetoothIn = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == handlerState) {                                     //if message is what we want
                String readMessage = (String) msg.obj;                                                                // msg.arg1 = bytes from connect thread
                recDataString.append(readMessage);                                      //keep appending to string until ~
                int endOfLineIndex = recDataString.indexOf("~");                    // determine the end-of-line
                if (endOfLineIndex > 0) {                                           // make sure there data before ~
                    dataInPrint = recDataString.substring(0, endOfLineIndex);    // extract string
                    txtString.setText("Datos recibidos = " + dataInPrint);

//                        SharedPreferences.Editor editor = sharedPref.edit();
//                        editor.putString(getString(R.string.data_key), dataInPrint);
//                        editor.commit();

                     ingresar();

                    if (recDataString.charAt(0) == '#')                             //if it starts with # we know it is what we are looking for
                    {
                        String sensor0 = recDataString.substring(1, 5);             //get sensor value from string between indices 1-5


                        if(sensor0.equals("1.00"))
                            sensorView0.setText("Encendido");   //update the textviews with sensor values
                        else
                            sensorView0.setText("Apagado"); //update the textviews with sensor values

                    }
                    recDataString.delete(0, recDataString.length());                    //clear all string data

                    dataInPrint = " ";

                }

            }
        }
    };

    btAdapter = BluetoothAdapter.getDefaultAdapter();       // get Bluetooth adapter
    checkBTState();


    // Set up onClick listeners for buttons to send 1 or 0 to turn on/off LED
    btnOff.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            mConnectedThread.write("2");    // Send "0" via Bluetooth
            Toast.makeText(getBaseContext(), "Apagar el LED", Toast.LENGTH_SHORT).show();
        }
    });

    btnOn.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            mConnectedThread.write("1");    // Send "1" via Bluetooth
            Toast.makeText(getBaseContext(), "Encender el LED", Toast.LENGTH_SHORT).show();
        }
    });
}

public void ingresar(){
            String URL_ENVIAR="http://equilibratechile.com/sensor/registrar.php?dataInPrint="+dataInPrint;
            StringRequest stringRequest = new com.android.volley.toolbox.StringRequest(Request.Method.GET, URL_ENVIAR,
            new Response.Listener<String>() {

                @Override
                public void onResponse(String response) {
                    try{
                        JSONObject jsonObject = new JSONObject(response);
                        String success = jsonObject.getString("success");

                        if(success.equals("1")){
                           Toast.makeText(MainActivity.this, "Ingresado", Toast.LENGTH_SHORT).show();
                        }
                        if(success.equals("0")){
                            Toast.makeText(MainActivity.this, "No ingresado", Toast.LENGTH_SHORT).show();

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                        Toast.makeText(MainActivity.this, "Vuelve a intentarlo", Toast.LENGTH_SHORT).show();

                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(MainActivity.this, "Revisa tú conexión a internet", Toast.LENGTH_SHORT).show();

                }
            });

    RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
    requestQueue.add(stringRequest);



}

private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {

    return  device.createRfcommSocketToServiceRecord(BTMODULEUUID);
    //creates secure outgoing connecetion with BT device using UUID
}

@Override
public void onResume() {
    super.onResume();

    //Get MAC address from DeviceListActivity via intent
    Intent intent = getIntent();

    //Get the MAC address from the DeviceListActivty via EXTRA
    address = intent.getStringExtra(DeviceListActivity.EXTRA_DEVICE_ADDRESS);

    //create device and set the MAC address
    //Log.i("ramiro", "adress : " + address);
    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();
    }
    // Establish the Bluetooth socket connection.
    try
    {
        btSocket.connect();
    } catch (IOException e) {
        try
        {
            btSocket.close();
        } catch (IOException e2)
        {
            //insert code to deal with this
        }
    }
    mConnectedThread = new ConnectedThread(btSocket);
    mConnectedThread.start();

    //I send a character when resuming.beginning transmission to check device is connected
    //If it is not an exception will be thrown in the write method and finish() will be called
    mConnectedThread.write("x");
}

@Override
public void onPause()
{
    super.onPause();
    try
    {
        //Don't leave Bluetooth sockets open when leaving activity
        btSocket.close();
    } catch (IOException e2) {
        //insert code to deal with this
    }
}

//Checks that the Android device Bluetooth is available and prompts to be turned on if off
private void checkBTState() {

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

//create new class for connect thread
private class ConnectedThread extends Thread {
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;

    //creation of the connect thread
    public ConnectedThread(BluetoothSocket socket) {
        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        try {
            //Create I/O streams for connection
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) { }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }


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

        // Keep looping to listen for received messages
        while (true) {
            try {
                bytes = mmInStream.read(buffer);            //read bytes from input buffer
                String readMessage = new String(buffer, 0, bytes);
                // Send the obtained bytes to the UI Activity via handler
                bluetoothIn.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();
            } catch (IOException e) {
                break;
            }
        }
    }
    //write method
    public void write(String input) {
        byte[] msgBuffer = input.getBytes();           //converts entered String into bytes
        try {
            mmOutStream.write(msgBuffer);                //write bytes over BT connection via outstream
        } catch (IOException e) {
            //if you cannot write, close the application
            Toast.makeText(getBaseContext(), "La Conexión fallo", Toast.LENGTH_LONG).show();
            finish();

        }
    }
}
}
3
  • saludos, en que versión de android estas intentando hacer esto que comentas? Commented el 6 feb. 2019 a las 19:55
  • Hola, estoy usando la API 27, Nougat si no me equivoco.
    – flo
    Commented el 6 feb. 2019 a las 20:02
  • podria recomendarte que revises la documentación de servicios en background y foreground para esa versión de android, lo digo por que en android oreo por ejemplo, los servicios tienen duración limitada. Commented el 6 feb. 2019 a las 20:56

1 respuesta 1

0

lo que te podría ayudar es utilizar Service de segundo plano

public class Logeo extends Service {

@Override
public void onCreate() {
    super.onCreate();

}

@Override
public int onStartCommand(Intent intencion, int flags, int idArranque) {

    //aqui poner tu código (inicia el servicio)
    return START_NOT_STICKY;
}

@Override
public void onDestroy() {
    //cuando quieras acabar tu servicio
    super.onDestroy();
}

public IBinder onBind(Intent intent) {
    return null;
}
}

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.