1

Bluetooth通信を確立するためにBluetoothChatサンプルを使用しています。私は今SecondView.javaを作成しました、そして私はBluetoothに再接続する必要なしにそこからデータを送受信したいと思います。BluetoothChat.javaの例で使用されている送信メソッドと受信メソッドにSecondView.javaにアクセスする方法はありますか?有効なメソッドはBound Serviceを使用することですが、これを実装する方法がわかりません。

4

1 に答える 1

3

Bluetooth チャットの例に従っている場合、Bluetooth 通信にスレッドを使用することになります。たとえば、Bluetooth 通信用の読み取りおよび書き込みメソッドを持つ connectedthread です。

アプリのどこからでも読み書きできるのは、実際には非常に簡単です。アプリケーションのそのスレッドへのグローバル参照が必要なだけです。

Android アプリでは、アプリケーションはアプリ全体でグローバルなコンテキストを持ちます。これは、任意のアクティビティから getApplication() メソッドで取得できます。「アプリケーション」コンテキストに独自の変数を設定するには、アプリケーション クラスを拡張し、マニフェストをそのクラスに向ける必要があります。

例を示します。アプリケーション クラスを拡張し、ゲッター メソッドとセッター メソッドを使用して、接続されたスレッドの変数を作成しました。

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 属性を、上で作成したアプリケーション クラスのクラス名に設定する必要があります。例えば

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

それが役立つことを願っています。

于 2012-10-16T09:38:03.427 に答える