2012-10-10 19 views
1

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

+0

而不是尝试从SecondView.java使用BluetoothChat.java中的发送和接收,那么只需修改BluetoothChat.java以拥有您在SecondView中创建的功能,那么您的结果类就具备了所需的所有功能?你需要两个班吗? – hBrent

+0

不,为了我的申请目的,我必须能够发送和接收来自多个班级的数据 –

+0

以下是可能有效的几个选项。一种是在您的Application对象中创建BluetoothChatService对象(在本例中为“mChatService”),而不是在BluetoothChat类中,如下所示:http://stackoverflow.com/questions/4272906/sharing-an-object-between - 活动。通过这种方式,您可以在所有类中使用BluetoothChatService提供的所有方法和数据。另一个选择是使用Fragments(请参阅http://developer.android.com/guide/components/fragments.html)。这将允许共享不仅功能,而且UI元素。 – hBrent

回答

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

    } 

,并努力该类指向您的清单,你需要在Android设置:应用元素的name属性,我们在上面创建的应用程序类的类名。例如。

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

一旦多数民众赞成做致电

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

请注意,您需要将线程首先设置模型一旦其创建你可以在任何一个活动访问ConnectedThread:

MyAppApplication.setBluetoothConnectedThread(MyNewConnectedThread); 

希望有帮助。

+0

你好! thanx为你的答案,我有一些问题。我使用蓝牙聊天示例和BleutoothChatService类具有读取和写入方法,所以我更改了“专用ConnectedThread mBluetoothConnectedThread;”到“专用BluetoothChatService mBluetoothConnectedThread;”这是正确的方式吗? 也在我想访问“ConnectedThread”的活动中,该类将“扩展活动”或其他内容? 最后,我到底在哪里调用这个“MyAppApplication.setBluetoothConnectedThread(MyNewConnectedThread);”? thanx再次 –

+1

是的,如果你使用的是BluetoothChatService,你需要添加一个私人的BluetoothChatService mBluetoothChatService;到你的应用程序类(也要确保你创建了类,就像在BluetoothChat活动中完成的一样),你基本上将所有的蓝牙聊天内容从BluetoothChat活动中移出并移动到应用程序类 你可以调用MyAppApplication.setBluetoothConnectedThread (MyNewConnectedThread),因为它只是调用一个类,并且Application类在应用程序的生命周期中只会有一个实例。 – athor