怎么连接蓝牙啊!为什么连接不上TAT,,

怎么连接蓝牙啊!为什么连接不上TAT,,

public class MainActivity extends AppCompatActivity  implements DeviceFragment.OnDeviceSelected{

    private static final int REQUEST_SELECT_IMAGE=1;
    private static final int REQUEST_ENABLE_BLUETOOTH=10;
    private Bitmap bitmap=null;
    private BluetoothAdapter mBlueToothAdapter=null;
    private ImageView mImg;
    private Button mBtnSelectImg;
    private Button mBtnSendImg;
    private BluetoothDevice mmmDevice=null;
    private BluetoothService mService=null;
    

    Handler mHandler =new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case Constants.MESSAGE_STATE_CHANGE:
                    switch (msg.arg1){
                        case BluetoothService.STATE_CONNECTING:
                            getSupportActionBar().setSubtitle("正在连接中...");
                    }
            }
        }
    };


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

        mBlueToothAdapter = BluetoothAdapter.getDefaultAdapter();
        if(mBlueToothAdapter==null){
            Toast.makeText(this, "设备不支持蓝牙", Toast.LENGTH_SHORT).show();
            finish();
        }
        initView();
        initEvent();

    }

    private void initEvent() {

        mBtnSelectImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //获取本地图片
                Intent getAlbum=new Intent(Intent.ACTION_GET_CONTENT);
                getAlbum.setType("image/*");
                startActivityForResult(getAlbum,REQUEST_SELECT_IMAGE);
            }
        });

        mBtnSendImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //TODO
            }
        });
    }

    private void initView() {
        mImg=(ImageView) findViewById(R.id.id_img);
        mBtnSelectImg=(Button) findViewById(R.id.id_select_img);
        mBtnSendImg=(Button) findViewById(R.id.id_send_img);
    }

    private void showToast(String msg){
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.my_menu,menu);
        ActionBar supportActionBar = getSupportActionBar();
        supportActionBar.setTitle("慕课快传");
        supportActionBar.setSubtitle("未连接");
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.bluetooth:
                DeviceFragment df=new DeviceFragment();
                FragmentTransaction ft=getSupportFragmentManager().beginTransaction();
                ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                df.show(ft,"df");
                break;

            case R.id.id_show_device:
                Intent discoverableIntent = new
                        Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
                startActivity(discoverableIntent);
                break;
            case R.id.id_clear_img:
                showToast("清除图片?");
                break;
        }
        return super.onOptionsItemSelected(item);
    }

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

        if(requestCode==REQUEST_SELECT_IMAGE){
            Uri uri=data.getData();
            String img_url=uri.getPath();
            ContentResolver cr=this.getContentResolver();
            try {
                bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            mImg.setImageBitmap(bitmap);

        }

        if(requestCode==REQUEST_ENABLE_BLUETOOTH){
            Toast.makeText(this,"蓝牙已经开启",Toast.LENGTH_SHORT).show();
        }

        super.onActivityResult(requestCode, resultCode, data);

    }


    @Override
    public void onDeviceSeleted(BluetoothDevice bluetoothDevice) {
        Log.i("123", "onDeviceSeleted: ");
        mmmDevice=bluetoothDevice;
        mService=new BluetoothService(MainActivity.this,mHandler);

        gogogo();

    }

    //开始连接蓝牙。
    private void gogogo(){
        if(mService!=null){
            if(mService.getState() ==BluetoothService.STATE_NONE){
                mService.start();
                Log.i("123", "onDeviceSeleted: start!");
                mService.connect(mmmDevice);

            }
        }

    }
    

}

public class BluetoothService {
    private static final String TAG = "BluetoothChatService";

    private BluetoothAdapter mAdapter;
    private Handler mHandler;
    private int mState;

    private AcceptThread mAccpetThread;
    private ConnectThread mConnectThread;

    private static final String NAME_SECURE = "BluetoothChatSecure";

    private static final UUID MY_UUID_SECURE =
            UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");

    public static final int STATE_NONE = 0;       // we're doing nothing
    public static final int STATE_LISTEN = 1;     // now listening for incoming connections
    public static final int STATE_CONNECTING = 2; // now initiating an outgoing connection
    public static final int STATE_CONNECTED = 3;  // now connected to a remote device


    public BluetoothService(Context context,Handler handler){
        mAdapter=BluetoothAdapter.getDefaultAdapter();
        mHandler=handler;
        mState=STATE_NONE;
    }


