应用程序从多任务处理中删除后,Android蓝牙连接丢失

时间:2014-05-15 11:29:52

标签: android bluetooth android-bluetooth

我正在开发设备和ECU(电子电路单元)之间的蓝牙应用。我使用服务类来建立后台服务以维护设备和ecu上的连接,即使从多任务中删除应用程序后我也需要连接。现在连接在删除后丢失了。可以做些什么?请帮我。

这是代码段

公共类IgnitionServicestart扩展了Service {

private static final String TAG = IgnitionServicestart.class.getSimpleName();
public static boolean isDeviceConnected = false;
// Name of the connected device
private static String mConnectedDeviceName = null;
// Array adapter for the conversation thread
private ArrayAdapter<String> mConversationArrayAdapter;
// String buffer for outgoing messages
private StringBuffer mOutStringBuffer = null;
// Local Bluetooth adapter
private BluetoothAdapter mBluetoothAdapter = null;
// Member object for the chat services
public static BluetoothChatService mChatService = null;
public static Context context;
@Override
public void onCreate() {
    // Start up the thread running the service.  Note that we create a
    // separate thread because the service normally runs in the process's
    // main thread, which we don't want to block.  We also make it
    // background priority so CPU-intensive work will not disrupt our UI.

    // Get the HandlerThread's Looper and use it for our Handler
    context=IgnitionServicestart.this;
    handlerKeepAlive = new Handler();
    handlerDisconnectBluetooth = new Handler();
    mNotManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            setupChat();

    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(Integer.toString(BluetoothChatService.STATE_CONNECTED));
    intentFilter.addAction(Integer.toString(BluetoothChatService.STATE_NONE));
    registerReceiver(bluetoothConnectionStatus, intentFilter);
    if (!Config.BLUETOOTH) {
        KeepAliveResponse objKeepAliveResponse = new KeepAliveResponse(
                mHandler);
        objKeepAliveResponse.start();
    }
}



@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    //Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();

    // For each start request, send a message to start a job and deliver the
    // start ID so we know which request we're stopping when we finish the job
    // If we get killed, after returning from here, restart
    //context=IgnitionServicestart.this;


    return START_NOT_STICKY;
}

@SuppressLint("NewApi")
private void setupChat() {
    if (Config.LOGGING) {
        Log.d(TAG, "setupChat()");
    }
    // Initialize the BluetoothChatService to perform bluetooth connections

    if (Config.BLUETOOTH) {
        if(mChatService == null)
            mChatService = new BluetoothChatService(this, mHandler);
    }
    //}
    // Initialize the buffer for outgoing messages
    mOutStringBuffer = new StringBuffer("");
}

