الفريق العربي للبرمجةأرشيف المنتديات · 2000 – 2023
نسخة أرشيفية للقراءة فقط — التسجيل والمشاركة مغلقان، والمحتوى محفوظ كما كان.

مشكلة في البحث عن الاجهزة والارتباط بها باستخدام البلوتوث....ارجو المساعدة عاجلا

بدأه سحابة خير في 11 سبتمبر 2008 · 0 رد · 1,255 مشاهدة · في JavaME
مشاركة: واتساب X فيسبوك تيليجرام
#1
السلام عليكم...من فضلكم اريد حل لمشكلة البرنامج التالي الذي يقوم بالربط بين الجوال (الزبون)واللابتوب

عندما اقوم بالبحث لاينفذ المطلوب ولم استطع معرفة الخلل:

client:

import java.io.*;

import javax.microedition.io.*;

import javax.bluetooth.*;

import java.io.IOException;

import java.util.Vector;

import javax.bluetooth.BluetoothStateException;

import javax.bluetooth.LocalDevice;

import javax.bluetooth.ServiceRecord;

import javax.microedition.midlet.*;

import javax.microedition.lcdui.*;

/**

* @author MacBook pc

*/

public class Client extends MIDlet implements

Runnable,CommandListener, DiscoveryListener{

private final static String UUID =

"A55665EE9F9146109085001F5B7A9241";

private final static String SERVICE_URL =

"btspp://localhost:" + UUID;

private Display display;

private Form form;

private DiscoveryAgent agent;

private Command exitCommand;

private Command searchCommand;

private Command connect;

private Command Back;

/**

* The max number of service searches that can occur at any one time.

*/

private int maxServiceSearches = 0;

/**

* The number of service searches that are presently in progress.

*/

private int serviceSearchCount;

/**

* Keeps track of the transaction IDs returned from searchServices.

*/

private int transactionID[];

/**

* The service record to a printer service that can print the message

* provided at the command line.

*/

private ServiceRecord record;

/**

* Keeps track of the devices found during an inquiry.

*/

private Vector deviceVector;

private String data="hello Server";

private List dList;

public Client() throws BluetoothStateException{

/*

* Retrieve the local Bluetooth device object.

*/

LocalDevice local = LocalDevice.getLocalDevice();

/*

* Retrieve the DiscoveryAgent object that allows us to perform device

* and service discovery.

*/

agent = local.getDiscoveryAgent();

/*

* Retrieve the max number of concurrent service searches that can

* exist at any one time.

*/

try {

maxServiceSearches = Integer.parseInt(

LocalDevice.getProperty("bluetooth.sd.trans.max"));

} catch (NumberFormatException e)

{

form.append("General Application Error");

}

transactionID = new int[maxServiceSearches];

// Initialize the transaction list

for (int i = 0; i < maxServiceSearches; i++) {

transactionID
= -1;

}

record = null;

deviceVector = new Vector();

}

public void run() {

form = new Form("M-Learning System");

form.append("Welcome to the client..\n");

display = Display.getDisplay(this);

display.setCurrent(form);

exitCommand = new Command("Exit", Command.EXIT, 1);

searchCommand = new Command("Search",

Command.SCREEN, 1);

form.addCommand(exitCommand);

form.addCommand(searchCommand);

form.setCommandListener(this);

}

/**

* Adds the transaction table with the transaction ID provided.

*

* @param trans the transaction ID to add to the table

*/

private void addToTransactionTable(int trans) {

for (int i = 0; i < transactionID.length; i++) {

if (transactionID
== -1) {

transactionID
= trans;

return;

}

}

}

/**

* Removes the transaction from the transaction ID table.

*

* @param trans the transaction ID to delete from the table

*/

private void removeFromTransactionTable(int trans) {

for (int i = 0; i < transactionID.length; i++) {

if (transactionID
== trans) {

transactionID
= -1;

return;

}

}

}

public void BluetoothMIDlet() {}

/**

* Completes a service search on each remote device in the list until all

* devices are searched or until a service is found that this application

* can connect to.

*

* @param devList the list of remote Bluetooth devices to search

*

* @return true if a connection service is found; otherwise false if

* no printer service was found on the devList provided

*

*/

private boolean searchServices(RemoteDevice[] devList) {

UUID[] searchList = new UUID[2];

/*

* Add the UUID for RFCOMM to make sure that the service record

* found will support RFCOMM. This value is defined in the

* Bluetooth Assigned Numbers document.

*/

searchList[0] = new UUID(0x0003);

/*

* Add the UUID for the printer service that we are going to use to

* the list of UUIDs to search for. (a fictional printer service UUID)

*/

searchList[1] = new UUID(UUID, false);

/*

* Start a search on as many devices as the system can support.

*/

for (int i = 0; i < devList.length; i++) {

/*

* If we found a service record for the printer service, then

* we can end the search.

*/

if (record != null) {

return true;

}

try {

int trans = agent.searchServices(null, searchList, devList
,

this);

addToTransactionTable(trans);

} catch (BluetoothStateException e) {

/*

* Failed to start the search on this device, try another

* device.

*/

}

/*

* Determine if another search can be started. If not, wait for

* a service search to end.

*/

synchronized (this) {

serviceSearchCount++;

if (serviceSearchCount == maxServiceSearches) {

try {

this.wait();

} catch (Exception e) {

}

}

}

}

/*

* Wait until all the service searches have completed.

*/

while (serviceSearchCount > 0) {

synchronized (this) {

try {

this.wait();

} catch (Exception e) {

}

}

}

if (record != null) {

return true;

} else {

return false;

}

}

public void startApp()

throws MIDletStateChangeException {

new Thread(this).start();

}

public void pauseApp() {}

public void destroyApp(boolean unconditional) {}

public void commandAction(Command c, Displayable d) {

ServiceRecord connectService = null ;

if (c==searchCommand){

try {

// Create a new List and set it to the current

// displayable

// Create a new List and set it to the current

// displayable

dList = new List("List of Devices", List.EXCLUSIVE);

dList.addCommand(new Command("Back", Command.BACK, 1));

dList.addCommand(new Command("Connect", Command.OK, 1));

dList.setCommandListener(this);

Display.getDisplay(this).setCurrent(dList);

/* Start an inquiry to find a printer */

try {

agent.startInquiry(DiscoveryAgent.GIAC, this);

/*

* Wait until all the devices are found before trying to start the

* service search.

*/

synchronized (this) {

try {

this.wait();

} catch (Exception e) {

}

}

} catch (BluetoothStateException e) {

System.out.println("Unable to find devices to search");

}

connectService = search();

} catch (BluetoothStateException ex) {

ex.printStackTrace();

} catch (MIDletStateChangeException ex) {

ex.printStackTrace();

} catch (IOException ex) {

ex.printStackTrace();

}

}

else if(c== connect)

try {

if(connectService != null)

connect();

} catch (BluetoothStateException ex) {

ex.printStackTrace();

}

else if(c==Back){

}

else

notifyDestroyed();

}

public ServiceRecord search() throws BluetoothStateException, MIDletStateChangeException, IOException{

RemoteDevice[] devList;

if (deviceVector.size() > 0) {

devList = new RemoteDevice[deviceVector.size()];

deviceVector.copyInto(devList);

if (searchServices(devList)) {

return record;

}

}

return null;

}

public void connect() throws BluetoothStateException{

OutputStream os = null;

try {

StreamConnection conn = (StreamConnection)Connector.open(SERVICE_URL);

/*

* Sends data to remote device

*/

os = conn.openOutputStream();

os.write(data.getBytes());

form.append("Bluetooth connection successfully established.\n");

os.close();

conn.close();

} catch(IOException e) {

form.append("IOException");

form.append(e.getMessage());

}

}

public void deviceDiscovered(RemoteDevice device, DeviceClass arg1) {

String name = null ;

if(arg1.getMajorDeviceClass()==0x100)

if (arg1.getServiceClasses()== 0x20000){

try {

name = device.getFriendlyName(true);

} catch (IOException ex) {

ex.printStackTrace();

}

dList.insert(0, name+ "-I", null);

deviceVector.insertElementAt(device, 0);

}

}

public void serviceSearchCompleted(int transID, int respCode) {

/*

* Removes the transaction ID from the transaction table.

*/

removeFromTransactionTable(transID);

serviceSearchCount--;

synchronized (this) {

this.notifyAll();

}

}

/**

* Called when service(s) are found during a service search.

* This method provides the array of services that have been found.

*

* @param transID the transaction ID of the service search that is

* posting the result

*

* @param service a list of services found during the search request

*

* @see DiscoveryAgent#searchServices

*/

public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {

/*

* If this is the first record found, then store this record

* and cancel the remaining searches.

*/

if (record == null) {

record = servRecord[0];

/*

* Cancel all the service searches that are presently

* being performed.

*/

for (int i = 0; i < transactionID.length; i++) {

if (transactionID
!= -1) {

agent.cancelServiceSearch(transactionID
);

}

}

}

}

public void inquiryCompleted(int arg0) {

Alert dialog = null;

// Determine if an error occurred. If one did

// occur display an Alert

// before allowing the application to exit.

if (arg0 != DiscoveryListener.INQUIRY_COMPLETED) {

dialog = new Alert("Bluetooth Error",

"The inquiry failed to complete normally",

null, AlertType.ERROR);

} else {

dialog = new Alert("Inquiry Completed",

"The inquiry completed normally", null,

AlertType.INFO);

}

dialog.setTimeout(Alert.FOREVER);

Display.getDisplay(this).setCurrent(dialog);

}

}

مواضيع مشابهة

عدد الزوار حالياً

المتواجدون خلال آخر دقيقتين · يتحدّث كل ٣٠ ثانية

—الإجمالي—أعضاء مسجّلون—زوار بدون تسجيل

جارٍ التحقق من المتواجدين…