为多个活动启用蓝牙连接

时间:2016-12-19 05:29:05

标签: android service bluetooth bindservice

在我的应用程序中我想将多个活动的值发送到连接的Thread,我不知道解决这个问题请帮帮我 例:  我想发送String string =“#FFFFFF000 *”;从First-activity发送到服务类,                 String string =“#000000000 *”;从Second-activity到服务类

 public class BluetoothDataService1 extends Service {
        final int handlerState = 0;
        Handler bluetoothIn;
        private BluetoothAdapter btAdapter = null;

        private ConnectingThread mConnectingThread;
        private ConnectedThread mConnectedThread;

        private boolean stopThread;

        private static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

       // private static String MAC_ADDRESS="98:D3:31:30:A5:00" ;
        private static String MAC_ADDRESS="98:D3:32:20:42:54" ;

        private StringBuilder recDataString = new StringBuilder();
        private final IBinder binder = new LocalBinder();


        @Override
        public void onCreate() {
            super.onCreate();

            stopThread = false;

        }


        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            super.onStartCommand(intent, flags, startId);
            bluetoothIn = new Handler()
            {
                public void handleMessage(android.os.Message msg) {

                    if (msg.what == handlerState) {
                        String readMessage = (String) msg.obj;
                        recDataString.append(readMessage);


                    }
                    recDataString.delete(0, recDataString.length());
                }


            };

            btAdapter = BluetoothAdapter.getDefaultAdapter();
            checkBTState();
            return START_STICKY;
            //return super.onStartCommand(intent, flags, startId);
        }



        @Override
        public void onDestroy() {
            super.onDestroy();
            bluetoothIn.removeCallbacksAndMessages(null);
            stopThread = true;
            if (mConnectedThread != null ) {
                mConnectedThread.closeStreams();
            }
            if (mConnectingThread != null) {
                mConnectingThread.closeSocket();
            }

        }


        @Override
        public IBinder onBind(Intent intent)

        {
            return binder;
        }


        //Checks  Bluetooth is available and turned on /off
        private void checkBTState() {
            if (btAdapter == null) {

                stopSelf();
            } else {
                if (btAdapter.isEnabled()) {

                    try {
                        BluetoothDevice device = btAdapter.getRemoteDevice(MAC_ADDRESS);
                        mConnectingThread = new ConnectingThread(device);
                        mConnectingThread.start();
                    }   catch (IllegalArgumentException e) {

                        stopSelf();
                    }
                }   else {

                    stopSelf();
                }
            }
        }

    //    public void senddata() {
    //
    //    }

        // New Class for Connecting Thread
           public class ConnectingThread extends Thread {
            private final BluetoothSocket mmSocket;
            private final BluetoothDevice mmDevice;
            public ConnectingThread(BluetoothDevice device) {

                mmDevice = device;
                BluetoothSocket temp = null;

                try {

                    temp = mmDevice.createRfcommSocketToServiceRecord(BTMODULEUUID);

                }   catch (IOException e) {

                    stopSelf();
                }
                mmSocket = temp;
            }

            @Override
            public void run() {
                super.run();
                btAdapter.cancelDiscovery();
                try {
                    mmSocket.connect();
                    mConnectedThread = new ConnectedThread(mmSocket);
                    mConnectedThread.start();
                    mConnectedThread.write("x");
                } catch (IOException e) {
                    try {

                        mmSocket.close();
                        stopSelf();
                    } catch (IOException e2) {

                        stopSelf();

                    }
                } catch (IllegalStateException e) {

                    stopSelf();
                }
            }
            public void closeSocket() {
                try {

                    mmSocket.close();
                } catch (IOException e2) {

                    stopSelf();
                }
            }
        }

        // New Class for Connected Thread
        class ConnectedThread extends Thread {
            private final InputStream mmInStream;
            private final OutputStream mmOutStream;

            //creation of the connect thread
            public ConnectedThread(BluetoothSocket socket) {

                InputStream tmpIn = null;
                OutputStream tmpOut = null;

                try {
                    //Create I/O streams for connection
                    tmpIn = socket.getInputStream();
                    tmpOut = socket.getOutputStream();
                }   catch (IOException e) {

                    stopSelf();
                }

                mmInStream = tmpIn;
                mmOutStream = tmpOut;
            }

            public void run() {

                byte[] buffer = new byte[256];
                int bytes;

                // Keep looping to listen for received messages
                while (true && !stopThread) {
                    try {
                        bytes = mmInStream.read(buffer);
                        String readMessage = new String(buffer, 0, bytes);
                        //Send the obtained bytes to the UI Activity via handler
                        bluetoothIn.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();
                    }   catch (IOException e) {

                        stopSelf();
                        break;
                    }
                }
            }

            //write method
            public void write(String input) {
                byte[] msgBuffer = input.getBytes();
                try {
                    mmOutStream.write(msgBuffer);
                }   catch (IOException e) {
                    stopSelf();
                }
            }

            public void closeStreams() {
                try {
                    mmInStream.close();
                    mmOutStream.close();
                }   catch (IOException e2) {
                    stopSelf();
                }
            }
        }

    //    private class LocalBinder implements IBinder {
    //    }
    public class LocalBinder extends Binder {
              BluetoothDataService1 getService() {
                 return BluetoothDataService1.this;
        }
    }

这是我的活动

public class SendActivity extends Activity implements View.OnClickListener {
    Button on;
    BluetoothDataService1 bluetoothDataService1;
    public boolean isBound = false;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send);
        on= (Button) findViewById(R.id.btnon);
        on.setOnClickListener(this);
    }

    @Override
    public  void onStart() {
        super.onStart();
          Intent intent = new Intent(this, BluetoothDataService1.class);
          bindService(intent, connection, Context.BIND_AUTO_CREATE);
    }

    @Override
    public void onClick(View v) {
        if (isBound) {

//                  Intent intent=new Intent (SendActivity.this,BluetoothDataService1.class);
//                  intent.putExtra("ON","#ffffff00" );
//                  startService(intent);
        }
    }
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {
            BluetoothDataService1.LocalBinder binder = (BluetoothDataService1.LocalBinder) service;
            bluetoothDataService1 = binder.getService();
            isBound = true;

        }
        @Override
             public void onServiceDisconnected(ComponentName arg0) {
             isBound = false;
        }
    };
    @Override
      public void onStop() {
        super.onStop();
          if (isBound) {
              unbindService(connection);
              isBound = false;
        }
    }

1 个答案:

答案 0 :(得分:0)

  1. 无论我从你的问题中理解了什么,我都在给出解决方案 给你  2.您必须创建变量static,以便您可以直接从其他活动访问该变量  3.比如你有3个活动A B C.  4.现在你想要从A和B获取变量到C
    1. 然后你可以在下面的A和B中检查变量static。
    2. 在公共静态String string="#FFFFFF000"中与B
    3. 相同
    4. 你可以进入C
    5. String string = A.string;
  2. 或者您可以在A活动和B活动中创建静态方法,并从C活动中调用该方法。 公共区域
  3. 喜欢`public static void send(){             static veriableName =“FFFFFF000”              //在这里发送代码

               }`
    
  4. 并通过从C调用此方法,您可以这样做  A.send();