J2ME蓝牙程序开发实战入门(2)

分类: J2ME   出处:iocblog整理  更新时间:2009-02-01   添加到收藏  

  /**
  * 客户端gui
  * @author jagie
  *
  * todo to change the template for this generated type comment go to
  * window - preferences - java - code style - code templates
  */
  public class clientbox extends form implements runnable, commandlistener,
  discoverylistener {
  
  //字串输入框
  textfield input = new textfield(null, "", 50, textfield.any);
  //loger
  stringitem result = new stringitem("结果:", "");
  
  private discoveryagent discoveryagent;
  
  private uuid[] uuidset;
  
  //响应服务的uuid
  private static final uuid echo_server_uuid = new uuid(
  "f0e0d0c0b0a000908070605040302010", false);
  
  //设备集合
  vector devices = new vector();
  //服务集合
  vector records = new vector();
  
  //服务搜索的事务id集合
  int[] transids;
  stupidbtmidlet midlet;
  
  public clientbox(stupidbtmidlet midlet) {
  super("");
  this.midlet=midlet;
  
  this.append(result);
  
  this.addcommand(new command("取消",command.cancel,1));
  this.setcommandlistener(this);
  
  new thread(this).start();
  }
  
  public void commandaction(command arg0, displayable arg1) {
  if(arg0.getcommandtype()==command.cancel){
  midlet.showmainmenu();
  }else{
  //匿名内部thread,访问远程服务。
  thread fetchthread=new thread(){
  public void run(){
  for(int i=0;i<records.size();i++){
  servicerecord sr=(servicerecord)records.elementat(i);
  if(accessservice(sr)){
  //访问到一个可用的服务即可
  break;
  }
  }
  }
  };[iocblog.net 来源]
  fetchthread.start();
  }
  
  }
  
  private boolean accessservice(servicerecord sr){
  boolean result=false;
  try {
  string url = sr.getconnectionurl(
  servicerecord.noauthenticate_noencrypt, false);
  streamconnection  conn = (streamconnection) connector.open(url);
  
  dataoutputstream dos=conn.opendataoutputstream();
  dos.writeutf(input.getstring());
  dos.close();
  datainputstream dis=conn.opendatainputstream();
  string echo=dis.readutf();
  dis.close();
  showinfo("反馈结果是:"+echo);
  result=true;
  
  } catch (ioexception e) {
  
  }
  return result;
  }
  
  public synchronized void run() {
  //发现设备和服务的过程中,给用户以gauge
  gauge g=new gauge(null,false,gauge.indefinite,gauge.continuous_running);
  this.append(g);
  showinfo("蓝牙初始化...");
  boolean isbtready = false;
  
  try {
  
  localdevice localdevice = localdevice.getlocaldevice();
  discoveryagent = localdevice.getdiscoveryagent();
  
  isbtready = true;
  } catch (exception e) {
  e.printstacktrace();
  }
  
  if (!isbtready) {
  showinfo("蓝牙不可用");
  //删除gauge
  this.delete(1);
  return;
  }
  
  uuidset = new uuid[2];
  
  //标志我们的响应服务的uuid集合
  uuidset[0] = new uuid(0x1101);
  uuidset[1] = echo_server_uuid;
  
  try {
  discoveryagent.startinquiry(discoveryagent.giac, this);
  } catch (bluetoothstateexception e) {
  
  }
  
 [iocblog.net 来源]

上一页 [1] [2]


Tag: 蓝牙程序



文章整理:iocblog
版权申明:本站文章均来自网络,如有侵权,请联系我们,我们收到后立即删除,谢谢!
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有。