Я использую Unity для создания своего приложения для Android, поэтому я сделал плагин для Android.
В этом плагине я хочу подключить свой Android к другому модулю Bluetooth (я не знаю, как называется модуль)
Это мой код:
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.