这就是应该怎么做。
主机将使他/她的设备可被发现,然后选择将要加载的游戏板的类型。客户端将连接到主机设备,并且两个设备都将连接。主机先前选择的游戏板类型应同时在两个设备上加载。
这是我的代码,到目前为止,它仅会导致错误
BluetoothActivity.java
case MESSAGE_DEVICE_NAME:
// save the connected device's name
mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
Toast.makeText(TwoPlayerActivityBluetooth.this, "Connected to " + mConnectedDeviceName, Toast.LENGTH_SHORT).show();
/* If the device chose a game board, then send*/
if (GBChoice != 0)
{
sendGamepiece(GBChoice);
}
/* If the device didn't choose a game board, then receive */
else
{
byte[] readBuf2 = (byte[]) msg.obj;
String readMessage2 = new String(readBuf2, 0, msg.arg1);
/* Save the received data to a variable */
ChosenGB = readMessage2;
}
/* If the sent game board choice and received game board choice is both 1, then load the game board1*/
if (GBChoice == 1 && ChosenGB == 1)
{
loadGameBoard1();
}
break;
BluetoothService.java
public void run()
{
readGamepiece();
readLocation();
}
public void readGamepiece()
{
byte[] buffer2 = new byte[1024];
int bytes;
while(true)
{
try
{
bytes = mInStream.read(buffer2);
mHandler.obtainMessage(BluetoothActivity.MESSAGE_DEVICE_NAME, bytes, -1, buffer2).sendToTarget();
}
catch(IOException e)
{
Log.e(TAG, "disconnected", e);
connectionLost();
break;
}
}
}
public void writeGamepiece(byte[] buffer2)
{
try
{
mOutStream.write(buffer2);
mHandler.obtainMessage(BluetoothActivity.MESSAGE_DEVICE_NAME, -1 , -1 , buffer2).sendToTarget();
}
catch(IOException e)
{
Log.e(TAG, "Exception during write", e);
}
}
public void readLocation()
{
byte[] buffer = new byte[1024];
int bytes;
while(true)
{
try
{
bytes = mInStream.read(buffer);
mHandler.obtainMessage(BluetoothActivity.PLAYER_LOCATION_READ, bytes, -1, buffer).sendToTarget();
}
catch(IOException e)
{
Log.e(TAG, "disconnected", e);
connectionLost();
break;
}
}
}
public void writeLocation(byte[] buffer)
{
try
{
mOutStream.write(buffer);
mHandler.obtainMessage(BluetoothActivity.PLAYER_LOCATION_WRITE, -1 , -1 , buffer).sendToTarget();
}
catch(IOException e)
{
Log.e(TAG, "Exception during write", e);
}
}
错误:
FATAL EXCEPTION: mainProcess: com.example.try34.midproject, PID: 3829
java.lang.NullPointerException: Attempt to invoke virtual method 'byte[] java.lang.String.getBytes()' on a null object reference
at com.example.try34.midproject.view.BluetoothActivity.sendGamepiece(BluetoothActivity.java:1024)
at com.example.try34.midproject.view.BluetoothActivity.access$1800(BluetoothActivity.java:44)
at com.example.try34.midproject.view.BluetoothActivity$9.handleMessage(BluetoothActivity.java:741)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7409)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)