注册 登录
编程论坛 Android开发

蓝牙通信

sweet6hero 发布于 2014-09-26 16:05, 5993 次点击
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 编辑 ]
6 回复
#2
sweet6hero2014-09-26 16:06
蓝牙跟zmq通信,需要zmq.jar跟libjzmq.so  测试蓝牙转wifi性能

[ 本帖最后由 sweet6hero 于 2014-9-26 16:07 编辑 ]
#3
sweet6hero2014-09-26 16:11
package test;

import org.zeromq.ZMQ;
import org.zeromq.ZMQException;

public class zmqREPtest {
    public static void main(String[] argv) {
                  ZMQ.Context context = ZMQ.context(1);
                  ZMQ.Socket socket = context.socket(ZMQ.REP);
                  String url = "tcp://*:9999";
                  try {
                      socket.bind(url);
                  } catch (ZMQException e) {
                      throw e;
                  }
                 boolean wait = true;
                 while (wait) {
                     byte[] request;
                     try {
                         request = socket.recv(0);
         
 
                         /* TODO process request
                          * .....
                         */
                         socket.send("OK".getBytes(), 1);
         
                     } catch (ZMQException e) {
                         throw e;
                     }
                 } // while(wait)
             }
}
#4
sweet6hero2014-09-26 16:13
package com.example.zmq;

import org.zeromq.ZMQ;
import org.zeromq.ZMQException;

import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
@SuppressLint("NewApi")
public class MainActivity extends Activity {
    protected static final String TAG="ZMQMainActivity";
    static {
        System.loadLibrary("jzmq");
        Log.d(TAG, "loadlibrary ---------------------------. ");
        }
    public ZMQ.Context context=ZMQ.context(1);
    public static String urlrep = "tcp://*:9999";
   
    public TextView tv;
    public   ZMQ.Socket socketrep;
    private  IZMQService zmqService=null;
    private boolean mIsBound;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //启动servie
        doBindService();
        tv = (TextView) findViewById(R.id.TextView02);
        
    }
   
    @Override
    public void onResume() {
        super.onResume();
        //注册广播
        IntentFilter zmqActionFilter = new IntentFilter(
                ZMQService.BROADCAST_COUNTER_ACTION);
        registerReceiver(zmqActionReceiver, zmqActionFilter);
    }

    @SuppressLint("NewApi")
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.my_menu, menu);
        Log.d(TAG, "onCreateOptionsMenu---------. ");
        menu.getItem(0).setIcon(android.R.drawable.ic_input_get);
        menu.getItem(1).setIcon(android.R.drawable.ic_input_add);
        menu.getItem(2).setIcon(android.R.drawable.ic_input_delete);
        return true;
    }
 
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getTitle().equals("连接")) {
            try {
                try {
                    //发回
                    Log.d(TAG, "connect--------------------. ");
                    if(context==null){
                         context=ZMQ.context(1);
                    }
                    if(socketrep==null){
                         socketrep =context.socket(ZMQ.REP);
                    }
                    socketrep.bind(urlrep);
                 } catch (ZMQException e) {
                      Log.d(TAG, "ZMQException--------------------. "+e.getMessage());
                      throw e;
                 }
                tv.setText("connect succesful");
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (item.getTitle().equals("接收")) {
            Log.d(TAG, "startRev--------------------. ");
            //zmqService.startRev(socketrep);
            new Thread(new Runnable(){

                @Override
                public void run() {
                     boolean wait = true;
                     while (wait) {
                         byte[] request;
                         try {
                             request = socketrep.recv(0);
                             String str=new String(request);
                             Log.d(TAG, "startRev--------------------. "+str);
                             //System.out.println(str);
                             socketrep.send(request, 1);
                         } catch (ZMQException e) {
                             throw e;
                         }
                     } // while(wait)
                    
                }
               
            }).start();

        } else if (item.getTitle().equals("断开")) {
                    try {
                        Log.d(TAG, "stopRev--------------------. ");
                        if(socketrep !=null){
                            socketrep.close();
                            Log.d(TAG, "---------------------. ");
                            socketrep=null;
                        }
                        if(zmqService !=null)
                              zmqService.stopRev();
                        Log.d(TAG, "---------------------. ");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
        }
        
        return super.onOptionsItemSelected(item);
    }
   
    @Override
    public void onPause() {
        super.onPause();
        unregisterReceiver(zmqActionReceiver);
        doUnbindService();
    }
   
   
   
    void doBindService() {
        bindService(new Intent(MainActivity.this, ZMQService.class),mConnection, Context.BIND_AUTO_CREATE);
        mIsBound = true;
    }

    void doUnbindService() {
        if (mIsBound) {
            unbindService(mConnection);
            mIsBound = false;
        }
    }
   
    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
             // service连接建立时将调用该方法
            zmqService = ((ZMQService.ZMQBinder) service).getService();
            Log.d(TAG, "zmqService--------------------.onServiceConnected ");
         
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            // 当进程崩溃时将被调用,因为运行在同一程序,如果是崩溃将所以永远不会发生
            // 当解除绑定时也被调用
            zmqService = null;
            Log.d(TAG, "zmqService--------------------.onServiceDisconnected ");
            
        }
    };
   

   
  //广播接收调用的函数
  private BroadcastReceiver zmqActionReceiver = new BroadcastReceiver() {
          public void onReceive(Context context, Intent intent) {
              //获取广播的值
              String r=intent.getStringExtra(ZMQService.COUNTER_VALUE);
              tv.setText(r.toString());
              Log.d(TAG, "Receive  event-------------------"+r);
          }
      };

}
#5
sweet6hero2014-09-26 16:13
package com.example.zmq;

