Automatic reconnection of bluetooth android studio

1

Good morning.

I am developing an app in android studio, in which I connect via bluetooth to the printer.

The detail is that if I leave the app the bluetooth connection to the printer is lost, and what I want is when I start the app I will automatically connect to the printer, I'll leave the code for what I am trying to do but the app thunders

This file is used so that from the bluetooth connection to the printer, that if it works for me because it is the use in my configuration screen.

public class ConexionBluetooth extends Activity {


    private static final String TAG = "BluetoothConnectMenu";
    // Intent request codes
    // private static final int REQUEST_CONNECT_DEVICE = 1;
    private static final int REQUEST_ENABLE_BT = 2;

    ArrayAdapter<String> adapter;
    private BluetoothAdapter mBluetoothAdapter;
    private Vector<BluetoothDevice> remoteDevices;
    private BroadcastReceiver searchFinish;
    private BroadcastReceiver searchStart;
    private BroadcastReceiver discoveryResult;
    private Thread hThread;
    private Context context;
    private String MacAddres = "";
    private BroadcastReceiver reconectar;
    // UI
    private EditText btAddrBox;
    private Button connectButton;
    private Button searchButton;
    private ListView list;
    // BT
    private BluetoothPort bluetoothPort;

    // Activar Bluetooth en caso de no estar activado
    public void bluetoothSetup()
    {
        // Initialize
        clearBtDevData();
        bluetoothPort = BluetoothPort.getInstance();
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null)
        {
            // Device does not support Bluetooth
            return;
        }
        if (!mBluetoothAdapter.isEnabled())
        {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }
    }

    private static final String dir = Environment.getExternalStorageDirectory().getAbsolutePath() + "//temp";
    private static final String fileName = dir + "//BTPrinter";
    private String lastConnAddr;
    private void loadSettingFile()
    {
        int rin = 0;
        char [] buf = new char[128];
        try
        {
            FileReader fReader = new FileReader(fileName);
            rin = fReader.read(buf);
            if(rin > 0)
            {
                lastConnAddr = new String(buf,0,rin);
                btAddrBox.setText(lastConnAddr);
            }
            fReader.close();
        }
        catch (FileNotFoundException e)
        {
            Log.i(TAG, "No existe historia de conexiones.");
        }
        catch (IOException e)
        {
            Log.e(TAG, e.getMessage(), e);
        }
    }

    private void saveSettingFile()
    {
        try
        {
            File tempDir = new File(dir);
            if(!tempDir.exists())
            {
                tempDir.mkdir();
            }
            FileWriter fWriter = new FileWriter(fileName);
            if(lastConnAddr != null)
                fWriter.write(lastConnAddr);
            fWriter.close();
        }
        catch (FileNotFoundException e)
        {
            Log.e(TAG, e.getMessage(), e);
        }
        catch (IOException e)
        {
            Log.e(TAG, e.getMessage(), e);
        }
    }

    // Limpiar lista de dispositivos.
    private void clearBtDevData()
    {
        remoteDevices = new Vector<BluetoothDevice>();
    }
    // add paired device to list
    private void addPairedDevices()
    {
        BluetoothDevice pairedDevice;
        Iterator<BluetoothDevice> iter = (mBluetoothAdapter.getBondedDevices()).iterator();
        while(iter.hasNext())
        {
            pairedDevice = iter.next();
            remoteDevices.add(pairedDevice);
            adapter.add(pairedDevice.getName() +"\n["+pairedDevice.getAddress()+"] [Paired]");
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.bluetooth_menu);
        // Setting
        btAddrBox = (EditText) findViewById(R.id.EditTextAddressBT);
        connectButton = (Button) findViewById(R.id.ButtonConnectBT);
        searchButton = (Button) findViewById(R.id.ButtonSearchBT);
        list = (ListView) findViewById(R.id.ListView01);
        context = this;
        // Setting
        loadSettingFile();
        bluetoothSetup();



        // Connect, Disconnect -- Button
        connectButton.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                if(!bluetoothPort.isConnected()) // Connect routine.
                {
                    try
                    {
                        Conectar(btAddrBox.getText().toString());
                        //btConn(mBluetoothAdapter.getRemoteDevice(btAddrBox.getText().toString()));
                    }
                    catch(IllegalArgumentException e)
                    {
                        // Bluetooth Address Format [OO:OO:OO:OO:OO:OO]
                        Log.e(TAG,e.getMessage(),e);
                        //AlertView.showAlert(e.getMessage(), context);
                        Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_LONG).show();
                        return;
                    }
                }
                else // Disconnect routine.
                {
                    // Always run.
                    btDisconn();
                }
            }
        });
        // Search Button
        searchButton.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                if (!mBluetoothAdapter.isDiscovering())
                {
                    clearBtDevData();
                    adapter.clear();
                    mBluetoothAdapter.startDiscovery();
                }
                else
                {
                    mBluetoothAdapter.cancelDiscovery();
                }
            }
        });
        // Bluetooth Device List
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
        list.setAdapter(adapter);
        addPairedDevices();
        // Connect - click the List item.
        list.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
            {
                BluetoothDevice btDev = remoteDevices.elementAt(arg2);
                String Mac = String.valueOf(remoteDevices.elementAt(arg2));
                if(mBluetoothAdapter.isDiscovering())
                {
                    mBluetoothAdapter.cancelDiscovery();
                }
                btAddrBox.setText(btDev.getAddress());
                //btConn(btDev);
                Conectar(Mac);
            }
        });

        // UI - Event Handler.
        // Search device, then add List.
        discoveryResult = new BroadcastReceiver()
        {
            @Override
            public void onReceive(Context context, Intent intent)
            {
                    String key;
                BluetoothDevice remoteDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if(remoteDevice != null)
                {
                    if(remoteDevice.getBondState() != BluetoothDevice.BOND_BONDED)
                    {
                        key = remoteDevice.getName() +"\n["+remoteDevice.getAddress()+"]";
                    }
                    else
                    {
                        key = remoteDevice.getName() +"\n["+remoteDevice.getAddress()+"] [Paired]";
                    }
                    remoteDevices.add(remoteDevice);
                    adapter.add(key);
                }
            }
        };
        registerReceiver(discoveryResult, new IntentFilter(BluetoothDevice.ACTION_FOUND));
        searchStart = new BroadcastReceiver()
        {
            @Override
            public void onReceive(Context context, Intent intent)
            {
                connectButton.setEnabled(false);
                btAddrBox.setEnabled(false);
                searchButton.setText(getResources().getString(R.string.bt_stop_search_btn));
            }
        };
        registerReceiver(searchStart, new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED));
        searchFinish = new BroadcastReceiver()
        {
            @Override
            public void onReceive(Context context, Intent intent)
            {
                connectButton.setEnabled(true);
                btAddrBox.setEnabled(true);
                searchButton.setText(getResources().getString(R.string.bt_search_btn));
            }
        };
        registerReceiver(searchFinish, new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED));

    }
    //Funcion Para Conectar solo Mac en String
    private void Conectar(final String MacAddres)
    {
        AsyncBluetooth task = new AsyncBluetooth();
        task.execute(MacAddres);
    }
    // Bluetooth Metodo Desconectar.
    public void btDisconn()
    {
        try
        {
            bluetoothPort.disconnect();
        }
        catch (Exception e)
        {
            Log.e(TAG, e.getMessage(), e);
        }
        if((hThread != null) && (hThread.isAlive()))
            hThread.interrupt();
        // UI
        connectButton.setText(getResources().getString(R.string.dev_conn_btn));
        list.setEnabled(true);
        btAddrBox.setEnabled(true);
        searchButton.setEnabled(true);
        Toast.makeText(context, getResources().getString(R.string.bt_disconn_msg), Toast.LENGTH_SHORT).show();

    }




    //ClaSE Nueva de Asyntask ConexionBluetooth

    public class AsyncBluetooth extends AsyncTask<String, Void,Integer>
    {
        private final ProgressDialog dialog = new ProgressDialog(ConexionBluetooth.this);


        @Override
        protected void onPreExecute() {

            dialog.setTitle(getResources().getString(R.string.bt_tab));
            dialog.setMessage(getResources().getString(R.string.connecting_msg));
            dialog.show();
            super.onPreExecute();
        }

        @Override
        protected Integer doInBackground(String... params) {
            Integer resultado = null;

            try
            {
                SharedPreferences bluetooth = getSharedPreferences("ConexionBluetooth",0);
                SharedPreferences.Editor editor = bluetooth.edit();
                editor.putString("Mac",params[0]);
                editor.commit();
                lastConnAddr = params[0];
                bluetoothPort.connect(lastConnAddr);
                resultado = Integer.valueOf(0);
            }catch (IOException e)
            {
                resultado = Integer.valueOf(-1);
            }


            return resultado;
        }

        @Override
        protected void onPostExecute(Integer result) {
            if (result.intValue() == 0)
            {
                RequestHandler rh = new RequestHandler();
                hThread = new Thread(rh);
                hThread.start();
                // UI
                connectButton.setText(getResources().getString(R.string.dev_disconn_btn));
                list.setEnabled(false);
                btAddrBox.setEnabled(false);
                searchButton.setEnabled(false);
                if(dialog.isShowing())
                    dialog.dismiss();
                Toast.makeText(context, getResources().getString(R.string.bt_conn_msg), Toast.LENGTH_SHORT).show();
            }else
            {

                if(dialog.isShowing())
                    dialog.dismiss();
                AlertView.showAlert(getResources().getString(R.string.bt_conn_fail_msg),
                        getResources().getString(R.string.dev_check_msg), context);
            }

            super.onPostExecute(result);
        }
    }

}

