安卓蓝牙聊天应用数据库

时间:2018-07-28 19:54:26

标签: java android database bluetooth chat

我正在开发一个蓝牙聊天应用程序,并且已经通过它发送和接收文本,但是我想将此数据保存在我的应用程序中,所以我想知道人们将如何根据设备存储数据?我已经进行了一些聊天,所以如果我再次连接,我将不得不显示数据库中的先前数据。怎么样?

BluetoothChat.java

public class BluetoothChat extends AppCompatActivity {
private static final String TAG = "BluetoothChat";
private static final boolean D = true;

public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_NAME = 4;
public static final int MESSAGE_TOAST = 5;

public static final String DEVICE_NAME = "device_name";
public static final String TOAST = "toast";

private static final int REQUEST_CONNECT_DEVICE = 2;
private static final int REQUEST_ENABLE_BT = 3;


private ListView mConversationView;
private EditText mOutEditText;
private Button mSendButton,mFileButton;

private String mConnectedDeviceName = null;
private ArrayAdapter<String> mConversationArrayAdapter;
private StringBuffer mOutStringBuffer;
private BluetoothAdapter mBluetoothAdapter = null;
private BluetoothChatService mChatService = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (D)
        Log.e(TAG, "+++ ON CREATE +++");

    setContentView(R.layout.activity_bluetooth_chat);
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    if (mBluetoothAdapter == null) {
        Toast.makeText(this, "Bluetooth is not available",
                Toast.LENGTH_LONG).show();
        finish();
        return;
    }
}

@Override
public void onStart() {
    super.onStart();
    if (D)
        Log.e(TAG, "++ ON START ++");


    if (!mBluetoothAdapter.isEnabled()) {
        Intent enableIntent = new Intent(
                BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
    } else {
        if (mChatService == null)
            setupChat();
    }
}

@Override
public synchronized void onResume() {
    super.onResume();
    if (D)
        Log.e(TAG, "+ ON RESUME +");


    if (mChatService != null) {

        if (mChatService.getState() == BluetoothChatService.STATE_NONE) {

            mChatService.start();
        }
    }
}

private void setupChat() {
    Log.d(TAG, "setupChat()");

    mConversationArrayAdapter = new ArrayAdapter<String>(this,
            R.layout.message);
    mConversationView = (ListView) findViewById(R.id.in);
    mConversationView.setAdapter(mConversationArrayAdapter);

    mOutEditText = (EditText) findViewById(R.id.edit_text_out);
    mOutEditText.setOnEditorActionListener(mWriteListener);


    mSendButton= findViewById(R.id.button_send);
    mSendButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            TextView view = (TextView) findViewById(R.id.edit_text_out);
            String message = view.getText().toString();
            sendMessage(message);
        }
    });

    mChatService = new BluetoothChatService(this, mHandler);

    mOutStringBuffer = new StringBuffer("");
}

@Override
public synchronized void onPause() {
    super.onPause();
    if (D)
        Log.e(TAG, "- ON PAUSE -");
}

@Override
public void onStop() {
    super.onStop();
    if (D)
        Log.e(TAG, "-- ON STOP --");
}

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

    if (mChatService != null)
        mChatService.stop();
    if (D)
        Log.e(TAG, "--- ON DESTROY ---");
}

private void ensureDiscoverable() {
    if (D)
        Log.d(TAG, "ensure discoverable");
    if (mBluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
        Intent discoverableIntent = new Intent(
                BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        discoverableIntent.putExtra(
                BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
        startActivity(discoverableIntent);
    }
}

private void sendMessage(String message) {
    if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
        Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT)
                .show();
        return;
    }

    if (message.length() > 0) {
        byte[] send = message.getBytes();
        mChatService.write(send);

        mOutStringBuffer.setLength(0);
        mOutEditText.setText(mOutStringBuffer);
    }
}

