Android的连接与蓝牙设备上点击按钮,蓝牙设备 [英] Android connect to bluetooth device with click button on bluetooth device

查看:348
本文介绍了Android的连接与蓝牙设备上点击按钮,蓝牙设备的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个按钮装置蓝牙,我想连接到该设备上的按钮,点击后这个设备,它有什么例子来做到这一点?

I have device bluetooth with button, I want connect to this device after click button on this device, it's there any example to do this?

推荐答案

愿这帮助你。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.Set;
import java.util.UUID;

import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity implements Runnable {
protected static final String TAG = "TAG";
private static final int REQUEST_CONNECT_DEVICE = 1;
private static final int REQUEST_ENABLE_BT = 2;
Button mScan, mPrint;
 static OutputStream outStream;
BluetoothAdapter mBluetoothAdapter;
private UUID applicationUUID = UUID
        .fromString("00001101-0000-1000-8000-00805F9B34FB");
private ProgressDialog mBluetoothConnectProgressDialog;
static BluetoothSocket mBluetoothSocket;
BluetoothDevice mBluetoothDevice;

@Override
public void onCreate(Bundle mSavedInstanceState) {
    super.onCreate(mSavedInstanceState);
    setContentView(R.layout.activity_main);

    mScan = (Button) findViewById(R.id.Scan);
    mScan.setOnClickListener(new View.OnClickListener() {
        public void onClick(View mView) {
            mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            if (mBluetoothAdapter == null) {
                Toast.makeText(MainActivity.this, "Message1", 2000).show();
            } else {
                if (!mBluetoothAdapter.isEnabled()) {
                    Intent enableBtIntent = new Intent(
                            BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enableBtIntent,
                            REQUEST_ENABLE_BT);
                } else {
                    ListPairedDevices();
                    Intent connectIntent = new Intent(MainActivity.this,
                            DeviceListActivity.class);
                    startActivityForResult(connectIntent,
                            REQUEST_CONNECT_DEVICE);
                }
            }
        }
    });

    mPrint = (Button) findViewById(R.id.mPrint);
    mPrint.setOnClickListener(new View.OnClickListener() {
        public void onClick(View mView) {
            Thread t = new Thread() {
                public void run() {
                    try {
                        if (mBluetoothSocket != null) {

                            //code for send data on printer to print
                                                           sendDataToDevice("Hello");

                        }

                        // printer specific code you can comment ==== > End
                    } catch (Exception e) {
                        Log.e("Main", "Exe ", e);
                    }
                }
            };
            t.start();
        }
    });

    /* mDisc = (Button) findViewById(R.id.dis); */
    /*
     * mDisc.setOnClickListener(new View.OnClickListener() { public void
     * onClick(View mView) { if (mBluetoothAdapter != null)
     * mBluetoothAdapter.disable(); } });
     */

}// onCreate

public void onActivityResult(int mRequestCode, int mResultCode,
        Intent mDataIntent) {
    super.onActivityResult(mRequestCode, mResultCode, mDataIntent);

    switch (mRequestCode) {
    case REQUEST_CONNECT_DEVICE:
        if (mResultCode == Activity.RESULT_OK) {
            Bundle mExtra = mDataIntent.getExtras();
            String mDeviceAddress = mExtra.getString("DeviceAddress");
            Log.v(TAG, "Coming incoming address " + mDeviceAddress);
            mBluetoothDevice = mBluetoothAdapter
                    .getRemoteDevice(mDeviceAddress);
            mBluetoothConnectProgressDialog = ProgressDialog.show(this,
                    "Connecting...", mBluetoothDevice.getName() + " : "
                            + mBluetoothDevice.getAddress(), true, false);
            Thread mBlutoothConnectThread = new Thread(this);
            mBlutoothConnectThread.start();
            // pairToDevice(mBluetoothDevice); This method is replaced by
            // progress dialog with thread
        }
        break;

    case REQUEST_ENABLE_BT:
        if (mResultCode == Activity.RESULT_OK) {
            ListPairedDevices();
            Intent connectIntent = new Intent(MainActivity.this,
                    DeviceListActivity.class);
            startActivityForResult(connectIntent, REQUEST_CONNECT_DEVICE);
        } else {
            Toast.makeText(MainActivity.this, "Message", 2000).show();
        }
        break;
    }
}

private void ListPairedDevices() {
    Set<BluetoothDevice> mPairedDevices = mBluetoothAdapter
            .getBondedDevices();
    if (mPairedDevices.size() > 0) {
        for (BluetoothDevice mDevice : mPairedDevices) {
            Log.v(TAG, "PairedDevices: " + mDevice.getName() + "  "
                    + mDevice.getAddress());
        }
    }
}

public void run() {
    try {
        mBluetoothSocket = mBluetoothDevice
                .createRfcommSocketToServiceRecord(applicationUUID);
        mBluetoothAdapter.cancelDiscovery();
        mBluetoothSocket.connect();
        mHandler.sendEmptyMessage(0);
    } catch (IOException eConnectException) {
        Log.d(TAG, "CouldNotConnectToSocket", eConnectException);
        closeSocket(mBluetoothSocket);
        return;
    }
}
   private void sendDataToDevice(String message) {
    byte[] msgBuffer = message.getBytes();

    Log.d(TAG, "...Send data: " + message + "...");

    try {

        outStream.write(msgBuffer);
    } catch (IOException e) {
        String msg = "In onResume() and an exception occurred during write: "
                + e.getMessage();
        if (address.equals("00:00:00:00:00:00"))
            msg = msg
                    + ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address on line 35 in the java code";
        msg = msg
                + ".\n\nTry Connecting the device one more time from the options menu.\n\n";

        errorExit("Fatal Error", msg);
    }
}

private void closeSocket(BluetoothSocket nOpenSocket) {
    try {
        nOpenSocket.close();
        Log.d(TAG, "SocketClosed");
    } catch (IOException ex) {
        Log.d(TAG, "CouldNotCloseSocket");
    }
}

private Handler mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        mBluetoothConnectProgressDialog.dismiss();
        Toast.makeText(MainActivity.this, "DeviceConnected", 5000).show();
    }
};
}

