android bluetooth Service discovery failed

paopao2013 发布于 2013/01/24 14:28
阅读 1K+
收藏 0

代码如下:在connect的那个地方有问题,连接不上,这个做客户端不做服务器端,然后连接电脑上的蓝牙设备不知道有什么问题

package my.namespace;




import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.UUID;

import javax.security.auth.PrivateCredentialPermission;

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.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;


public class BluetoothTransfer extends Activity {
    /** Called when the activity is first created. */
    private BluetoothReceiver bluetoothReceiver ;
    private BluetoothAdapter bluetoothAdapter;
    private BluetoothDevice rDevice = null;
    private BluetoothDevice device = null;
//    private BluetoothSocket mmSocket;
    private Button scanButton ;
    private Button discoverButton ;
    private Button connectBt;
    private TextView deviceAdress;
    private TextView messageRead;
    private TextView programClose;
    private String address;
    private String TAG = "hello";
//    private Handler mHandler;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        messageRead = (TextView)findViewById(R.id.messageRead);
        discoverButton = (Button)findViewById(R.id.discoverBt);
        scanButton = (Button)findViewById(R.id.scanBt);
        deviceAdress = (TextView)findViewById(R.id.DeviceAdress);
        discoverButton.setOnClickListener(new discoverBtListener());
        scanButton.setOnClickListener(new scanBtListener());
        connectBt = (Button)findViewById(R.id.connectBt);
        connectBt.setOnClickListener(new connectListener());
        programClose= (TextView)findViewById(R.id.programClose);
        IntentFilter intentFilter_all = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        bluetoothReceiver = new BluetoothReceiver();
        registerReceiver(bluetoothReceiver, intentFilter);
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    }
    
    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        if(bluetoothAdapter != null){    
            if(!bluetoothAdapter.isEnabled()){
                 Intent BlueEnable = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                 startActivity(BlueEnable);
             }
            deviceAdress.setText("start");
        }
        else
            programClose.setText("NO bluetoothAdapter fund,please quit");
        
    }
    class connectListener implements OnClickListener{

        public void onClick(View v) {
            // TODO Auto-generated method stub
            rDevice = bluetoothAdapter.getRemoteDevice(address);
        //    Toast.makeText(getApplicationContext(), "obtained",Toast.LENGTH_SHORT).show();
            ConnectThread mConnect = new ConnectThread(rDevice);
            mConnect.start();
        }
        
    }

    class discoverBtListener implements OnClickListener{

        public void onClick(View v) {
            // TODO Auto-generated method stub
            System.out.println("Visiable");
            Intent discoverEnbleIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            discoverEnbleIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 0);
            startActivity(discoverEnbleIntent);
        }
        
    }
    class scanBtListener implements OnClickListener{

        public void onClick(View v) {
            // TODO Auto-generated method stub
            
            if(bluetoothAdapter != null ){
                if(!bluetoothAdapter.isEnabled()){
                     Intent BlueEnable = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                     startActivity(BlueEnable);
                 }
                System.out.println("start discovery!");
                bluetoothAdapter.startDiscovery();
        /*        try{            
                    deviceAdress.setText(bluetoothReceiver.getDeviceName()+"\t"+bluetoothReceiver.getDeviceAddress());
                }catch(Exception e){
                    deviceAdress.setText("waiting");
                }*/
                
            }
            else{
                System.out.println("no Adapter find");
                deviceAdress.setText("no Adapter find");
            }
                
        }
        
    }
    class BluetoothReceiver extends BroadcastReceiver {
        

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            //modify by zhu
//            String action = intent.getAction();
//            if (BluetoothDevice.ACTION_FOUND.equals(action))
//            {
//                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//                if (device.getBondState() != BluetoothDevice.BOND_BONDED)
//                {
//                    Log.v(TAG, "find device:" + device.getName()+ device.getAddress());
//                }
//            }
//            else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action))
//            {
//                setTitle("搜索完成");
//            }
//            else
//            {
//                Log.v(TAG, "nothing ");
//            }
////            if (mNewDevicesAdapter.getCount() == 0)
////            {
////                Log.v(TAG,"find over");
////            }
//
//        }
//    }
    //modify end
            //
            System.out.println("Device Find");
            device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            if (device.getBondState() != BluetoothDevice.BOND_BONDED)
            {
                Log.v(TAG, "find device:" + device.getName()+ device.getAddress());
            }
            else
            {
                Log.v(TAG, "already paired!!!!!");
            }
            System.out.println(device.getAddress());
        //    if (device.getBondState() != BluetoothDevice.BOND_BONDED)
            if(device != null)
                deviceAdress.setText(device.getName()+"\t"+device.getAddress());
            else
                deviceAdress.setText("NO Device Fund");
            address = device.getAddress();
        }    
  /*    public String getDeviceName(){
            return device.getName();
        }
        public String getDeviceAddress(){
            return device.getAddress();
        }*/

    }
    private class ConnectThread extends Thread {       
        private final BluetoothSocket mmSocket;
        private final BluetoothDevice mmDevice;
        
        private  final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
        
        public ConnectThread(BluetoothDevice device) {
        BluetoothSocket tmp = null;
        mmDevice = device;
        Method m;
        System.out.println("discov" + device.getAddress());
        Log.v(TAG, "ConnectThread ok");
        try {
            int sdk = Integer.parseInt(Build.VERSION.SDK);
//            m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
//            tmp = (BluetoothSocket) m.invoke(device, 1);
//            if (sdk >= 10)
//            {
//                tmp = device.createInsecureRfcommSocketToServiceRecord(MY_UUID);
//            }
//            else
//            {
                tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
//            }
        
        } catch (IOException e) {Log.v(TAG, "异常!!!!!!!!!!!!!!"); }
        mmSocket = tmp;
        }
        
        public void run() {
        
            bluetoothAdapter.cancelDiscovery();
            try {
                mmSocket.connect();            } catch (IOException connectException) {
            // Unable to connect; close the socket and get out
                connectException.printStackTrace();
                System.out.println("连接异常" + connectException.getMessage());
                try {
                Log.v(TAG, "ConnectThread failed!!!!!!!!!!!!!!");
                mmSocket.close();
                } catch (IOException closeException) { }
                return;
              }        
            // Do work to manage the connection (in a separate thread)
            ConnectedThread IOmessage = new ConnectedThread(mmSocket);
            IOmessage.start();
        }
    }
    private class ConnectedThread extends Thread {
 //       private final BluetoothSocket mmSocket;
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;
     
        public ConnectedThread(BluetoothSocket socket) {
//            mmSocket = socket;
            System.out.println("startTrase");
            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();
                System.out.println("normal");
            } catch (IOException e) {
                System.out.println("getinException");
            }
     
            mmInStream = tmpIn;
            mmOutStream = tmpOut;
        }
     
        public void run() {
            System.out.println("startRun");
            byte[] buffer = new byte[1024];  // buffer store for the stream
            int bytes = 0; // bytes returned from read()
      //    int i=0;
            
            // Keep listening to the InputStream until an exception occurs
            while (true) {
                System.out.println("startRun2");
                try {                  
                    System.out.println("startRun3");
                    bytes= mmInStream.read(buffer);// Read from the InputStream   
                    System.out.println("startRun4");
             //     i++;
                    System.out.println("byte==" + bytes);
                    System.out.println("startRun5");
                    String readMessage = new String(buffer, 0, bytes);
                    System.out.println("startRun6");
                    System.out.println(readMessage);
                    messageRead.setText(readMessage);
                    System.out.println("startRun7");
             //       mHandler.obtainMessage(1, bytes, -1, buffer).sendToTarget(); // Send the obtained bytes to the UI Activity
                } catch (Exception e) {
                    System.out.println("Eception over");
                    break;
                }
            }
            System.out.println("Run over");
        }
     
        /* 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) { }
        }*/
    }
}
加载中
0
Lippor
Lippor
我也遇到了,不知道为什么
返回顶部
顶部