Bluetooth Suche beenden

J

jdajul

Ambitioniertes Mitglied
1
Hallo, ich habe eine Frage bezüglich meiner aktuellen App.
Ich möchte gerne über Bluetooth auf ein anderes Gerät zugreifen. Die umliegenden Geräte sollen von der App gesucht werden, per Click möchte ich dann mit einem Gerät verbinden.
Das klappt soweit auch, das einzige Problem ist, dass auch nachdem die App mit einem Gerät verbunden ist, weitere Geräte gesucht werden.
Wie kann ich das ausschalten?

Vielen Dank für die Hilfe!

Code:
public class MainActivity extends ActionBarActivity {
    BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
    static final boolean D = true;
    static final int REQUEST_ENABLE_BT = 2;
    static final String TAG = "Bluetooth";
    // String for MAC address
    static String mydeviceaddress;
    // SPP UUID service - this should work for most devices
    static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    BluetoothSocket btSocket = null;
    //BTConnHelper btconn;
    ConnectedThread mConnectedThread;
    Handler bluetoothIn;
    final int handlerState = 0; //used to identify handler message

    GUIHelper gui;
    SeekBar Master, Channel1, Channel2, Channel3, Channel4, Channel5, Channel6;
    CheckBox MuteMaster, Mute1, Mute2, Mute3, Mute4, Mute5, Mute6;
    Button settings;
    TextView textView;
    ArrayAdapter<String> mArrayAdapter;
    ArrayList arrayList;
    ListView lv;
    BroadcastReceiver mReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initializeVariables();
        bluetooth = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth adapter
        deviceSupportBluetooth();//?
        setDeviceToast();
        seekbarconfig(Master, "Master");
        seekbarconfig(Channel1, "Channel1");
        //    gui.seekbarconfig(Master);
        //    mConnectedThread.write("test");
        settings.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent in = new Intent(MainActivity.this, Settings.class);
//                startActivity(in);
                ConnectedThread CT = new ConnectedThread(btSocket);
                try {
                    btSocket.connect();
                } catch (Exception e) {
                    //,,,
                }
                CT.write("send 1...");
                System.out.println("send 1...");
            }


        });


        // connectToDevice();


    }

    public void seekbarconfig(SeekBar seekBar, final String fadername) {
        // Initialize the textview with '0'.
        textView.setText("Covered: " + seekBar.getProgress() + "/" + seekBar.getMax());
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            int progress = 0;


            @Override
            public void onProgressChanged(SeekBar seekBar, int progressValue, boolean fromUser) {
                progress = progressValue;

                Toast.makeText(getApplicationContext(), "Changing"+fadername+"progress" + progressValue, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                Toast.makeText(getApplicationContext(), "Started tracking seekbar", Toast.LENGTH_SHORT).show();
            }


            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                textView.setText("Covered: " + progress + "/" + seekBar.getMax());
                Toast.makeText(getApplicationContext(), "Stopped tracking seekbar", Toast.LENGTH_SHORT).show();
            }
        });
    }


    private void initializeVariables() {
        arrayList = new ArrayList();


    }

    @Override
    public void onStart() {
        super.onStart();
        if (D) Log.e(TAG, "++ ON START ++");

        // If BT is not on, request that it be enabled.
        checkIfBluetoothisEnabled();
        connectToDevice();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (D) Log.e(TAG, "++ ON DESTROY ++");
        unregisterReceiver(mReceiver);
    }

    @Override
    public synchronized void onResume() {
        super.onResume();
        if (D) Log.e(TAG, "+ ON RESUME +");

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public void deviceSupportBluetooth() {
        if (bluetooth == null) {
            Toast.makeText(this, "Your Device does not support Bluetooth", Toast.LENGTH_LONG).show();
            finish();
            return;

        }
    }

    public void setDeviceToast() {
        String status;
        if (bluetooth.isEnabled()) {
            mydeviceaddress = bluetooth.getAddress();
            String mydevicename = bluetooth.getName();

            int state = bluetooth.getState();
            status = mydevicename + " : " + mydeviceaddress + " : " + state;

        } else {
            status = "Bluetooth is not Enabled.";
        }
        System.out.println("Bluetooth Status " + status);
    }

    public BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
        return device.createInsecureRfcommSocketToServiceRecord(BTMODULEUUID);
//creates secure outgoing connecetion with BT device using UUID
    }

    public 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(), "Connection Failure", Toast.LENGTH_LONG).show();
                finish();
            }
        }
    }

    public void checkIfBluetoothisEnabled() {
        if (!bluetooth.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
            // Otherwise, setup the control session
        } else {
            //do here the bluetooth work
        }
    }


    public void connectToDevice() {


        lv = (ListView) findViewById(R.id.listView);
        final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
                this,
                android.R.layout.simple_list_item_1,
                arrayList
        );
       
        //getting new devices...

        //arrayList.add("ab hier neue geraete");
        bluetooth.startDiscovery();
        if (bluetooth.startDiscovery()) {
            System.out.println("discovery started");
            mReceiver = new BroadcastReceiver() {
                public void onReceive(Context context, Intent intent) {
                    String action = intent.getAction();
                    System.out.println("onreceive called");

                    if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);


                        arrayAdapter.add(device.getName() + "\n" + device.getAddress());
                        //bluetooth.cancelDiscovery();
                        System.out.println("while onreceive" + arrayList);
                    } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                        Log.v(TAG, "Entered the Finished ");
                        bluetooth.cancelDiscovery();
                    } else {
                        System.out.println("hoppala da funktioniet was nciht");
                    }
                }

            };

            IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
            registerReceiver(mReceiver, filter);


        }

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                                    long arg3) {
                // TODO Auto-generated method stub
                String devicehelper = arrayList.get(position).toString();
                String[] device = devicehelper.split("\n");
                String deviceName = device[0];
                String deviceMAC = device[1];
                System.out.println(device[1]);
                connectWithDeviceNow(deviceMAC);
            }
        });

        lv.setAdapter(arrayAdapter);


    }

    public void connectWithDeviceNow(String MAC) {
        //   create device and set the MAC address
        BluetoothDevice device = bluetooth.getRemoteDevice(MAC);//mydeviceaddress
        System.out.println("devicename: " + device + device.getName());
        bluetooth.cancelDiscovery();
        try {
            btSocket = createBluetoothSocket(device);
        } catch (IOException e) {
            Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_LONG).show();
        }
// Establish the Bluetooth socket connection.
        try {
            btSocket.connect();
            Toast.makeText(getBaseContext(), "Mit Gerät " + device.getName() + " verbunden", Toast.LENGTH_LONG);

        } catch (IOException e) {
            Toast.makeText(MainActivity.this, "Gerät ausgeschaltet \n oder nicht in Reichweite", Toast.LENGTH_LONG);

            try {
                btSocket.close();

            } catch (IOException e2) {
                System.out.println("Socket closing doesnt work!");

//insert code to deal with this
            }
        }
        //  System.out.println("btconn is: "+btconn);
        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
    }


}
 

Ähnliche Themen

S
Antworten
4
Aufrufe
4.376
mblaster4711
mblaster4711
A
Antworten
10
Aufrufe
1.017
swa00
swa00
Hansimglueck0815
Antworten
0
Aufrufe
731
Hansimglueck0815
Hansimglueck0815
Zurück
Oben Unten