// The Handler that gets information back from the BluetoothChatService
private final static Handler mHandler = new Handler() {

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
        case MESSAGE_STATE_CHANGE:
            if (Config.LOGGING) {
                Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
            }
            switch (msg.arg1) {
            case BluetoothChatService.STATE_CONNECTED:
                // mTitle.setText(R.string.title_connected_to);
                // mTitle.append(mConnectedDeviceName);
                // mConversationArrayAdapter.clear();
                // Toast.makeText(getApplicationContext(),
                // R.string.title_connected_to+mConnectedDeviceName,
                // Toast.LENGTH_SHORT).show();
                isDeviceConnected = true;
                nKeepAliveReqCount = 0;
                nKeepAliveResCount = 0;
                // Start sending Keep Alive messages.
                //handlerKeepAlive.removeCallbacks(SendKeepAliveMessage);
                //handlerKeepAlive.postDelayed(SendKeepAliveMessage, Config.KEEP_ALIVE_INTERVAL);
                context.sendBroadcast(new Intent(Integer.toString(BluetoothChatService.STATE_CONNECTED)));
                break;

            case BluetoothChatService.STATE_CONNECTING:
                // mTitle.setText(R.string.title_connecting);
                Toast.makeText(context,
                        R.string.title_connecting, Toast.LENGTH_SHORT)
                        .show();
                break;
            case BluetoothChatService.STATE_LISTEN:
            case BluetoothChatService.STATE_NONE:
                // mTitle.setText(R.string.title_not_connected);
                // Toast.makeText(getApplicationContext(),
                // R.string.title_not_connected, Toast.LENGTH_SHORT).show();
                isDeviceConnected = false;
                context.sendBroadcast(new Intent(Integer.toString(BluetoothChatService.STATE_NONE)));
                break;
            }
            break;
        case MESSAGE_WRITE:
            byte[] writeBuf = (byte[]) msg.obj;
            // construct a string from the buffer
            /*
             * String hexstring1=getHex(writeBuf);
             * writeBuf=hexstring1.getBytes();
             */
            String writeMessage = new String(writeBuf);
            if (Config.LOGGING) {
                Log.d("String Message", writeMessage);
            }
            // mConversationArrayAdapter.add("Me:  " + writeMessage);
            break;
        case MESSAGE_READ:
            // mTitle.setVisibility(View.VISIBLE);
            byte[] readBuf = (byte[]) msg.obj;
            // construct a string from the valid bytes in the buffer
            String readMessage = new String(readBuf, 0, msg.arg1);
            if (Config.LOGGING) {
                Log.d("String Message", readMessage);
            }
            //                  mConversationArrayAdapter.add(mConnectedDeviceName + ":  " + readMessage);
            processReceivedMessage(readBuf);
            break;
        case MESSAGE_DEVICE_NAME:
            // save the connected device's name

            if (Config.BLUETOOTH) {
                mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
                Toast.makeText(context,
                        "Connected to " + mConnectedDeviceName,
                        Toast.LENGTH_SHORT).show();
            }
            break;
        case MESSAGE_TOAST:
            /********* COMMENTED CODE TO BE USED WHILE DEBUGGING ON DEVICE - BEGIN ***********/
            //                  if (Config.INTERNAL) {
            //                      Toast.makeText(MenuActivity.this,
            //                              msg.getData().getString(TOAST), Toast.LENGTH_LONG)
            //                              .show();
            //                  }
            /********* COMMENTED CODE TO BE USED WHILE DEBUGGING ON DEVICE - END ***********/

            break;
        case MESSAGE_ALERT:
            /********* COMMENTED CODE TO BE USED WHILE DEBUGGING ON DEVICE - BEGIN ***********/
            //                  if (Config.INTERNAL) {
            //                      for (int i = 0; i < 5; i++) {
            //                          Toast.makeText(MenuActivity.this,
            //                                  msg.getData().getString(TOAST),
            //                                  Toast.LENGTH_LONG).show();
            //                      }
            //                  }
            /********* COMMENTED CODE TO BE USED WHILE DEBUGGING ON DEVICE - END ***********/

            break;
        }
    }
};




/**
 * Sends a message.
 * 
 * @param message
 *            A string of text to send.
 */
public static void sendMessage(char[] message) {
    // Check that we're actually connected before trying anything

    if (Config.BLUETOOTH) {
        if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
            Toast.makeText(context, R.string.not_connected, Toast.LENGTH_SHORT).show();
            return;
        }
    }

    Toast.makeText(context, "inside send message"+message.toString(), Toast.LENGTH_SHORT).show();
    // Check that there's actually something to send
    if (message.length > 0) {
        // Get the message bytes and tell the BluetoothChatService to write
        byte[] send = new byte[message.length];
        for (int i = 0; i < message.length; i++) {
            send[i] = (byte) message[i];
        }

        if (Config.BLUETOOTH) {
            mChatService.write(send);
        }
        // Reset out string buffer to zero and clear the edit text field
        //mOutStringBuffer.setLength(0);
        // mOutEditText.setText(mOutStringBuffer);
    }
}
private BroadcastReceiver bluetoothConnectionStatus = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "receiver", Toast.LENGTH_SHORT).show();
        if (intent.getAction().equalsIgnoreCase(Integer.toString(BluetoothChatService.STATE_CONNECTED))) {
            Toast.makeText(context, "connected receiver", Toast.LENGTH_SHORT).show();
        }
        else if (intent.getAction().equalsIgnoreCase(Integer.toString(BluetoothChatService.STATE_NONE))) {
            Toast.makeText(context, "disconnected receiver", Toast.LENGTH_SHORT).show();
        }
    }
};

@Override
public IBinder onBind(Intent intent) {
    return null;
}

}

0 个答案:

没有答案