⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 client.java

📁 基于J2ME的一个可用的手机蓝牙程序
💻 JAVA
字号:

import java.util.*;

import javax.bluetooth.*;

public class Client implements Runnable,DiscoveryListener{
	
	private Canvas canvas;
	
	private Thread thread;
	private DiscoveryAgent discoveryagent;//发现服务代理
	//	响应服务的UUID
	private static final UUID ECHO_SERVER_UUID=new UUID("F0E0D0C0B0A000908070605040302010", false);

	private static final int inquiryAccessCode = DiscoveryAgent.GIAC;
	private Vector transIDs=new Vector();//服务搜索事务ID的集合
	private Vector unsearchedRemoteDevices=new Vector();

	private int numServiceSearchesInProgress=0;

	private boolean inquiryInProgress=false;

	private Hashtable  serviceRecord=new Hashtable();

	private Vector add=new Vector();

	private ClientProcessor newHandler;

	
//	-----------------------------构造函数---------------------------
	public Client(Canvas canvas){
		this.canvas=canvas;
		
		try{
			LocalDevice localdevice=LocalDevice.getLocalDevice();
			discoveryagent=localdevice.getDiscoveryAgent();
		}catch(BluetoothStateException e){}

        
		start();
	}

	
	public synchronized void start() {
        thread = new Thread(this);
        thread.start();
	}
	
	
	public void run(){
        Thread currentThread = Thread.currentThread();
        running:
        while (thread == currentThread)
        {
            synchronized (this)
            {
                if (thread != currentThread)
                {
                    break running;
                }
                else if (!inquiryInProgress)
                {
                    doServiceSearch();
                }

               try
                {
                    wait(500);
                }
                catch (InterruptedException e)
                {
                    // we can safely ignore this
                }
            }
        }
	}
	
	
//	-----------------------------查找主机---------------------------	
	  public void doServiceSearch()
	    {
	        if (unsearchedRemoteDevices.size() > 0) 
	        {
	            synchronized(this)
	            {
	                RemoteDevice device =(RemoteDevice) unsearchedRemoteDevices .elementAt(0);
	                UUID[] uuids = new UUID[1];
	                uuids[0] = ECHO_SERVER_UUID;
	                try
	                {
	                    int[] attrSet = null; // default attrSet
	                    numServiceSearchesInProgress++;
	                    int transId = discoveryagent.searchServices(attrSet, uuids,device, this);
	                    transIDs.addElement(new Integer(transId));
	                    unsearchedRemoteDevices.removeElementAt(0);
	                }
	                catch (BluetoothStateException e)
	                {
	                    numServiceSearchesInProgress--;
	                }
	            }
	        }
	    }
	  
	
//		-----------------------------唤醒设备查找---------------------------
		public void inquiryCompleted(int discType) {
			// TODO 自动生成方法存根
			inquiryInProgress=false;
		}

		
	  
//		-----------------------------唤醒服务查找---------------------------
		public void serviceSearchCompleted(int transId, int respCode) {
			// TODO 自动生成方法存根
			 // remove the transaction id from the pending list
	        for (int i=0; i < transIDs.size(); i++)
	        {
	            Integer pendingId = (Integer) transIDs.elementAt(i);
	            if (pendingId.intValue() == transId)
	            {
	            	transIDs.removeElement(pendingId);
	                break;
	            }
	        }

		}
		
	
		
//		-----------------------------服务查找---------------------------
		public void servicesDiscovered(int transID, ServiceRecord[] serviceRecords) {
			// TODO 自动生成方法存根
			 if (serviceRecords.length == 1)
		        {
		            RemoteDevice device = serviceRecords[0].getHostDevice();
		            String name = device.getBluetoothAddress();

		            if (!serviceRecord.containsKey(name))
		            {
		            	serviceRecord.put(name, serviceRecords[0]);
			            add.addElement(name);
		            }
		        }

		}

		
//		-----------------------------设备查找---------------------------
		public void deviceDiscovered(RemoteDevice remoteDevice, DeviceClass deviceClass) {
			// TODO 自动生成方法存根
			  boolean isPhone =(deviceClass.getMajorDeviceClass() == 0x200);

		        // Setting the following line to 'true' is a workaround
		        // for some early beta SDK device emulators. Set it
		        // to false when compiling the MIDlet for download to
		        // real MIDP phones!
		        boolean isEmulator = true; //false;

		        if (isPhone || isEmulator)
		        {
		            unsearchedRemoteDevices.addElement(remoteDevice);
		        }
		}

		
		
		
		  //取得地址
		  public String getAdd(int i){
			  return add.elementAt(i).toString();
		  }
		  
		  //取得服务地址数
		  public int getAddsize(){
			  return add.size();
		  }
		  
		  
		 //开始查找服务 
		  public void dosearch(){
			   // remove old device lists
			  add.removeAllElements();
	          unsearchedRemoteDevices.removeAllElements();
	            for (Enumeration keys = serviceRecord.keys();
                keys.hasMoreElements();)
	            {
	            	serviceRecord.remove(keys.nextElement());
	            }

	          try
	          {
	              // disable page scan and inquiry scan
	              LocalDevice dev = LocalDevice.getLocalDevice();
	              dev.setDiscoverable(DiscoveryAgent.NOT_DISCOVERABLE);
	              //startActivityIndicator();
	              // this is non-blocking
	              discoveryagent.startInquiry(inquiryAccessCode, this);

	              inquiryInProgress=true;
	         
	          }
	          catch (BluetoothStateException e) {}
		  }
		  
		  
		  //建立连接
		  public void makeConn(int n){
	          ServiceRecord ServiceRecord =(ServiceRecord) serviceRecord.get(add.elementAt(n));
	         
        	  newHandler =new ClientProcessor(this,ServiceRecord);
              newHandler.start(); // start reader & writer
			}
		
		  
		   
		    public void read(byte[] temp){
				canvas.read(temp);
			}
			
			public void send(String data){
				newHandler.send(data);
				System.out.println(data);
			}
			

		

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -