我使用Unity来制作我的Android应用程序,所以我制作了Android插件。
在此插件中,我想将Android连接到其他蓝牙模块(我不知道模块名称是什么)
这是我的代码:
package com.jiho.myplugin;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.os.ParcelUuid;
import android.widget.Toast;
import com.unity3d.player.UnityPlayer;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.UUID;
public class Uplugin{
private static Uplugin m_instance;
public static Context context;
private static BluetoothAdapter myBluetoothAdapter;
private static UUID remoteUUID;
private static BluetoothSocket sock;
private static BluetoothDevice remoteDevice;
private static String remoteAddress;
public static Uplugin instance(){
if(m_instance == null){
m_instance = new Uplugin();
}
return m_instance;
}
private void SetContext(Context ct)
{
context = ct;
}
private static void bondBluetooth(Activity activity) {
myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
//pairingList
List<String> pairingList = new ArrayList<>();
Toast.makeText(context, "start!", Toast.LENGTH_SHORT).show();
if(!myBluetoothAdapter.isEnabled())
{
myBluetoothAdapter.enable();
}
while(true)
{
if(myBluetoothAdapter.isEnabled())
{
break;
}
}
Set<BluetoothDevice> pairedDevices = myBluetoothAdapter.getBondedDevices();
if(pairedDevices.size()>0) {
for (BluetoothDevice device : pairedDevices) {
if(device.getName().contains("TANDA"))
{
remoteDevice = device;
remoteAddress = device.getAddress();
ParcelUuid list[] = device.getUuids();
remoteUUID = UUID.fromString(list[0].toString());
break;
}
}
}
else
{
Toast.makeText(context, "no pair", Toast.LENGTH_SHORT).show();
}
}
private static void ConnectBluetooth(Activity activity)
{
BluetoothDevice mRemoteDevice;
BluetoothSocket mBluetoothSock = null;
mRemoteDevice = myBluetoothAdapter.getRemoteDevice(remoteAddress);
try{
mBluetoothSock = mRemoteDevice.createInsecureRfcommSocketToServiceRecord(remoteUUID);
} catch (IOException e){
Toast.makeText(context, "create error", Toast.LENGTH_SHORT).show();
}
sock = mBluetoothSock;
myBluetoothAdapter.cancelDiscovery();
try{
sock.connect();
} catch(IOException e){ Toast.makeText(context, "connect error", Toast.LENGTH_SHORT).show();}
}
In my Unity, i call "StratBluetooth()" first and than call "ConnectBluetooth()"
when i run this code first time, it was work.
but since next time it doesnt work at all.
createInsecureRfcommSocket()和connect()在代码中正常工作,但没有成功
到catch(IOException e)
以及isConnected() == true
它在我的Android中没有连接。