通过蓝牙连接两个设备(java android)

时间:2014-05-30 13:31:40

标签: java android connect

我想通过蓝牙连接两台设备进行数据传输。我尝试按网站http://developer.android.com/guide/topics/connectivity/bluetooth.html中的说明制作。我的应用程序可以发现并配对但无法连接。尽管付出了很多努力,我还是不明白为什么。代码;

        package com.example.bluetooth_v1;  // paketin ismi girilicek

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.app.Activity;
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.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity  implements OnItemClickListener
{

public static final int SUCCESS_CONNECT =0;
public static final int MESSAGE_READ = 1 ;
public static final UUID MY_UUID = UUID.fromString("00000000-2ef2-4138-ffff-   
fffff16071b8");
public static final int STATE_CONNECTING = 2;
ArrayAdapter<String>  liste;
Button baglan;
ListView listeG;
BluetoothAdapter bAdapter;
Set<BluetoothDevice> aygitDizisi;
IntentFilter filtre;
BroadcastReceiver  alici;
ArrayList<String> pairedDevices;
ArrayList<BluetoothDevice> devices; 
Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
    // TODO Auto-generated method stub
    super.handleMessage(msg);
    switch(msg.what){
    case SUCCESS_CONNECT:
        ConnectedThread connectedThread = new 
  ConnectedThread((BluetoothSocket)msg.obj);
        Toast.makeText(getApplicationContext(), "CONNECT", 300).show();
        String s="successfully connected";
        connectedThread.write(s.getBytes()); 
        Log.i("uyarı", "connected");
        break;
    case MESSAGE_READ:
        byte[] readBuf=(byte[])msg.obj;
        String string= new String(readBuf);
        break;
    }
}
};

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

    init();
    if(bAdapter==null){
        Toast.makeText(getApplicationContext(), "blu yok", 0).show();
        finish();   
    }

    else {
        if(!bAdapter.isEnabled()){

            turnOnBT();
        }
        getPairedDevices(); 
        startDiscovery();

    }

}

private void startDiscovery() {
    bAdapter.cancelDiscovery();
    bAdapter.startDiscovery();

}



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

}

private void getPairedDevices() {
    aygitDizisi=bAdapter.getBondedDevices();
    if(aygitDizisi.size()>0){
        for(BluetoothDevice device:aygitDizisi){
            pairedDevices.add(device.getName());
        }
    }

}

private void init() {

    listeG=(ListView) findViewById(R.id.listView1);
    liste =new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,0);
    listeG.setAdapter(liste);
    listeG.setOnItemClickListener(this);
    bAdapter= BluetoothAdapter.getDefaultAdapter();
    filtre=new IntentFilter(BluetoothDevice.ACTION_FOUND);
    pairedDevices = new ArrayList<String>();
    devices=new ArrayList<BluetoothDevice>();
    alici = new BroadcastReceiver(){                 // ACTION_FOUND için broadcast
   oluşturduk(*******)
        @Override
        public void onReceive(Context context, Intent intent) {//bilgiler alındı
        String action=intent.getAction();

        if(BluetoothDevice.ACTION_FOUND.equals(action)){//discovery  cihazı  
       bulduğunda bilgileri intenten al.
            BluetoothDevice 
    device=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            devices.add(device);
            String s="";

            for(int a = 0;a<pairedDevices.size();a++){
                if(device.getName().equals(pairedDevices.get(a))){              
                    s="(paired)";
                    break;
                }

        }
            liste.add(device.getName()+" "+s+" "+"\n"+device.getAddress());
        }
        else if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){

        }
        else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){ 

                    }           

        else if(BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)){

            if(bAdapter.getState()==bAdapter.STATE_OFF){

            }

          }

        }

    };
    registerReceiver(alici, filtre);
     filtre=new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
    registerReceiver(alici, filtre);
     filtre=new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    registerReceiver(alici, filtre);
     filtre=new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
}