private TextView.OnEditorActionListener mWriteListener = new TextView.OnEditorActionListener() {
    public boolean onEditorAction(TextView view, int actionId,
                                  KeyEvent event) {
        if (actionId == EditorInfo.IME_NULL
                && event.getAction() == KeyEvent.ACTION_UP) {
            String message = view.getText().toString();
            sendMessage(message);
        }
        if (D)
            Log.i(TAG, "END onEditorAction");
        return true;
    }
};

private final void setStatus(int resId) {
    getSupportActionBar().setSubtitle(resId);
}

private final void setStatus(CharSequence subTitle) {

    getSupportActionBar().setSubtitle(subTitle);
}



private final Handler mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case MESSAGE_STATE_CHANGE:
                if (D)
                    Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
                switch (msg.arg1) {
                    case BluetoothChatService.STATE_CONNECTED:

// setStatus(“ Connected”);                             setStatus(getString(R.string.title_connected_to)+“” + String.valueOf(mConnectedDeviceName));

                        mConversationArrayAdapter.clear();
                        break;
                    case BluetoothChatService.STATE_CONNECTING:
                        setStatus(String.valueOf(getString(R.string.title_connecting)));

                        break;
                    case BluetoothChatService.STATE_LISTEN:
                    case BluetoothChatService.STATE_NONE:
                        setStatus(R.string.title_not_connected);
                        break;
                }

                break;
            case MESSAGE_WRITE:
                byte[] writeBuf = (byte[]) msg.obj;
                String writeMessage = new String(writeBuf);
                mConversationArrayAdapter.add("Me:  " + writeMessage);
                break;
            case MESSAGE_READ:
                byte[] readBuf = (byte[]) msg.obj;
                String readMessage = new String(readBuf, 0, msg.arg1);
                mConversationArrayAdapter.add(mConnectedDeviceName + ":  "
                        + readMessage);
                break;
            case MESSAGE_DEVICE_NAME:
                mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
                Toast.makeText(getApplicationContext(),
                        "Connected to " + mConnectedDeviceName,
                        Toast.LENGTH_SHORT).show();
                break;
            case MESSAGE_TOAST:
                Toast.makeText(getApplicationContext(),
                        msg.getData().getString(TOAST), Toast.LENGTH_SHORT)
                        .show();
                break;
        }
    }
};

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (D)
        Log.d(TAG, "onActivityResult " + resultCode);
    switch (requestCode) {
        case REQUEST_CONNECT_DEVICE:
            if (resultCode == Activity.RESULT_OK) {
                connectDevice(data);
            }
            break;
        case REQUEST_ENABLE_BT:
            if (resultCode == Activity.RESULT_OK) {
                setupChat();
            } else {
                Log.d(TAG, "BT not enabled");
                Toast.makeText(this, R.string.bt_not_enabled_leaving,
                        Toast.LENGTH_SHORT).show();
                finish();
            }
    }
}

private void connectDevice(Intent data) {
    String address = data.getExtras().getString(
            DeviceListActivity.EXTRA_DEVICE_ADDRESS);
    BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
    mChatService.connect(device);
}

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    Intent serverIntent = null;
    switch (item.getItemId()) {
        case R.id.connect_scan:
            serverIntent = new Intent(this, DeviceListActivity.class);
            startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
            return true;
        case R.id.discoverable:
           ensureDiscoverable();
            return true;

        case R.id.shareapk:

            Intent intent= new Intent(BluetoothChat.this,Share_Apk.class);

            startActivity(intent);

    }
    return false;
}

}

BluetoothChatService.java