import org.zeromq.ZMQ;

public interface IZMQService {
     public void startRev(ZMQ.Socket socketrep);
     public void stopRev();
}
#6
sweet6hero2014-09-26 16:13
package com.example.zmq;

import org.zeromq.ZMQ;
import org.zeromq.ZMQ.Socket;
import org.zeromq.ZMQException;

import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

public class ZMQService extends Service implements IZMQService {
    private final static String TAG = "ZMQMainActivity";

    public final static String BROADCAST_COUNTER_ACTION = "broadcast.COUNTER_ACTION";
    public final static String COUNTER_VALUE = "broadcast.zmq.value";

    private ZMQ.Socket socketrep;
    private boolean wait = true;

    public class ZMQBinder extends Binder {
        // 通过binder类获得服务接口
        public ZMQService getService() {
            return ZMQService.this;
        }
    }

    private final IBinder binder = new ZMQBinder();

    // 服务启动后调用该方法
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    // 服务初始化
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "Counter Service Created---------------------.");
    }

    @Override
    public void onDestroy() {
        Log.d(TAG, "Counter Service Destroyed----------------.");
    }

    @Override
    public void startRev(ZMQ.Socket socketrep) {
        if (socketrep == null) {
             Log.d(TAG, "socketrep------------is null--------. ");
             Intent intent = new Intent(BROADCAST_COUNTER_ACTION);
             intent.putExtra(COUNTER_VALUE, "socketrep is null");
             sendBroadcast(intent);
             return;
        }
        // 开一个异步的线程
        AsyncTask<ZMQ.Socket, Void, String> task = new AsyncTask<ZMQ.Socket, Void, String>() {

            @Override
            protected String doInBackground(ZMQ.Socket... params) {
                 ZMQ.Socket s=params[0];
                 Log.d(TAG, "S--------------------. "+s.toString());
                 wait = true;
                 while (wait) {
                     byte[] request;
                     try {
                         request = s.recv(0);
                         String str=new String(request);
                         //Log.d(TAG, "str--------------------. "+str);
                         s.send(request, 1);
                         if(str.equals("ok")){
                             wait=false;
                             Intent intent = new Intent(BROADCAST_COUNTER_ACTION);
                                intent.putExtra(COUNTER_VALUE, "ok");
                                // 发送广播
                                sendBroadcast(intent);
                         }
         
                     } catch (ZMQException e) {
                         throw e;
                     }
                 }
                return "ok";
            }
        };
        task.execute(socketrep);
    }

    public void stopRev() {
        wait = false;
    }
}
#7
snakezou2015-01-01 18:30
请问做过用Qt进行蓝牙传输的例子吗?
1