And what I'm doing is that on my login screen, there's a call again to call my Asynctask for the connection, it thunders to me

 SharedPreferences bluetooth = getSharedPreferences("ConexionBluetooth",0);
        AsyncBluetooth tas2 = new AsyncBluetooth();
        tas2.execute(bluetooth.getString("Mac",""));

public class AsyncBluetooth extends AsyncTask<String, Void,Integer>
    {
        private final ProgressDialog dialog = new ProgressDialog(Login.this);


        @Override
        protected void onPreExecute() {

            dialog.setTitle(getResources().getString(R.string.bt_tab));
            dialog.setMessage(getResources().getString(R.string.connecting_msg));
            dialog.show();
            super.onPreExecute();
        }

        @Override
        protected Integer doInBackground(String... params) {
            Integer resultado = null;

            try
            {
                lastConnAddr = params[0];
                bluetoothPort.connect(params[0]);
                resultado = Integer.valueOf(0);
            }catch (IOException e)
            {
                resultado = Integer.valueOf(-1);
            }


            return resultado;
        }

        @Override
        protected void onPostExecute(Integer result) {
            if (result.intValue() == 0)
            {
                RequestHandler rh = new RequestHandler();
                hThread = new Thread(rh);
                hThread.start();
                // UI
                if(dialog.isShowing())
                    dialog.dismiss();
                Toast.makeText(context, getResources().getString(R.string.bt_conn_msg), Toast.LENGTH_SHORT).show();
            }else
            {

                if(dialog.isShowing())
                    dialog.dismiss();
                AlertView.showAlert(getResources().getString(R.string.bt_conn_fail_msg),
                        getResources().getString(R.string.dev_check_msg), context);
            }

            super.onPostExecute(result);
        }

Error, I told you that the Asynctask call was made on Oncreate, I do not know if it's ok.

  

E / AndroidRuntime: FATAL EXCEPTION: AsyncTask # 2                     Process: mx.com.oncontrol.oncontroldesconnected, PID: 5021                     java.lang.RuntimeException: An error occured while executing doInBackground ()                         at android.os.AsyncTask $ 3.done (AsyncTask.java:300)                         at java.util.concurrent.FutureTask.finishCompletion (FutureTask.java:355)                         at java.util.concurrent.FutureTask.setException (FutureTask.java:222)                         at java.util.concurrent.FutureTask.run (FutureTask.java:242)                         at android.os.AsyncTask $ SerialExecutor $ 1.run (AsyncTask.java:231)                         at java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1112)                         at java.util.concurrent.ThreadPoolExecutor $ Worker.run (ThreadPoolExecutor.java:587)                         at java.lang.Thread.run (Thread.java:831)                      Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void   com.citizen.port.android.BluetoothPort.connect (java.lang.String) 'on a   null object reference                         at mx.com.oncontrol.oncontroldesconnected.Login $ AsyncBluetooth.doInBackground (Login.java:506)                         at mx.com.oncontrol.oncontroldesconnected.Login $ AsyncBluetooth.doInBackground (Login.java:485)                         at android.os.AsyncTask $ 2.call (AsyncTask.java:288)                         at java.util.concurrent.FutureTask.run (FutureTask.java:237)                         at android.os.AsyncTask $ SerialExecutor $ 1.run (AsyncTask.java:231)                         at java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1112)                         at java.util.concurrent.ThreadPoolExecutor $ Worker.run (ThreadPoolExecutor.java:587)                         at java.lang.Thread.run (Thread.java:831)

bluetooth port function that I use to connect to the printer

 public void connect(String address) throws IOException {
        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        BluetoothDevice bluetoothDevice = mBluetoothAdapter.getRemoteDevice(address);
        if(mBluetoothAdapter.isDiscovering()) {
            mBluetoothAdapter.cancelDiscovery();
        }

        if(!this.isValidAddress(address)) {
            throw new IOException("Bluetooth Address is not valid.");
        } else {
            this.setBTSocket(bluetoothDevice);
            this.connectCommon();
        }
    }
    
asked by Hugo Rodriguez 21.12.2016 в 17:03
source

1 answer

1

I see that when you start your application ( onCreateView() ), you call the bluetoothSetup() method, which is the one that enables Bluetooth.

Modify your method in the part where you find that the Adapter is not enabled.

  public void bluetoothSetup()
    {
        // Initialize
        clearBtDevData();
        bluetoothPort = BluetoothPort.getInstance();
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null)
        {
            // Device does not support Bluetooth
            return;
        }
        if (!mBluetoothAdapter.isEnabled())
        {
             //Habilita Bluetooth!
             mBluetoothAdapter.enable(); 

            //Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            //startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }
    }

You do not need to perform Intent , in fact using startActivityForResult() you do not have a onActivityResult method to perform any action.

Enable Bluetooth :

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();    
if (!mBluetoothAdapter.isEnabled()) {//No esta activo?
    mBluetoothAdapter.enable(); //Habilita Bluetooth.
}else{
  Toast.makeText(getApplicationContext(), "Bluetooth esta actualmente activo!", Toast.LENGTH_LONG).show();
}

Disable Bluetooth :

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();    
if (mBluetoothAdapter.isEnabled()) { //Esta activo?
    mBluetoothAdapter.disable(); //deshabilita Bluetooth.
}
    
answered by 22.12.2016 в 00:01