如何使用服务将蓝牙连接移至主要活动

我不知道如何解决我的问题。 通常,Bluetoothactivity中的应用程序可以启用,发现,发现设备并与设备配对。 (它可以与耳机配合使用,但是与HC-06配对使用就可以了) 我需要知道如何在Homeactivity中调用我的服务,因为我不能忘记生命周期活动。 Bluetoothactivity屏幕:

https://imgur.com/yfGU5qZ

Homeactivity屏幕:

https://imgur.com/zTlqAGD

我创建了MyBluetoothService,它是使用yt的一些教程编写的。 我有线程-连接,接受,连接。 单击列表中的设备后,我必须绑定并移至Homeactivity(为此,我应该使用Intent),其中6个文本视图必须从与HC-06相连的Arduino获取信息。

Bluetoothactivity代码:

public class Bluetoothactivity extends AppCompatactivity implements AdapterView.OnItemClicklistener {

private static final String TAG = "Parking System";
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

public ArrayList<BluetoothDevice> btDevices = new ArrayList<>();
public ArrayList<BluetoothDevice> pairedBtDevices = new ArrayList<>();
public Set<BluetoothDevice> pairedDevices;
public DevicesAdapter devicesAdapter;

BluetoothAdapter bluetoothAdapter;

MyBluetoothService myBluetoothService;

private ListView listView,listView2;

@Override
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_bluetooth);
    listView = (ListView)findViewById(R.id.list_devices);
    listView2 = (ListView)findViewById(R.id.list_no_paired_devices);

    IntentFilter filter = new IntentFilter(BluetoothDevice.actION_bond_STATE_CHANGED);
    registerReceiver(broadcastReceiver4,filter);

    bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();



    listView.setOnItemClicklistener(Bluetoothactivity.this);
    listView2.setOnItemClicklistener(Bluetoothactivity.this);

    if (bluetoothAdapter==null){
        Toast.makeText(getapplicationContext(),"Bluetooth is not avaible for this device !",Toast.LENGTH_SHORT).show();
        finish();
    }
    if (!bluetoothAdapter.isEnabled()){
        Log.d(TAG,"Bluetooth enaibling");
        makeDiscoverable();
        Intent enableBtIntent = new Intent(BluetoothAdapter.actION_REQUEST_ENABLE);
        startactivity(enableBtIntent);
        IntentFilter intent = new IntentFilter(BluetoothAdapter.actION_STATE_CHANGED);
        registerReceiver(broadcastReceiver,intent);
    }

    showPairedDevice();

    if (bluetoothAdapter.isDiscovering()) {
        bluetoothAdapter.cancelDiscovery();
    }

}

public boolean onCreateOptionsMenu(Menu menu){
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.bluetooth_activity_menu,menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item){
    switch (item.getItemId()){
        case R.id.refresh:
            Log.d(TAG,"MenuItem Refresh: Clicked");
            Log.d(TAG,"MenuItem Refresh: Removing paired devices from list");
            pairedBtDevices.removeAll(pairedBtDevices);
            Log.d(TAG,"MenuItem Refresh: Removing all unpaired devices from list");
            btDevices.removeAll(btDevices);
            Log.d(TAG,"MenuItem Refresh: invoking showPairedDevice() method");
            showPairedDevice();
            Log.d(TAG,"MenuItem Refresh: Looking for unpaired devices");
            if(bluetoothAdapter.isDiscovering()){
                bluetoothAdapter.cancelDiscovery();
                Log.d(TAG,"MenuItem Refresh: Canceled Discovery");
                bluetoothAdapter.startDiscovery();
                Log.d(TAG,"MenuItem Refresh: Started discovery");
                checkBtPermissions();
                IntentFilter discoverDevicesIntent = new IntentFilter((BluetoothDevice.actION_FOUND));
                registerReceiver(broadcastReceiver3,discoverDevicesIntent);
            }
            if(!bluetoothAdapter.isDiscovering()){
                checkBtPermissions();
                bluetoothAdapter.startDiscovery();
                IntentFilter discoverDevicesIntent = new IntentFilter((BluetoothDevice.actION_FOUND));
                registerReceiver(broadcastReceiver3,discoverDevicesIntent);
            }
            return true;
    }
    return super.onOptionsItemSelected(item);
}

