手机开发 - Android蓝牙模块连接后怎么接收数据?求助
PHPz
PHPz 2017-04-17 17:57:02
0
2
664
package myapplication.com.myapplicationble;

import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupMenu;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {

    private BluetoothAdapter BA;
    BluetoothServerSocket mmServerSocket;

    private static String address = "20:16:09:26:81:80"; // <==应填写蓝牙串口模块的蓝牙地址。
    private BluetoothSocket btSocket = null;
    private OutputStream outStream = null;
    public InputStream inStream = null;
    EditText editText;
    TextView textView;
    Button button, button1;
    private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

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

        initView();

    }
    /**
     * 连接蓝牙
     * **/
    public void connect() {
        BA = BluetoothAdapter.getDefaultAdapter();
        BluetoothDevice device = BA.getRemoteDevice(address);

//          pairedDevices = BA.getBondedDevices();
        try {
            btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
            new  ReceiveDatas(btSocket).start();
        } catch (IOException e) {
        }
        BA.cancelDiscovery();
        try {
            btSocket.connect();
            String s="sm\n";
            outStream = btSocket.getOutputStream();
            outStream.write(s.getBytes());
            //outStream.write(0x41);
            inStream = btSocket.getInputStream();
            Jieshou();
          //  System.out.println("**" + inStream.toString());
          //  System.out.println("**" + inStream.read());
           //  int x = inStream.read();
            //outStream.write(x+1);
           // System.out.println("****--"+x);



        } catch (IOException e) {
        }
        try {
          //  btSocket.close();
        } catch (Exception e2) {

            // Log .e(TAG,"ON RESUME: Unable to close socket during connection failure", e2);
        }
    }

    public void initView() {


        editText = (EditText) findViewById(R.id.edit);
        textView = (TextView) findViewById(R.id.textView);
        button = (Button) findViewById(R.id.button);
        button1 = (Button) findViewById(R.id.button1);
        BA = BluetoothAdapter.getDefaultAdapter();
       /**
        * 连接蓝牙
        * */
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.out.println("***11");
                as();
            }
        });
        /**
         * 发送信息 可以发送了
         * **/
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String s = editText.getText().toString().trim();
                try {
                    outStream = btSocket.getOutputStream();
                    inStream=btSocket.getInputStream();
                    outStream.write(s.getBytes());


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


    }



/**
 *
 *   连接蓝牙
 * **/
    public void as() {
        new AsyncTask() {

            @Override
            protected String doInBackground(Object[] params) {

                connect();
                return null;
            }

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }

            @Override
            protected void onPostExecute(Object o) {
                super.onPostExecute(o);
                Toast.makeText(getApplicationContext(), "2", Toast.LENGTH_SHORT).show();
            }
        }.execute();
    }
/**
     * 
     * */
    public  void Jieshou() {

        new Thread(new Runnable() {
            @Override
            public void run() {
                while(true){


                    ByteArrayOutputStream  byteArrayOutputStream=null;
                    byteArrayOutputStream = new ByteArrayOutputStream();
                    try {
                        inStream=btSocket.getInputStream();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    byte[] buffer = new byte[1024];// 缓冲数据流
                    int temp = 0;
                    //   while( (temp = inStream.read(buffer)) != -1) {
                    //  os.write(buffer, 0, temp);
                    byteArrayOutputStream.write(buffer, 0, temp);
                    //   }
                    System.out.println("*shuju*"+byteArrayOutputStream.toByteArray().toString());
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }
        }).start();
    }

  
}

已经可以发送信息到蓝牙了,可是怎么接收数据啊?求助

PHPz
PHPz

学习是最好的投资!

모든 응답(2)
大家讲道理

데이터를 받는 스레드를 찾았습니다...

으아아아
PHPzhong

글쓰는 방식이 좀 이상한 것 같아요...

mBluetoothGattCallback은 연결 상태를 콜백하고 데이터를 전송하는 데 사용되는 BluetoothGattCallback의 구현입니다. 자세한 내용은 Baidu에서 검색하거나 공식 문서를 읽어보세요

최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