android BlutoothChatService use in multiple classes

前端 未结 1 896
醉话见心
醉话见心 2021-01-15 20:47

im using the BluetoothChat sample in order to establish a bluetooth communication. Ive created SecondView.java now and i want to send and receive data from there without hav

相关标签:
1条回答
  • 2021-01-15 21:37

    If you are following the bluetooth chat example, then you will be using threads for bluetooth communication, e.g. a connectedthread that has the read and write methods for bluetooth communication.

    Its actually really simple to be able to read and write from anywhere in your app. You just need to have a global reference to that thread for your application.

    In a android app, the application has a context that is a global across your entire app. You can get this with the getApplication() method from any activity. To set your own variables on the 'Application' context, you need to extend the application class, and point your manifest towards it.

    Heres an example. I've extended the application class, and made a variable for the connected thread, with getter and setter methods.

    class MyAppApplication extends Application {
            private ConnectedThread mBluetoothConnectedThread;
    
            @Override
            public void onCreate() {
                super.onCreate();
            }
    
            public ConnectedThread getBluetoothConnectedThread() {
                return mBluetoothConnectedThread;
            }
    
            public void setBluetoothConnectedThread(ConnectedThread mBluetoothConnectedThread) {
                this.mBluetoothConnectedThread = mBluetoothConnectedThread;
            }
    
        }
    

    And to point your manifest towards that class, you need to set the android:name attribute of the application element to the class name of the application class we created above. E.g.

     <application
            android:name="com.myapp.package.MyApplication"
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppTheme">
    

    Once thats done you can access the ConnectedThread at any in a activity by calling

    MyAppApplication.getBluetoothConnectedThread().write()
    MyAppApplication.getBluetoothConnectedThread().read()
    

    Note that you need to set the thread to the model first once its created:

    MyAppApplication.setBluetoothConnectedThread(MyNewConnectedThread);
    

    Hope that helps.

    0 讨论(0)
提交回复
热议问题