private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context,Intent intent) {
        String action = intent.getaction();
        if(action.equals(bluetoothAdapter.actION_STATE_CHANGED)){
            final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,bluetoothAdapter.ERROR);
            switch (state){
                case BluetoothAdapter.STATE_OFF:
                    Log.d(TAG,"BroadcastReceive: OFF");
                    break;
                case BluetoothAdapter.STATE_TURNING_OFF:
                    Log.d(TAG,"BroadcastReceive: Turning OFF");
                    break;

                case BluetoothAdapter.STATE_ON:
                    Log.d(TAG,"BroadcastReceive: ON");
                    break;
                case BluetoothAdapter.STATE_TURNING_ON:
                    Log.d(TAG,"BroadcastReceive: Turning ON");
                    break;
            }
        }
    }
};

private final BroadcastReceiver broadcastReceiver2 = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context,Intent intent) {
        final String action = intent.getaction();
        if(action.equals(BluetoothAdapter.actION_SCAN_MODE_CHANGED)){
            int mode = intent.getIntExtra(BluetoothAdapter.EXTRA_SCAN_MODE,BluetoothAdapter.ERROR);
            switch(mode){
                case BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVErablE:
                    Log.d(TAG,"BroadcastReceiver2: Discoverability enabled");
                    break;
                case BluetoothAdapter.SCAN_MODE_CONNECTABLE:
                    Log.d(TAG,"BroadcastReceiver2: Discoverability enable. Ready to receive connections");
                    break;
                case BluetoothAdapter.SCAN_MODE_NONE:
                    Log.d(TAG,"BroadcastReceiver2: Discovering disabled. Is not ready to receive connections");
                    break;
                case BluetoothAdapter.STATE_CONNECTING:
                    Log.d(TAG,"BroadcastReceiver2: Connecting...");
                    break;
                case BluetoothAdapter.STATE_CONNECTED:
                    Log.d(TAG,"BroadcastReceiver2: Connected !");
                    break;
            }
        }
    }
};

private BroadcastReceiver broadcastReceiver3 = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context,Intent intent) {
          final String action = intent.getaction();
          Log.d(TAG,"OnReceive: action found");
          if(action.equals(BluetoothDevice.actION_FOUND)){
              BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
              Log.d(TAG,"Adding " + device + "to btDevices");
              btDevices.add(device);
              Log.d(TAG,"Paired Devices: " + pairedBtDevices + "Device: " + device);
              if(pairedBtDevices.size()>0){
                  for(BluetoothDevice pairedDevice : pairedDevices){
                      Log.d(TAG,"Paired Devices: Foreach " + pairedDevice);
                      Log.d(TAG,"Paired Devices: Check value " + pairedDevice.equals(device));
                      if(pairedDevice.equals(device)){
                          btDevices.remove(device);
                          Log.d(TAG,"Removed " + device + "from btDevices");
                      }
                  }

              }
              Log.d(TAG,"OnReceive: " + device.getName() + " | " + device.getaddress());
              devicesAdapter = new DevicesAdapter(context,R.layout.device_list_adapter_view,btDevices);
              listView2.setadapter(devicesAdapter);
          }
    }
};

private final BroadcastReceiver broadcastReceiver4 = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context,Intent intent) {
        final String action = intent.getaction();
        if(action.equals(BluetoothDevice.actION_bond_STATE_CHANGED)){
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            if(device.getbondState()==BluetoothDevice.bond_bondED){
                Log.d(TAG,"BroadcastReceiver4: bond_bondED");
                Toast.makeText(getapplicationContext(),"Connected with: "+device.getName(),Toast.LENGTH_SHORT).show();
                Log.d(TAG,"BroadcastReceiver4: Invoking btDeviceConnection() method");
                //btDeviceConnection(device,MY_UUID);

            }
            if(device.getbondState()==BluetoothDevice.bond_bondING){
                Log.d(TAG,"BroadcastReceiver4: bond_bondING");
            }
            if(device.getbondState()==BluetoothDevice.bond_NONE){
                Log.d(TAG,"BroadcastReceiver4: bond_NONE");
            }
        }
    }
};

public void makeDiscoverable(){
    Log.d(TAG,"MakeDiscoverable: Making a device discoverable for 300 sec");
    Intent discoverableIntent = new Intent(BluetoothAdapter.actION_REQUEST_DISCOVErablE);
    discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVErablE_DURATION,300);
    startactivity(discoverableIntent);
    IntentFilter intentFilter = new IntentFilter(bluetoothAdapter.actION_SCAN_MODE_CHANGED);
    registerReceiver(broadcastReceiver2,intentFilter);
}

