#2
sweet6hero2014-09-26 16:06
|
package thu.wolf.bluetooth;
import
import
import
import java.util.ArrayList;
import java.util.UUID;
import org.zeromq.ZMQ;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Bluetooth_MainActivity extends Activity {
private static String TAG = "Bluetooth_MainActivity";
static {
Log.d(TAG, "loadlibrary ------------start---------------. ");
System.loadLibrary("jzmq");
Log.d(TAG, "loadlibrary -----------------end----------. ");
}
private Button conn = null;
private Button server = null;
private Button client = null;
private Button send = null;
private TextView msgtext = null;
private EditText size = null;
private EditText counter = null;
private BluetoothRev bluetoothRev = null;
private BluetoothAdapter adapter = null;
private BluetoothDevice device = null;
private static final String S_NAME = "BluetoothChat";
private static final UUID S_UUID = UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB");
private InputStream m_InputStream = null;
private OutputStream m_OutputStream = null;
private InputStream Serverm_InputStream = null;
private OutputStream Serverm_OutputStream = null;
private String address = null;
boolean serverflag;
private static final String MESSAGE_READ = "Message_Read";
private ArrayList<String> blueToothNames = null;
private ArrayList<BluetoothDevice> blutToothDevices = null;
private HandlerThread handlerThread = null;
private MyHandler transHandler = null;
boolean isfound = false;
long startMili;// 当前时间对应的毫秒数
long endMili;// 当前时间对应的毫秒数
int i;
int c;
String data = "";
ZMQ.Context context = ZMQ.context(1);
ZMQ.Socket zmqsocket = context.socket(ZMQ.REQ);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth__main);
conn = (Button) findViewById(R.id.conn);
server = (Button) findViewById(R.id.server);
client = (Button) findViewById(R.id.client);
// client.setEnabled(false);
send = (Button) findViewById(R.id.send);
size = (EditText) findViewById(R.id.size);
counter = (EditText) findViewById(R.id.counter);
msgtext = (TextView) findViewById(R.id.msg);
conn.setOnClickListener(new connOnClickListener());
server.setOnClickListener(new serverOnClickListener());
client.setOnClickListener(new clientOnClickListener());
send.setOnClickListener(new sendOnClickListener());
// 设备信息
blueToothNames = new ArrayList<String>();
blutToothDevices = new ArrayList<BluetoothDevice>();
i = Integer.parseInt(size.getText().toString());
c = Integer.parseInt(counter.getText().toString());
// 1、 获取一个蓝牙适配器
adapter = BluetoothAdapter.getDefaultAdapter();
if (adapter != null)// 判断是否为空
{
Log.d(TAG, "this device have bt------------------");
// 2、判断当前蓝牙设备是否可用
if (!adapter.isEnabled()) {
// 3、创建一个Intent对象,用于启动一个activity,来提示用户开启蓝牙
Intent intent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
// 开启一个activity提醒有应用要开启蓝牙
startActivity(intent);
} else
Toast.makeText(this, "蓝牙已开启,可以启动服务", 50).show();
} else
Log.d(TAG, "this device don't have bt------------------");
// 生成一个HandlerThread对象,实现了使用Looper来处理消息队列的功能,这个类由Android应用程序框架提供
handlerThread = new HandlerThread("handler_thread");
// 在使用HandlerThread的getLooper()方法之前,必须先调用该类的start();
// 只能在主线程中开启此线程
handlerThread.start();
// 更新界面的handler
transHandler = new MyHandler(handlerThread.getLooper());
init();
}
private void init() {
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
Log.d(TAG,
"Connecting zmq C server ---------------------------. ");
zmqsocket.connect("tcp://ip:9999");
//zmqsocket.send("hhhhhhh".getBytes(),0);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}).start();
}
class MyHandler extends Handler {
public MyHandler() {
}
public MyHandler(Looper L) {
super(L);
}
// 子类必须重写此方法,接受数据
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
Log.d(TAG, "handleMessage---------------------start--------");
super.handleMessage(msg);
// 此处可以更新UI
Bundle b = msg.getData();
String time = b.getString("time");
Log.d(TAG, "handleMessage-----------------------------" + time);
// msgtext.setText("time: "+time);
Log.d(TAG, "handleMessage---------------------end--------");
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.bluetooth__main, menu);
return true;
}
@Override
protected void onDestroy() {
// 取消广播
Log.d(TAG,
"unregisterReceiver-----------------------------bluetoothRev");
if (bluetoothRev != null) {
Log.d(TAG,
"unregisterReceiver-----------------------------bluetoothRev");
unregisterReceiver(bluetoothRev);
}
super.onDestroy();
}
// 1、开启server控件监听函数
class serverOnClickListener implements OnClickListener {
@Override
public void onClick(View v) {
serverflag = true;
Log.d(TAG,
"server------1-------OnClick----------------------server wait client conn");
Intent intent = new Intent(
BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 350);
// 1、设置对其他设备蓝牙可见
startActivity(intent);
client.setEnabled(false);
conn.setEnabled(false);
// 2、接收到其他设备蓝牙连接请求
RequestAcceptThread ServerThread = new RequestAcceptThread();
ServerThread.start();
}
}
/* 2、server作为服务端应答socket请求,得到socket */
public class RequestAcceptThread extends Thread {
private BluetoothServerSocket m_BluetoothServersocket = null;
public RequestAcceptThread() {
BluetoothServerSocket tmpBluetoothServersocket = null;
try {
// 2、获得蓝牙连接的BluetoothServerSocket等待client连接
tmpBluetoothServersocket = adapter
.listenUsingRfcommWithServiceRecord(S_NAME, S_UUID);
} catch (IOException e) {
}
m_BluetoothServersocket = tmpBluetoothServersocket;
Log.d(TAG,
"server------2--------get m_BluetoothServersocket----------------ok");
// msg.setText("服务已开启");
}
@Override
public void run() {
super.run();
// 阻塞监听直到异常出现或者有socket返回
BluetoothSocket socket = null;
while (true) {
try {
// 2、等待连接后获得socket
socket = m_BluetoothServersocket.accept();
if (socket != null) {
Log.d(TAG,
"server------2---------socket----------get ok-------------------");
break;
}
} catch (IOException e) {
System.out.println("exception while waiting");
break;
}
}
Log.d(TAG,
"server------2---------requst----------get ok-------------------");
if (socket != null) {
// 3、开启线程读取监听的数据
ServerConnectedThread ServerReadthread = new ServerConnectedThread(
socket);
ServerReadthread.start();
}
}
// 4、 取消socket监听,关闭线程
public void cancel() {
try {
m_BluetoothServersocket.close();
} catch (IOException e) {
}
}
}
// 5、server接收发送数据
private class ServerConnectedThread extends Thread {
private final BluetoothSocket ServermmSocket;
Message msg = transHandler.obtainMessage();
public ServerConnectedThread(BluetoothSocket socket) {
ServermmSocket = socket;
InputStream ServertmpIn = null;
OutputStream ServertmpOut = null;
try {
ServertmpIn = socket.getInputStream();
ServertmpOut = socket.getOutputStream();
} catch (IOException e) {
}
Serverm_InputStream = ServertmpIn;
Serverm_OutputStream = ServertmpOut;
}
public void run() {
//Log.d(TAG,"ServerConnectedThread---------read----------data-------------------");
byte[] buffer = new byte[1024];
int bytes;
while (true) {
try {
bytes = Serverm_InputStream.read(buffer);
String str = new String(buffer, 0, bytes);
//Log.d(TAG,"ServerConnectedThread read----------data-------------------"+ str);
if (bytes != 0) {
try {
if (zmqsocket == null) {
zmqsocket = context.socket(ZMQ.REQ);
zmqsocket.connect("tcp://*.*.*.*:9999");
//Log.d(TAG,"zmqsocket reconnect ---------------------------. ");
}
zmqsocket.send(str.getBytes(), 0);
//Log.d(TAG,"B wait reply from zmq C -----------------------------------");
byte[] reply = zmqsocket.recv(0);
String r = new String(reply);
//Log.d(TAG,"recv from C ,writeString back A ----------------start-----------. "+ r.toString());
Serverm_OutputStream.write(reply);
//Log.d(TAG,"recv from C ,writeString back A -----------------end----------. "+ r.length());
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (IOException e) {
break;
}
}
}
/* Call this from the main Activity to send data to the remote device */
public void write(byte[] bytes) {
try {
// 写数据
//Log.d(TAG,"ServerConnectedThread write----------data-------------------"+ new String(bytes));
Serverm_OutputStream.write(bytes);
} catch (IOException e) {
}
}
/* 关闭mmSocket */
public void cancel() {
try {
ServermmSocket.close();
} catch (IOException e) {
}
}
}
// client-----1--------控件监听函数搜索附近的设备
class clientOnClickListener implements OnClickListener {
@Override
public void onClick(View v) {
Log.d(TAG,
"client-----1-------------OnClick----------------------client serch device");
bluetoothRev = new BluetoothRev();
// 创建intentfilter及广播接收函数
IntentFilter discoveryfilter = new IntentFilter(
BluetoothDevice.ACTION_FOUND);
registerReceiver(bluetoothRev, discoveryfilter);
IntentFilter foundfilter = new IntentFilter(
BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
// /client-----2--------注册广播
Log.d(TAG,
"client-----1----------------registerReceiver-------------------bluetoothRev");
registerReceiver(bluetoothRev, foundfilter);
// client-----3-------开始扫描设备,扫描到设备后会自动发广播
adapter.startDiscovery();
msgtext.setText("正在扫描");
server.setEnabled(false);
}
}
// client-----2-------广播接收类
private class BluetoothRev extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
// BluetoothDevice device =
// intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// client-----2-------发现设备
device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if ("GT-N7102".equals(device.getName())
|| "GT-I9300".equals(device.getName()))
blutToothDevices.add(device);
// blueToothNames.add(device.getName());
Log.d(TAG,
"client-----2--------------serch---------------------device");
Log.d(TAG,
"client-----2----------------serch-------------------device"
+ device.getName());
isfound = true;
Toast.makeText(Bluetooth_MainActivity.this, "已获取设备,可连接", 50)
.show();
// When discovery is finished, change the Activity title
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED
.equals(action)) {
if (isfound == false)
Log.d(TAG,
"client-----2-------------don't serch----------------------device");
else {
Log.d(TAG,
"client-----2------------- serch----------------------device");
msgtext.setText("发现设备");
}
// client-----4------取消扫描
adapter.cancelDiscovery();
// client-----4------取消广播
Bluetooth_MainActivity.this.unregisterReceiver(this);
}
}
}
// client-----5---获取bluetoothAdapter适配器,开始连接
class connOnClickListener implements OnClickListener {
@Override
public void onClick(View v) {
Log.d(TAG,
"client-----5--------------- onclick----------------------requst conn server");
// client-----5---开始请求连接发现的蓝牙设备
device = blutToothDevices.get(0);
Log.d(TAG, "client-----5--------------- requst link device name :"
+ device.getName());
// client-----6--------客户端请求连接的线程
RequestThread ClientThread = new RequestThread(device);
ClientThread.start();
}
}
// client-----6--------客户端请求连接的线程
private class RequestThread extends Thread {
private BluetoothSocket mmSocket = null;
private BluetoothDevice mmDevice = null;
public RequestThread(BluetoothDevice device) {
BluetoothSocket tmp = null;
// mmDevice = device;
Log.d(TAG, "client-----6--------startconn-------------------device"
+ device.getName());
msgtext.setText("开始申请连接");
try {
// client-----6------获取BluetoothSocket
tmp = device.createRfcommSocketToServiceRecord(S_UUID);
Log.d(TAG, "client-----6---start get--mmSocket");
} catch (IOException e) {
}
if (tmp != null) {
mmSocket = tmp;
Log.d(TAG, "client-----6-----get mmSocket");
}
}
public void run() {
// Cancel discovery because it will slow down the connection
while (true) {// 必须多次连接以保证成功连接
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
// client-----6------开始连接
Log.d(TAG, "client-----6-----try to connection");
mmSocket.connect();
if (mmSocket != null) {
// mSocketManage(mmSocket);
Log.d(TAG, "client-----6-----try to connection");
// client-----6-------连接成功开始发送数据
ConnectedThread readthread = new ConnectedThread(
mmSocket);
readthread.start();
break;
}
} catch (IOException connectException) {
Log.d(TAG, "client-----6-----unable to connection");
try {
mmSocket.close();
} catch (IOException closeException) {
}
return;
}
}
}
public void cancel() {
try {
// client-----6-----关闭一个mmSocket
mmSocket.close();
} catch (IOException e) {
}
}
}
// client-----7---发送数据
class sendOnClickListener implements OnClickListener {
@Override
public void onClick(View v) {
Log.d(TAG,
"client-----7--------------- onclick----------------------send");
data = "";
for (int k = 0; k < i; k++) {
data = data + "a";
}
Log.d(TAG, "client-----7--------------- data " + data);
Log.d(TAG, "client-----7--------------- i: " + i + "---c:" + c);
startMili = System.currentTimeMillis();// 开始时间
try {
m_OutputStream.write(data.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
}
// client------8------ 接收发送数据
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
Message msg = transHandler.obtainMessage();
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
}
m_InputStream = tmpIn;
m_OutputStream = tmpOut;
}
public void run() {
//Log.d(TAG,"client------8--------start-----read----------data-------------------");
byte[] buffer = new byte[1024];
int bytes;
int cout = 1;
//Log.d(TAG, "client------8------ c----------" + c);
boolean flag = true;
while (flag) {
try {
if (cout >= c) {
endMili = System.currentTimeMillis();// 开始时间
// msg.obj =String.valueOf(endMili-startMili);
Log.d(TAG, "client------8------ time----------"+ String.valueOf(endMili - startMili));
//Log.d(TAG, "client------8------ sendMessage----------"+ cout);
//Bundle b = new Bundle();// 存放数据
//b.putString("time", String.valueOf(endMili - startMili));
//msg.setData(b);
//transHandler.sendMessage(msg);
cout = 1;
flag = false;
}
bytes = m_InputStream.read(buffer);
if (bytes != 0) {
//Log.d(TAG,"client------8------ read----------cout-------------------"+ cout);
String str = new String(buffer, 0, bytes);
cout++;
// msg.obj = new String(buffer, 0, bytes);
// msg.arg1 = bytes;
// 更新界面
// transHandler.sendMessage(msg);
m_OutputStream.write(data.getBytes());
} else {
bytes = m_InputStream.read(buffer);
}
} catch (IOException e) {
break;
}
}
}
/* Call this from the main Activity to send data to the remote device */
public void write(byte[] bytes) {
try {
// 写数据
//Log.d(TAG,"client------8------write----------data-------------------"+ new String(bytes));
m_OutputStream.write(bytes);
} catch (IOException e) {
}
}
/* 关闭mmSocket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
}
}
}
}
[ 本帖最后由 sweet6hero 于 2014-9-26 16:11 编辑 ]