    public void start(){
        Log.i("123","start start");
        if(mAccpetThread==null){
            mAccpetThread=new AcceptThread(true);
            mAccpetThread.start();
        }
    }

    public void connect(BluetoothDevice device){
        Log.i("123","connect connect");
        mConnectThread=new ConnectThread(device);
        mConnectThread.start();
        setState(STATE_CONNECTING);
    }

    public void setState(int mState) {
        this.mState = mState;
    }

    public int getState() {

        return mState;
    }

    private class AcceptThread extends Thread {

        //Local server socket
        private final BluetoothServerSocket mServerSocket;
        public AcceptThread(boolean secure) {
            Log.i("123","AcceptThread 构造");
            BluetoothServerSocket tmp=null;
            try {
                tmp = mAdapter.listenUsingRfcommWithServiceRecord(NAME_SECURE, MY_UUID_SECURE);
            } catch (IOException e) {
                Log.e(TAG, "AcceptThread: ",e );
            }
            mServerSocket=tmp;
        }

        public void run(){
            Log.i("123","AcceptThread Run");
            BluetoothSocket socket=null;

            while (mState!=STATE_CONNECTED){
                Log.i("123","mState!=STATE_CONNECTED ");
                try {
                    socket=mServerSocket.accept();
                } catch (IOException e) {
                    Log.e(TAG, "accept() failed",e );
                    break;
                }

                //如果连接;
                if (socket!=null) {
                    Log.i("123","连接成功啊!!! ");
                }
            }
        }
    }

    private class ConnectThread extends  Thread{
        private final  BluetoothSocket mSocket;
        private final BluetoothDevice mDevice;

        public ConnectThread(BluetoothDevice device){
            Log.i("123","ConnectThread 构造");
            mDevice=device;
            BluetoothSocket tmp=null;

            try {
                tmp = device.createRfcommSocketToServiceRecord(MY_UUID_SECURE);
            } catch (IOException e1) {
                e1.printStackTrace();
            }

            mSocket=tmp;
        }

        public void run(){

            Message msg=new Message();
            msg.what=Constants.MESSAGE_STATE_CHANGE;
            msg.arg1=STATE_CONNECTING;
            mHandler.sendMessage(msg);
            setState(STATE_CONNECTING);
            Log.i("123","ConnectThread Run");
            mAdapter.cancelDiscovery();

            try {
                mSocket.connect();
            } catch (IOException e) {
                try {
                    mSocket.close();
                    Log.i("123","ConnectThread close");
                } catch (IOException e1) {
                    Log.e(TAG, "unable to close() socket during connection failure",e );
                }
                return;
            }
        }
    }
}


正在回答 回答被采纳积分+1

登陆购买课程后可参与讨论,去登陆

3回答
irista23 2018-05-28 11:59:55

你的真机是Android6.0+吗?如果是添加下定位权限:

<uses-permission-sdk-23 android:name="android.permission.ACCESS_COARSE_LOCATION"/> 
<uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED"/>  
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
    if(Build.VERSION.SDK_INT >= 23){  
        //6.0以上设备  
        int checkCallPhonePermission = checkSelfPermission(Manifest.permission.  
                ACCESS_COARSE_LOCATION);  
        if(checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {  
             requestPermissions(new String[]{Manifest.permission.  
                    ACCESS_COARSE_LOCATION}, REQUEST_PERMISSION_LOCATION);  
            return;  
        }  
    }


好帮手慕雪 2018-05-27 17:11:00

你是说 Log.i("123","连接成功啊!!! ");没执行?那你得给全代码才能看出来哦。另:你还得确定两个真机的蓝牙都开启了哈。

  • 提问者 CV工程师鱼 #1
    对,连接成功那里没执行,,这不是已经是全部代码了吗, 我用一台真机运行APP来连接另一台真机的蓝牙
    2018-05-27 18:57:16
提问者 CV工程师鱼 2018-05-26 18:29:32

DialogFragment返回的Device是没问题的。。

问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
Android数据通信开发与应用2018版
  • 参与学习           人
  • 提交作业       147    份
  • 解答问题       687    个

本专题介绍了Android开发核心组件:广播、服务及全局应用。教会你如何使用AIDL、Thread、Socket、蓝牙解决进程线程间通信问题。利用Glide等实现异步加载及NDK原生代码开发。

了解课程
请稍等 ...
意见反馈 帮助中心 APP下载
官方微信

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师