和DeviceListActivty.java是这样的。

and DeviceListActivty.java is like this

import java.util.Set;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class DeviceListActivity extends Activity {
protected static final String TAG = "TAG";
private BluetoothAdapter mBluetoothAdapter;
private ArrayAdapter<String> mPairedDevicesArrayAdapter;

@Override
protected void onCreate(Bundle mSavedInstanceState) {
    super.onCreate(mSavedInstanceState);
    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    setContentView(R.layout.device_list);

    setResult(Activity.RESULT_CANCELED);
    mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this,
            R.layout.device_name);

    ListView mPairedListView = (ListView) findViewById(R.id.paired_devices);
    mPairedListView.setAdapter(mPairedDevicesArrayAdapter);
    mPairedListView.setOnItemClickListener(mDeviceClickListener);

    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    Set<BluetoothDevice> mPairedDevices = mBluetoothAdapter
            .getBondedDevices();

    if (mPairedDevices.size() > 0) {
        findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
        for (BluetoothDevice mDevice : mPairedDevices) {
            mPairedDevicesArrayAdapter.add(mDevice.getName() + "\n"
                    + mDevice.getAddress());
        }
    } else {
        String mNoDevices = "None Paired";// getResources().getText(R.string.none_paired).toString();
        mPairedDevicesArrayAdapter.add(mNoDevices);
    }
}

@Override
protected void onDestroy() {
    super.onDestroy();
    if (mBluetoothAdapter != null) {
        mBluetoothAdapter.cancelDiscovery();
    }
}

private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
    public void onItemClick(AdapterView<?> mAdapterView, View mView,
            int mPosition, long mLong) {
        mBluetoothAdapter.cancelDiscovery();
        String mDeviceInfo = ((TextView) mView).getText().toString();
        String mDeviceAddress = mDeviceInfo
                .substring(mDeviceInfo.length() - 17);
        Log.v(TAG, "Device_Address " + mDeviceAddress);

        Bundle mBundle = new Bundle();
        mBundle.putString("DeviceAddress", mDeviceAddress);
        Intent mBackIntent = new Intent();
        mBackIntent.putExtras(mBundle);
        setResult(Activity.RESULT_OK, mBackIntent);
        finish();
    }
};

  }

这篇关于Android的连接与蓝牙设备上点击按钮,蓝牙设备的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