private void showPairedDevice() {
    pairedDevices = bluetoothAdapter.getbondedDevices();
    Log.d(TAG,"ShowPairedDevice: Removing all paired devices from list");
    pairedBtDevices.removeAll(pairedDevices);
    Log.d(TAG,"ShowPairedDevice: Showing all paired devices");
    if(pairedDevices.size()>0){
        for(BluetoothDevice device : pairedDevices){
            pairedBtDevices.add(device);
        }
        devicesAdapter = new DevicesAdapter(getapplicationContext(),pairedBtDevices);
    }
    listView.setadapter(devicesAdapter);

}

public void checkBtPermissions(){
    if(Build.VERSION.SDK_INT>Build.VERSION_CODES.JELLY_BEAN_MR2){
        int permCheck = this.checkSelfPermission("Manifest.permission.accESS_FINE_LOCATION");
        permCheck+=this.checkSelfPermission("Manifest.permission.accESS_COARSE_LOCATION");
        if(permCheck!=0){
            this.requestPermissions(new String[]{Manifest.permission.accESS_FINE_LOCATION,Manifest.permission.accESS_COARSE_LOCATION},1001);
        }
        else{
            Log.d(TAG,"CheckBtPermission: Need to check permissions. Your SDK < JELLY_BEAN_MR2");
        }
    }
}
/*
private void btDeviceConnection(BluetoothDevice device,UUID uuid){
    Log.d(TAG,"BtDeviceConnection: Started");
    myBluetoothService.startClient(device,uuid);
}
*/
@Override
public void onItemClick(AdapterView<?> parent,View view,int position,long id) {
    bluetoothAdapter.cancelDiscovery();
    Log.d(TAG,"OnItemClick: Clicked a device");
    String deviceName = btDevices.get(position).getName();
    String deviceAddress = btDevices.get(position).getaddress();
    Log.d(TAG,"OnItemClick: Device name: "+deviceName);
    Log.d(TAG,"OnItemClick: Device address: "+deviceAddress);
    if(Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2){
        Log.d(TAG,"Trying to pair with: " + deviceName);
        Toast.makeText(getapplicationContext(),"Trying to pair with: " + deviceName,Toast.LENGTH_SHORT).show();
        btDevices.get(position).createbond();
    }
}


@Override
protected void onDestroy() {
    Log.d(TAG,"OnDestroy: Destroying");
    super.onDestroy();
    if(bluetoothAdapter !=null){
        bluetoothAdapter.cancelDiscovery();
    }
    unregisterReceiver(broadcastReceiver);
    unregisterReceiver(broadcastReceiver2);
    unregisterReceiver(broadcastReceiver3);
    unregisterReceiver(broadcastReceiver4);
}

MyBluetoothService代码:

public class MyBluetoothService{
private static final String TAG = "Parking System";
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

private final BluetoothAdapter bluetoothAdapter;
Context context;

private Handler handler;

private acceptThread insecureacceptThread;
private ConnectThread connectThread;

private BluetoothDevice bluetoothDevice;
private UUID deviceUUID;
private ProgressDialog progressDialog;

private ConnectedThread connectedThread;

public MyBluetoothService(Context context) {
    this.context = context;
    bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    start();
}


private class acceptThread extends Thread{
    private final BluetoothServerSocket bluetoothServerSocket;

    public acceptThread(){
        BluetoothServerSocket tmp = null;
        try {
            tmp = bluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord("Patking System",MY_UUID);
        } catch (IOException e) {
            e.printStackTrace();
        }

        bluetoothServerSocket = tmp;
    }

    @Override
    public void run() {
        Log.d(TAG,"Run: acceptThread Running");
        BluetoothSocket bluetoothSocket = null;
        try {
            bluetoothSocket= bluetoothServerSocket.accept();
            Log.d(TAG,"Run: accepted connection");
        } catch (IOException e) {
            Log.e(TAG,"acceptThread: IOException: " + e.getMessage());
        }

        /*if(bluetoothSocket!=null){
            connected(bluetoothSocket,blue)
        }*/
    }

    public void cancel(){
        Log.d(TAG,"Cancel: Canceling acceptThread");
        try{
            bluetoothServerSocket.close();
        }catch (IOException e){
            Log.e(TAG,"Cancel: acceptThread ServerSocket's error: "+e.getMessage());
        }
    }

}

private class ConnectThread extends Thread {