public class BluetoothChatService {
private static final String TAG = "BluetoothChatService";
private static final boolean D = true;

private static final String NAME = "BluetoothChat";

private static final UUID MY_UUID = UUID
        .fromString("0001101-0000-1000-8000-00805F9B34FB");

private final BluetoothAdapter mAdapter;
private final Handler mHandler;
private AcceptThread mAcceptThread;
private ConnectThread mConnectThread;
private ConnectedThread mConnectedThread;
private int mState;

public static final int STATE_NONE = 0;
public static final int STATE_LISTEN = 1;
public static final int STATE_CONNECTING = 2;
public static final int STATE_CONNECTED = 3;


public BluetoothChatService(Context context, Handler handler) {
    mAdapter = BluetoothAdapter.getDefaultAdapter();
    mState = STATE_NONE;
    mHandler = handler;
}


private synchronized void setState(int state) {
    if (D)
        Log.d(TAG, "setState() " + mState + " -> " + state);
    mState = state;

    mHandler.obtainMessage(BluetoothChat.MESSAGE_STATE_CHANGE, state, -1)
            .sendToTarget();
}


public synchronized int getState() {
    return mState;
}


public synchronized void start() {
    if (D)
        Log.d(TAG, "start");

    if (mConnectThread != null) {
        mConnectThread.cancel();
        mConnectThread = null;
    }

    if (mConnectedThread != null) {
        mConnectedThread.cancel();
        mConnectedThread = null;
    }

    setState(STATE_LISTEN);

    if (mAcceptThread == null) {
        mAcceptThread = new AcceptThread();
        mAcceptThread.start();
    }
}

public synchronized void connect(BluetoothDevice device) {
    if (D)
        Log.d(TAG, "connect to: " + device);

    if (mState == STATE_CONNECTING)
    {
        if (mConnectThread != null) {
            mConnectThread.cancel();
            mConnectThread = null;
        }
    }

    if (mConnectedThread != null)
    {
        mConnectedThread.cancel();
        mConnectedThread = null;
    }

    mConnectThread = new ConnectThread(device);
    mConnectThread.start();
    setState(STATE_CONNECTING);
}


public synchronized void connected(BluetoothSocket socket,
                                   BluetoothDevice device, final String socketType) {
    if (D)
        Log.d(TAG, "connected, Socket Type:" + socketType);

    if (mConnectThread != null)
    {
        mConnectThread.cancel();
        mConnectThread = null;
    }

    if (mConnectedThread != null) {
        mConnectedThread.cancel();
        mConnectedThread = null;
    }


    if (mAcceptThread != null) {
        mAcceptThread.cancel();
        mAcceptThread = null;
    }
    mConnectedThread = new ConnectedThread(socket, socketType);
    mConnectedThread.start();

    Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_DEVICE_NAME);
    Bundle bundle = new Bundle();
    bundle.putString(BluetoothChat.DEVICE_NAME, device.getName());
    msg.setData(bundle);
    mHandler.sendMessage(msg);

    setState(STATE_CONNECTED);
}

//毁灭     公共同步void stop(){         如果(D)             Log.d(TAG,“ stop”);

    if (mConnectThread != null) {
        mConnectThread.cancel();
        mConnectThread = null;
    }

    if (mConnectedThread != null) {
        mConnectedThread.cancel();
        mConnectedThread = null;
    }

    if (mAcceptThread != null) {
        mAcceptThread.cancel();
        mAcceptThread = null;
    }
    setState(STATE_NONE);
}

public void write(byte[] out) {
    ConnectedThread r;
    synchronized (this) {
        if (mState != STATE_CONNECTED)
            return;
        r = mConnectedThread;
    }
    r.write(out);
}

private void connectionFailed() {
    Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_TOAST);
    Bundle bundle = new Bundle();
    bundle.putString(BluetoothChat.TOAST, "Unable to connect device");
    msg.setData(bundle);
    mHandler.sendMessage(msg);

    BluetoothChatService.this.start();
}


private void connectionLost() {
    Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_TOAST);
    Bundle bundle = new Bundle();
    bundle.putString(BluetoothChat.TOAST, "Device connection was lost");
    msg.setData(bundle);
    mHandler.sendMessage(msg);

    BluetoothChatService.this.start();
}


private class AcceptThread extends Thread {
    private final BluetoothServerSocket mmServerSocket;
    private String mSocketType;

