通过计划的连接创建蓝牙后台服务

时间:2018-09-29 16:16:32

标签: android service bluetooth android-bluetooth

在我的项目中,我需要在android中创建一个服务,在其中通过使用InsecureRfComm简化连接过程,从而连接到蓝牙模块,因为一个条件是它们没有配对。我要做的是避免验证配对。该服务的主要思想是,尽管蓝牙模块不可用,但请在用户执行其他任务时继续尝试在后台连接。

但是在启动服务时,如果蓝牙模块处于活动状态,它将连接并且应用程序停止;如果蓝牙模块未处于活动状态,则应用程序仅关闭。

这是服务:

package com.example.moises.moisesbt;

import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.IBinder;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.UUID;

public class MyService extends Service {

private ConnectedThread mConnectedThread; // bluetooth background worker thread to send and receive data
private BluetoothSocket mBTSocket = null; // bi-directional client-to-client data path
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");  //
private static final String DEVICE_ADDRESS = "00:06:66:08:16:CA"; //MAC Address module Bluetooth
/**
 * Tag for Log
 */
private static final String TAG = "MyService";

/**
 * Return Intent extra
 */
public static String EXTRA_DEVICE_ADDRESS = "device_address";
/**
 * Member fields
 */
private BluetoothAdapter mBtAdapter;

/**
 * Newly discovered devices
 */
private ArrayAdapter<String> mNewDevicesArrayAdapter;

// Constants that indicate the current connection state
public static final int STATE_CONNECTION_FAILED = 0;       // we're doing nothing
public static final int STATE_CONNECTING = 2; // now initiating an outgoing connection
public static final int STATE_CONNECTED = 3;  // now connected to a remote device

int REQUEST_ENABLE_BT =1;

@Override
public IBinder onBind(Intent intent) {

    return  null;
}

@Override
public void onCreate() {
    // Get the local Bluetooth adapter
    mBtAdapter=BluetoothAdapter.getDefaultAdapter();
    if (!mBtAdapter.isEnabled()) {
        Toast.makeText(this, "Service was Created", Toast.LENGTH_LONG).show();
    }

}

    @Override
public void onDestroy() {
        super.onDestroy();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d("MyService", "Onstart Command");
    Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
    if (!mBtAdapter.isEnabled()) {
        Toast.makeText(getBaseContext(), "Bluetooth not on", Toast.LENGTH_SHORT).show();
    }
    else{
        implementar();
        if (mBTSocket!=null){

        }
    }
    return START_STICKY;
}


private void implementar() {
    Intent intent = new Intent();
    intent.putExtra(EXTRA_DEVICE_ADDRESS, DEVICE_ADDRESS);
    if (!mBtAdapter.isEnabled()) {
        Toast.makeText(getBaseContext(), "Bluetooth not on", Toast.LENGTH_SHORT).show();
        return;
    }

    Message message = Message.obtain();
    message.what = STATE_CONNECTING;


    // Spawn a new thread to avoid blocking the GUI one
    new Thread() {
        public void run() {
            boolean fail = false;

            //    BluetoothDevice device = mBtAdapter.getRemoteDevice(address);          //-->aqui
            BluetoothDevice device = mBtAdapter.getRemoteDevice(DEVICE_ADDRESS);
            try {
                mBTSocket = createBluetoothSocket(device);
            } catch (IOException e) {
                fail = true;
                Toast.makeText(getApplicationContext(), "Socket creation failed", Toast.LENGTH_SHORT).show();
            }
            // Establish the Bluetooth socket connection.
            try {
                mBTSocket.connect();
            } catch (IOException e) {
                fail = true;
                Message message = Message.obtain();
                message.what = STATE_CONNECTION_FAILED;
                Toast.makeText(getApplicationContext(),"Conexion fallida",Toast.LENGTH_SHORT).show();
                return;

            }
            if (fail == false) {
                mConnectedThread = new ConnectedThread(mBTSocket);
                mConnectedThread.start();
                Message message = Message.obtain();
                message.what = STATE_CONNECTED;
                Toast.makeText(getApplicationContext(),"Estado Conectado",Toast.LENGTH_SHORT).show();
                return;

            }
        }
    }.start();
}


private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
    try {
        final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", UUID.class);
        return (BluetoothSocket) m.invoke(device, MY_UUID);
    } catch (Exception e) {
        Log.e(TAG, "Could not create Insecure RFComm Connection", e);
    }
    return device.createRfcommSocketToServiceRecord(MY_UUID);
}


private class ConnectedThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;

    public ConnectedThread(BluetoothSocket socket) {
        mmSocket = socket;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        // Get the input and output streams, using temp objects because
        // member streams are final
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) {
        }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }

}

}

并在MainActivity中:

public class MainActivity extends AppCompatActivity {
  Button conectar;
 private BluetoothAdapter mBtAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    conectar =findViewById(R.id.conectar);

// Get the local Bluetooth adapter
    mBtAdapter=BluetoothAdapter.getDefaultAdapter();
if (mBtAdapter == null) {
        // Device does not support Bluetooth
    }
    if (!mBtAdapter.isEnabled()) {
        Intent enableBtIntent = new 
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
    }
}
public void StarService(View view){
    Intent intent = new Intent(this, MyService.class);
    startService(intent);
}
}

我想知道在进行服务时是否需要一个必不可少的元素以及如何解决它,或者是否更建议使用意图服务

0 个答案:

没有答案