    private BluetoothSocket bluetoothSocket;

    public ConnectThread(BluetoothDevice device,UUID uuid) {
        Log.d(TAG,"ConnectThread: Started");
        bluetoothDevice = device;
        deviceUUID = uuid;
    }

    @Override
    public void run() {
        BluetoothSocket tmp = null;
        Log.d(TAG,"Run: ConnectThread ");
        try{
            Log.d(TAG,"ConnectThread: Create RfcomSocket using UUID");
            tmp = bluetoothDevice.createRfcommSocketToServiceRecord(deviceUUID);
        }catch (IOException e){
            Log.e(TAG,"ConnectThread: Could not create RfcommSocket: "+e.getMessage());
        }
        bluetoothSocket=tmp;
        bluetoothAdapter.cancelDiscovery();

        try {
            bluetoothSocket.connect();
            Log.d(TAG,"Run: ConnectThread connected");
        } catch (IOException e) {
            try{
                bluetoothSocket.close();
                Log.d(TAG,"Run: Closed socket");
            }catch (IOException e2){
                Log.e(TAG,"Run: Can not to close connection in socket " + e2.getMessage());
            }
            Log.d(TAG,"Run: ConnectThread: Could not connect to UUID");
        }

        connected(bluetoothSocket,bluetoothDevice);
    }

    public void cancel(){
        try{
            Log.d(TAG,"Cancel: Closing client socket");
            bluetoothSocket.close();
        }catch (IOException e){
            Log.e(TAG,"Cancel of close() : bluetoothSocket in ConnectThread failed: "+e.getMessage());
        }
    }
}

public synchronized void start(){
    Log.d(TAG,"Start");
    if(connectThread != null){
        connectThread.cancel();
        connectThread=null;
    }
    if(insecureacceptThread==null){
        insecureacceptThread = new acceptThread();
        insecureacceptThread.start();
    }
}


private class ConnectedThread extends Thread{
    private final BluetoothSocket bluetoothSocket;
    private final InputStream inputStream;
    private final OutputStream outputStream;

    public ConnectedThread(BluetoothSocket socket){
        Log.d(TAG,"ConnectedThread: Starting");
        bluetoothSocket=socket;
        InputStream tmpInput = null;
        OutputStream tmpOutput = null;

        progressDialog.dismiss();
        try{
            tmpInput = bluetoothSocket.getInputStream();
            tmpOutput = bluetoothSocket.getOutputStream();
        }catch (IOException e){
            e.printStackTrace();
        }
        inputStream=tmpInput;
        outputStream=tmpOutput;
    }

    @Override
    public void run() {
        byte[] buffer = new byte[1024];
        int bytes;
        while(true){
            try {
                bytes = inputStream.read(buffer);
                String comingMsg = new String(buffer,bytes);
                Log.d(TAG,"InputStream: " + comingMsg);
            }catch (IOException e){
                Log.e(TAG,"Write: Error reading input." + e.getMessage());
                break;
            }
        }
    }

    public void write(byte[] bytes){
        String text = new String(bytes,Charset.defaultCharset());
        Log.d(TAG,"Write: Writing to outputStream: " + text);
        try{
            outputStream.write(bytes);
        }catch (IOException e){
            Log.e(TAG,"Write: Error writing to output " + e.getMessage());
        }
    }

    public void cancel(){
        try{
            bluetoothSocket.close();
        }catch (IOException e){
            e.printStackTrace();
        }

    }
}


private void connected(BluetoothSocket bluetoothSocket,BluetoothDevice bluetoothDevice) {
    Log.d(TAG,"Connected: Starting");
    connectedThread = new ConnectedThread(bluetoothSocket);
    connectedThread.start();
}

public void write(byte[] out){
    ConnectedThread r;
    Log.d(TAG,"Write: Write called");
    connectedThread.write(out);
}

public void startClient(BluetoothDevice device,"StartClient: Started");
    progressDialog = ProgressDialog.show(context,"Connecting Bluetooth","Please wait...",true);
    connectThread = new ConnectThread(device,uuid);
    connectThread.start();
}

}

Homeactivity代码:

https://pastebin.com/raw/JAXGW40e

另外,您可以检查我的代码,因为我想学习一些新知识。

shuangpingye 回答:如何使用服务将蓝牙连接移至主要活动

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3138521.html

大家都在问