    public AcceptThread() {
        BluetoothServerSocket tmp = null;

        try {
            tmp = mAdapter
                    .listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
        } catch (IOException e) {
            Log.e(TAG, "Socket Type: " + mSocketType + "listen() failed", e);
        }
        mmServerSocket = tmp;
    }

    public void run() {
        if (D)
            Log.d(TAG, "Socket Type: " + mSocketType
                    + "BEGIN mAcceptThread" + this);
        setName("AcceptThread" + mSocketType);

        BluetoothSocket socket = null;

        while (mState != STATE_CONNECTED) {
            try {

                socket = mmServerSocket.accept();
            } catch (IOException e) {
                Log.e(TAG, "Socket Type: " + mSocketType
                        + "accept() failed", e);
                break;
            }

            if (socket != null) {
                synchronized (BluetoothChatService.this) {
                    switch (mState) {
                        case STATE_LISTEN:
                        case STATE_CONNECTING:
                            connected(socket, socket.getRemoteDevice(),
                                    mSocketType);
                            break;
                        case STATE_NONE:
                        case STATE_CONNECTED:
                            try {
                                socket.close();
                            } catch (IOException e) {
                                Log.e(TAG, "Could not close unwanted socket", e);
                            }
                            break;
                    }
                }
            }
        }
        if (D)
            Log.i(TAG, "END mAcceptThread, socket Type: " + mSocketType);

    }

    public void cancel() {
        if (D)
            Log.d(TAG, "Socket Type" + mSocketType + "cancel " + this);
        try {
            mmServerSocket.close();
        } catch (IOException e) {
            Log.e(TAG, "Socket Type" + mSocketType
                    + "close() of server failed", e);
        }
    }
}


private class ConnectThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final BluetoothDevice mmDevice;
    private String mSocketType;

    public ConnectThread(BluetoothDevice device) {
        mmDevice = device;
        BluetoothSocket tmp = null;


        try {
            tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) {
            Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e);
        }
        mmSocket = tmp;
    }

    public void run() {
        Log.i(TAG, "BEGIN mConnectThread SocketType:" + mSocketType);
        setName("ConnectThread" + mSocketType);

        mAdapter.cancelDiscovery();

        try {
            mmSocket.connect();
        } catch (IOException e) {
            try {
                mmSocket.close();
            } catch (IOException e2) {
                Log.e(TAG, "unable to close() " + mSocketType
                        + " socket during connection failure", e2);
            }
            connectionFailed();
            return;
        }

        synchronized (BluetoothChatService.this) {
            mConnectThread = null;
        }

        connected(mmSocket, mmDevice, mSocketType);
    }

    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) {
            Log.e(TAG, "close() of connect " + mSocketType
                    + " socket failed", e);
        }
    }
}

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

    public ConnectedThread(BluetoothSocket socket, String socketType) {
        Log.d(TAG, "create ConnectedThread: " + socketType);
        mmSocket = socket;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) {
            Log.e(TAG, "temp sockets not created", e);
        }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }

    public void run() {
        Log.i(TAG, "BEGIN mConnectedThread");
        byte[] buffer = new byte[1024];
        int bytes;

        while (true) {
            try {
                bytes = mmInStream.read(buffer);

                mHandler.obtainMessage(BluetoothChat.MESSAGE_READ, bytes,
                        -1, buffer).sendToTarget();
            } catch (IOException e) {
                Log.e(TAG, "disconnected", e);
                connectionLost();
                BluetoothChatService.this.start();
                break;
            }
        }
    }


    public void write(byte[] buffer) {
        try {
            mmOutStream.write(buffer);

            mHandler.obtainMessage(BluetoothChat.MESSAGE_WRITE, -1, -1,
                    buffer).sendToTarget();
        } catch (IOException e) {
            Log.e(TAG, "Exception during write", e);
        }
    }

    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) {
            Log.e(TAG, "close() of connect socket failed", e);
        }
    }
}

}

0 个答案:

没有答案