Android:@Override handleMessage未被调用

时间:2015-12-07 09:01:28

标签: android bluetooth handler android-handler

因此,我要将自己的皮肤从脸上拉下来,这让我感到很沮丧。我试图捕获通过蓝牙发送的数据,并且Handler的handleMessage()方法不会触发。有人可以帮忙吗?

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();
    private static final String BT_UUID = "a2cd7958-5745-450c-9dfc-48ad58ca8d95";

    private static final int MESSAGE_READ = 999;

    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothDevice mDevice;
    private BluetoothSocket mBluetoothSocket;

    private Handler mConnectionHandler;

    private RelativeLayout mConnectionLayout;

    private static MainActivity mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        Intent intent = getIntent();
        mDevice = intent.getParcelableExtra("device");

        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        mConnectionLayout = (RelativeLayout)findViewById(R.id.connection_overlay);
        mContext = this;
    }

    @Override
    public void onResume() {
        super.onResume();
        attemptBluetoothConnection();
    }

    public void attemptBluetoothConnection() {
        UUID uuid = UUID.fromString(BT_UUID);
        try {
            mBluetoothSocket = mDevice.createInsecureRfcommSocketToServiceRecord(uuid);
            Log.v("[bluetooth]", "creating RF Comm channel...");
        } catch (IOException e) {
            e.printStackTrace();
            mBluetoothSocket = null;
        }
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                if (mBluetoothSocket != null) {
                    Log.v(TAG, "socket not null, attempting connection...");
                    try {
                        mBluetoothSocket.connect();
                        Log.d(TAG, "Connection made!");
                        mConnectionLayout.setVisibility(View.GONE);
                    } catch (IOException e) {
                        Log.e(TAG, e.getMessage());
                        try {
                            Log.v(TAG, "Trying fallback");
                            mBluetoothSocket = (BluetoothSocket) mDevice.getClass().getMethod("createInsecureRfcommSocket", new Class[]{int.class}).invoke(mDevice, 1);
                            mBluetoothSocket.connect();
                            mConnectionLayout.setVisibility(View.GONE);
                            mConnectionHandler = new Handler() {
                                @Override
                                public void handleMessage(Message msg) {
                                    Log.v(TAG, "[handleMessage]");
                                    switch (msg.what) {
                                        case MESSAGE_READ:
                                            String data = new String((byte[])msg.obj, 0, msg.arg1);
                                            Log.v(TAG, "Received Data: (" + data.length() + ") " + data);
                                    }
                                }
                            };
                            mConnectionHandler.post(new ConnectedThread(mBluetoothSocket));
                            Log.v(TAG, "Connection made!");
                        } catch (Exception e2) {
                            e2.printStackTrace();
                        }
                        Log.d("Connection not made...", "");
                    }
                } else {
                    Log.v("[bluetooth]", "socket is null...");

                }
            }
        });
    }

    public 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 = new byte[1024];  // buffer store for the stream
            int bytes; // bytes returned from read()

            // Keep listening to the InputStream until an exception occurs
            while (true) {
                Log.v(TAG, "Reading InputStream...");
                try {
                    // Read from the InputStream
                    bytes = mmInStream.read(buffer);
                    // Send the obtained bytes to the UI activity
                    Log.v(TAG, "Sending to " + mConnectionHandler.obtainMessage().getTarget().toString());
                    mConnectionHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();
                } 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) { }
        }
    }
}

这段代码完美无缺,直到我开始进行它自己的独立活动。任何帮助表示赞赏。感谢。

0 个答案:

没有答案