@Override
    protected void onPause() {
        super.onPause();
        //unregisterReceiver(alici);
    }
@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent
    data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==RESULT_CANCELED){
            Toast.makeText(getApplicationContext(), "devam etmek için 
   blu aç", Toast.LENGTH_LONG).show();
            finish();
        }
    } 

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
        long arg3) {
    if(bAdapter.isDiscovering()){
        bAdapter.cancelDiscovery();
    }
    if(liste.getItem(arg2).contains("paired")){

            BluetoothDevice selectedDevice = devices.get(arg2);
            ConnectThread connect = new ConnectThread(selectedDevice);
            bAdapter.cancelDiscovery();
            connect.start();  

            Log.i("uyarı", "in click listener");        
    }  
    else{
        Toast.makeText(getApplicationContext(), "Cihaz eşlenmedi",  
    0).show();
    }

}
private class ConnectThread extends Thread {

    private final BluetoothSocket mmSocket;
    private final BluetoothDevice mmDevice;

    public ConnectThread(BluetoothDevice device) {
        // Use a temporary object that is later assigned to mmSocket,
        // because mmSocket is final
        BluetoothSocket tmp = null;
        mmDevice = device;

        // Get a BluetoothSocket to connect with the given BluetoothDevice
        try {
            // MY_UUID is the app's UUID string, also used by the server code
            tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) { }
        mmSocket = tmp;
    }

    public void run() {
        // Cancel discovery because it will slow down the connection
        bAdapter.cancelDiscovery();
        Log.i("uyarı", "connect-run");
        try {
            // Connect the device through the socket. This will block
            // until it succeeds or throws an exception
            mmSocket.connect(); 
            Log.i("uyarı", "connect succeded");
        } catch (IOException connectException) {Log.i("uyarı", "connected failed");
            // Unable to connect; close the socket and get out
            try {
                mmSocket.close();
            } catch (IOException closeException) { }
            return;
        }

        // Do work to manage the connection (in a separate thread)

       mHandler.obtainMessage(SUCCESS_CONNECT,mmSocket).sendToTarget();

    }       

    /** Will cancel an in-progress connection, and close the socket */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
}
private class ConnectedThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;

    public ConnectedThread(BluetoothSocket socket) {
        mmSocket = socket;
        InputStream tmpIn =  null;
        OutputStream tmpOut = null;

        // Get the input and output streams, using temp objects because
        // member streams are final
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) { }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }

    public void run() {
        byte[] buffer ;// buffer store for the stream
        int bytes; // bytes returned from read()

        // Keep listening to the InputStream until an exception occurs
        while (true) {
            try {
                // Read from the InputStream
                buffer = new byte[1024];  
                bytes = mmInStream.read(buffer);
                mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
                .sendToTarget();
                // Send the obtained bytes to the UI activity

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

    /* Call this from the main activity to send data to the remote device */
    public void write(byte[] bytes) {
        try {
            mmOutStream.write(bytes);
        } catch (IOException e) { }
    }

    /* Call this from the main activity to shutdown the connection */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
}
}

此调试输出;    我的调试输出;

              05-30 16:23:42.302: I/uyarı(3533): in click listener
              05-30 16:23:42.307: I/uyarı(3533): connect-run
              05-30 16:23:44.937: I/uyarı(3533): connected failed
              05-30 16:23:48.837: I/uyarı(3533): in click listener
              05-30 16:23:48.842: I/uyarı(3533): connect-run
              05-30 16:23:49.962: I/uyarı(3533): connected failed

Eclipse调试输出

        05-30 16:21:34.027: E/ActivityThread(2974): android.app.IntentReceiverLeaked: 
              Activity com.example.bluetooth_v1.MainActivity has leaked IntentReceiver 
              com.example.bluetooth_v1.MainActivity$2@414513f8 that was originally 
              registered here. Are you missing a call to unregisterReceiver()?

0 个答案:

没有答案