android BlutoothChatService在多个类中使用

时间:2012-10-10 12:04:21

标签: android bluetooth

即时通讯使用BluetoothChat示例以建立蓝牙通信。我现在创建了SecondView.java,我想从那里发送和接收数据,而不必重新连接到蓝牙。有没有办法访问BluetoothChat.java示例中使用的发送和接收方法到我的SecondView.java?我发现一个工作方法是使用绑定服务,但我不知道如何实现它..

1 个答案:

答案 0 :(得分:3)

如果您正在关注蓝牙聊天示例,那么您将使用线程进行蓝牙通信,例如具有蓝牙通信读写方法的connectedthread。

从应用程序的任何位置读取和写入实际上非常简单。您只需要为您的应用程序提供该线程的全局引用。

在Android应用程序中,应用程序具有整个应用程序中的全局上下文。您可以使用任何活动中的getApplication()方法获取此信息。要在“应用程序”上下文中设置自己的变量,您需要扩展应用程序类,并将清单指向它。

这是一个例子。我已经扩展了应用程序类,并使用getter和setter方法为连接的线程创建了一个变量。

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;
        }

    }

要将清单指向该类,您需要将application元素的android:name属性设置为我们在上面创建的应用程序类的类名。 E.g。

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

完成后,您可以通过调用

访问活动中任何活动的ConnectedThread
MyAppApplication.getBluetoothConnectedThread().write()
MyAppApplication.getBluetoothConnectedThread().read()

请注意,您需要在创建模型后首先将线程设置为模型:

MyAppApplication.setBluetoothConnectedThread(MyNewConnectedThread);

希望有所帮助。