连接蓝牙设备

时间:2016-08-11 19:43:15

标签: android android-bluetooth

大家好,我尝试将我的arduino连接到我的项目,但是我的代码出错了 问题是当我写这段代码 BluetoothDevice aygit = intent.getParcelableArrayExtra(BluetoothDevice.EXTRA_DEVICE);此代码给我错误 如何解决我的问题。

我的代码:

package com.softengine.mehmet.bluetooth;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.bluetooth.BluetoothDevice;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
import android.os.Handler;

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {

    Button ledAc, ledKapat;
    TextView text;
    ListView liste;
    public static final UUID myUUID = UUID.fromString("00000000-0000-1000-8000-00805F9B34FB");
    public static final int baglanti = 0;
    public static final int mesajOku = 1;
    OutputStream outstream;
    InputStream instream;
    ArrayAdapter<String> adapterListesi;
    BluetoothAdapter blt;
    ArrayList<String> eslesen;
    ArrayList<BluetoothDevice> aygitlar;
    IntentFilter filtre;
    BroadcastReceiver receiver;
    Set<BluetoothDevice> deviceArray;
    Handler mHandler=new Handler(){
        public void handleMessage(Message msg){
            super.handleMessage(msg);
            switch (msg.what){
                case baglanti:
                    ConnectedThread connectedThread=new ConnectedThread((BluetoothSocket)msg.obj);
                    text.setText("Bağlandı");
                    break;
                case mesajOku:
                    byte[] bufoku=(byte[])msg.obj;
                    String str=new String(bufoku);
                    Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        liste = (ListView) findViewById(R.id.listView);
        liste.setOnItemClickListener(this);
        adapterListesi = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_activated_1, 0);
        liste.setAdapter(adapterListesi);

        blt = BluetoothAdapter.getDefaultAdapter();
        eslesen = new ArrayList<String>();

        filtre = new IntentFilter(BluetoothDevice.ACTION_FOUND);//biz sadece yanımızda olan bluetoth cihazları ile işlem yapmak için kullanıyoruz
        aygitlar = new ArrayList<BluetoothDevice>();

        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();

                //xxxxx problem problem problem problem problem xxxxxxx

                if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                    BluetoothDevice aygit = intent.getParcelableArrayExtra(BluetoothDevice.EXTRA_DEVICE);
                    aygitlar.add(aygit);
                    String s = "";
                    for (int i = 0; i < eslesen.size(); i++) {
                        if (aygit.getName().equals(eslesen.get(i))) {
                            s = "Eslesti";
                            break;
                        }
                    }
                    adapterListesi.add(aygit.getName() + "" + s + "" + "\n" + aygit.getAddress());
                } else if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
                    if (blt.getState() == blt.STATE_OFF) {
                        bltAc();
                    }
                }
            }
        };

        registerReceiver(receiver, filtre);
        filtre = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
        registerReceiver(receiver, filtre);

        if (blt == null) {
            Toast.makeText(MainActivity.this, "Cihaz bluetooth teknolojisini desteklemiyor", Toast.LENGTH_SHORT).show();
            text.setText("Bluetooth  Yok");
        } else {
            if (blt.isEnabled()) {
                bltAc();
            }
            secim();
            startDiscovery();

            ledAc = (Button) findViewById(R.id.btnAc);
            ledAc.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    try {
                        ledOn();
                    } catch (IOException e) {

                    }
                }
            });
            ledKapat = (Button) findViewById(R.id.btnKapat);
            ledKapat.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    try {
                        ledOff();

                    } catch (IOException e) {
                    }
                }
            });
        }


    }

    private void ledOff() throws IOException {
        outstream.write("2".getBytes());
    }

    private void ledOn() throws IOException{
        outstream.write("1".getBytes());
    }


    private void startDiscovery() {

        blt.cancelDiscovery();
        blt.startDiscovery();
    }

    private void secim() {
        deviceArray = blt.getBondedDevices();//eşlesen cihazları atadık
        if (deviceArray.size() > 0) {
            for (BluetoothDevice aygit : deviceArray) {
                eslesen.add(aygit.getName());
            }
        }

    }

    private void bltAc() {
        Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(intent, 1);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RESULT_CANCELED) {
            Toast.makeText(MainActivity.this, "Bluetooth aygıtını açın", Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (blt.isDiscovering()) {
            blt.cancelDiscovery();

        }
        if (adapterListesi.getItem(position).contains("Eslesti")) {
            BluetoothDevice secilenAygit = aygitlar.get(position);
            ConnectThread connect = new ConnectThread(secilenAygit);
            connect.start();
        } else {
            Toast.makeText(MainActivity.this, "Aygıta balanılamadı", Toast.LENGTH_SHORT).show();
        }

    }

    private class ConnectThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final BluetoothDevice mmDevice;

        public ConnectThread(BluetoothDevice aygit) {
            BluetoothSocket tmp = null;
            mmDevice = aygit;
            try {
                tmp = aygit.createRfcommSocketToServiceRecord(myUUID);

            } catch (IOException e) {
                text.setText("Bağlantı Yok");
            }
            mmSocket = tmp;

        }

        @Override
        public void run() {
            blt.cancelDiscovery();
            try {
                mmSocket.connect();
            } catch (IOException e) {
                try {
                    mmSocket.close();
                } catch (IOException ee) {

                }
                return;

            }
            mHandler.obtainMessage(baglanti,mmSocket).sendToTarget();
        }
        public void cancel(){

            try {
                mmSocket.close();
            }catch (Exception e){}
        }
    }

    private class ConnectedThread extends Thread{
        private final BluetoothSocket mmSocket;

        public ConnectedThread(BluetoothSocket socket){
            InputStream tmpIn=null;
            OutputStream tmpOut=null;
            try {
                tmpIn=socket.getInputStream();
                tmpOut=socket.getOutputStream();
            }catch (IOException e){

            }
            instream =tmpIn;
            outstream=tmpOut;
        }
        public void run(){
            byte[]buffer;
            int bytes;
            while (true){
                try {
                    buffer=new byte[1024];
                    bytes=instream.read(buffer);
                    mHandler.obtainMessage(mesajOku,bytes,-1,buffer).sendToTarget();;
                }catch (IOException e){break;}
            }

        }
        public void cancel(){

            try {
                mmSocket.close();
            }catch (Exception e){}
        }
    }
}

0 个答案:

没有答案