Hi all.
Hope you can help me out with this problem.
I am trying to get a bluetooth finder to stop, and start again.
What I can see is that the first time it stops and then start again, it work. the next time I do it, nothing happens. When I say it works, I mean it finds the devices and lists them. It doesnt do that the second time. I can see that it doesnt stop the first time as my test output keeps spitting out data. Hope someone can help me here. thx in advance.
P.s. this is a modification of another bluetooth code so not my own work, just trying to rewrite it so it fits my need.
Main midlet:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Vector;
import javax.bluetooth.LocalDevice;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import org.netbeans.microedition.lcdui.SplashScreen;
import org.netbeans.microedition.lcdui.TableItem;
/**
* @author MMA
*/
public class MainMidlet extends MIDlet implements CommandListener, Runnable {
private boolean midletPaused = false;
MyFinder mainFinder = new MyFinder(this);
//<editor-fold defaultstate="collapsed" desc=" Generated Fields ">
private List Menu;
private Form ClientForm;
private TextField textField;
private Form ServerForm;
private StringItem stringItem;
private TableItem tableItem;
private Form ServerList;
private ChoiceGroup choiceGroup;
private SplashScreen SendSplash;
private Command backCommand1;
private Command backCommand;
private Command okCommand1;
private Command okCommand;
private Command exitCommand;
private Command backCommand2;
private Command okCommand2;
private Command Send;
private Command start_searchCommand;
private Command stop_searchCommand;
private Image image1;
//</editor-fold>
/**
* The MainMidlet constructor.
*/
public MainMidlet() {
}
//<editor-fold defaultstate="collapsed" desc=" Generated Methods ">
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc=" Generated Method: initialize ">
/**
* Initilizes the application.
* It is called only once when the MIDlet is started. The method is called before the <code>startMIDlet</code> method.
*/
private void initialize () {
// write pre-initialize user code here
// write post-initialize user code here
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc=" Generated Method: startMIDlet ">
/**
* Performs an action assigned to the Mobile Device - MIDlet Started point.
*/
public void startMIDlet () {
// write pre-action user code here
switchDisplayable (null, getMenu ());
// write post-action user code here
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc=" Generated Method: resumeMIDlet ">
/**
* Performs an action assigned to the Mobile Device - MIDlet Resumed point.
*/
public void resumeMIDlet () {
// write pre-action user code here
// write post-action user code here
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc=" Generated Method: switchDisplayable ">
/**
* Switches a current displayable in a display. The <code>display</code> instance is taken from <code>getDisplay</code> method. This method is used by all actions in the design for switching displayable.
* @param alert the Alert which is temporarily set to the display; if <code>null</code>, then <code>nextDisplayable</code> is set immediately
* @param nextDisplayable the Displayable to be set
*/
public void switchDisplayable (Alert alert, Displayable nextDisplayable) {
// write pre-switch user code here
Display display = getDisplay ();
if (alert == null) {
display.setCurrent (nextDisplayable);
} else {
display.setCurrent (alert, nextDisplayable);
}
// write post-switch user code here
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc=" Generated Method: commandAction for Displayables ">
/**
* Called by a system to indicated that a command has been invoked on a particular displayable.
* @param command the Command that was invoked
* @param displayable the Displayable where the command was invoked
*/
public void commandAction (Command command, Displayable displayable) {
// write pre-action user code here
if (displayable == ClientForm) {
if (command == backCommand1) {
// write pre-action user code here
switchDisplayable (null, getMenu ());
// write post-action user code here
} else if (command == okCommand1) {
// write pre-action user code here
switchDisplayable (null, getServerList ());
// write post-action user code here
}
} else if (displayable == Menu) {
if (command == List.SELECT_COMMAND) {
// write pre-action user code here
MenuAction ();
// write post-action user code here
} else if (command == exitCommand) {
// write pre-action user code here
exitMIDlet ();
// write post-action user code here
}
} else if (displayable == SendSplash) {
if (command == SplashScreen.DISMISS_COMMAND) {
// write pre-action user code here
switchDisplayable (null, getServerList ());
// write post-action user code here
}
} else if (displayable == ServerForm) {
if (command == backCommand) {
// write pre-action user code here
switchDisplayable (null, getMenu ());
// write post-action user code here
} else if (command == okCommand) {
// write pre-action user code here
switchDisplayable (null, getServerForm ());
// write post-action user code here
}
} else if (displayable == ServerList) {
if (command == backCommand2) {
// write pre-action user code here
switchDisplayable (null, getClientForm ());
// write post-action user code here
} else if (command == okCommand2) {
// write pre-action user code here
switchDisplayable (null, getSendSplash ());
// write post-action user code here
} else if (command == start_searchCommand) {
// write pre-action user code here
start_device_search();
// write post-action user code here
} else if (command == stop_searchCommand) {
// write pre-action user code here
stop_device_search();
// write post-action user code here
}
}
// write post-action user code here
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc=" Generated Getter: Menu ">
/**
* Returns an initiliazed instance of Menu component.
* @return the initialized component instance
*/
public List getMenu () {
if (Menu == null) {
// write pre-init user code here
Menu = new List ("Menu", Choice.IMPLICIT);
Menu.append ("Client", null);
Menu.append ("Server", null);
Menu.addCommand (getExitCommand ());
Menu.setCommandListener (this);
Menu.setSelectedFlags (new boolean[] { false, false });
// write post-init user code here
}
return Menu;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc=" Generated Method: MenuAction ">
/**
* Performs an action assigned to the selected list element in the Menu component.
*/
public void MenuAction () {
// enter pre-action user code here
String __selectedString = getMenu ().getString (getMenu ().getSelectedIndex ());
if (__selectedString != null) {
if (__selectedString.equals ("Client")) {
// write pre-action user code here
switchDisplayable (null, getClientForm ());
// write post-action user code here
} else if (__selectedString.equals ("Server")) {
// write pre-action user code here
switchDisplayable (null, getServerForm ());
// write post-action user code here
}
}
// enter post-action user code here
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc=" Generated Getter: ClientForm ">
/**
* Returns an initiliazed instance of ClientForm component.
* @return the initialized component instance
*/
public Form getClientForm () {
if (ClientForm == null) {
// write pre-init user code here
ClientForm = new Form ("", new Item[] { getTextField () });
ClientForm.addCommand (getBackCommand1 ());
ClientForm.addCommand (getOkCommand1 ());
ClientForm.setCommandListener (this);
// write post-init user code here
}
return ClientForm;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc=" Generated Getter: textField ">
/**
* Returns an initiliazed instance of textField component.
* @return the initialized component instance
*/
public TextField getTextField () {
if (textField == null) {
// write pre-init user code here
textField = new TextField ("Message:", null, 32, TextField.ANY);
// write post-init user code here
}
return textField;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc=" Generated Getter: ServerForm ">
/**
* Returns an initiliazed instance of ServerForm component.
* @return the initialized component instance
*/
public Form getServerForm () {
if (ServerForm == null) {
// write pre-init user code here
ServerForm = new Form ("Server", new Item[] { getTableItem (), getStringItem () });
ServerForm.addCommand (getBackCommand ());
ServerForm.addCommand (getOkCommand ());
ServerForm.setCommandListener (this);
// write post-init user code here
}
return ServerForm;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc=" Generated Getter: tableItem ">
/**
* Returns an initiliazed instance of tableItem component.
* @return the initialized component instance
*/
public TableItem getTableItem () {
if (tableItem == null) {
// write pre-init user code here
tableItem = new TableItem (getDisplay (), "Device:");
// write post-init user code here
}
return tableItem;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc=" Generated Getter: stringItem ">
/**
* Returns an initiliazed instance of stringItem component.
* @return the initialized component instance
*/
public StringItem getStringItem () {
if (stringItem == null) {
// write pre-init user code here
stringItem = new StringItem ("Message", null);
// write post-init user code here
}
return stringItem;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc=" Generated Getter: backCommand ">
/**
* Returns an initiliazed instance of backCommand component.
* @return the initialized component instance
*/
public Command getBackCommand () {
if (backCommand == null) {
// write pre-init user code here
backCommand = new Command ("Back", Command.BACK, 0);
// write post-init user code here
}
return backCommand;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc=" Generated Getter: backCommand1 ">
/**
* Returns an initiliazed instance of backCommand1 component.
* @return the initialized component instance
*/
public Command getBackCommand1 () {
if (backCommand1 == null) {
// write pre-init user code here
backCommand1 = new Command ("Back", Command.BACK, 0);
// write post-init user code here
}
return backCommand1;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc=" Generated Getter: okCommand1 ">
/**
* Returns an initiliazed instance of okCommand1 component.
* @return the initialized component instance
*/
public Command getOkCommand1 () {
if (okCommand1 == null) {
// write pre-init user code here
okCommand1 = new Command ("Ok", Command.OK, 0);
// write post-init user code here
}
return okCommand1;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc=" Generated Getter: okCommand ">
/**
* Returns an initiliazed instance of okCommand component.
* @return the initialized component instance
*/
public Command getOkCommand () {
if (okCommand == null) {
// write pre-init user code here
okCommand = new Command ("Ok", Command.OK, 0);
// write post-init user code here
}
return okCommand;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc=" Generated Getter: exitCommand ">
/**
* Returns an initiliazed instance of exitCommand component.
* @return the initialized component instance
*/
public Command getExitCommand () {
if (exitCommand == null) {
// write pre-init user code here
exitCommand = new Command ("Exit", Command.EXIT, 0);
// write post-init user code here
}
return exitCommand;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc=" Generated Getter: ServerList ">
/**
* Returns an initiliazed instance of ServerList component.
* @return the initialized component instance
*/
public Form getServerList () {
if (ServerList == null) {
// write pre-init user code here
ServerList = new Form ("", new Item[] { getChoiceGroup () });
ServerList.addCommand (getBackCommand2 ());
ServerList.addCommand (getOkCommand2 ());
ServerList.addCommand (getStart_searchCommand ());
ServerList.addCommand (getStop_searchCommand ());
ServerList.setCommandListener (this);
// write post-init user code here
}
return ServerList;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc=" Generated Getter: choiceGroup ">
/**
* Returns an initiliazed instance of choiceGroup component.
* @return the initialized component instance
*/
public ChoiceGroup getChoiceGroup () {
if (choiceGroup == null) {
// write pre-init user code here
choiceGroup = new ChoiceGroup ("Servers", Choice.MULTIPLE);
choiceGroup.setPreferredSize (-1, -1);
choiceGroup.setLayout (ImageItem.LAYOUT_CENTER | Item.LAYOUT_TOP | Item.LAYOUT_BOTTOM | Item.LAYOUT_VCENTER);
choiceGroup.setSelectedFlags (new boolean[] { });
// write post-init user code here
}
return choiceGroup;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc=" Generated Getter: backCommand2 ">
/**
* Returns an initiliazed instance of backCommand2 component.
* @return the initialized component instance
*/
public Command getBackCommand2 () {
if (backCommand2 == null) {
// write pre-init user code here
backCommand2 = new Command ("Back", Command.BACK, 0);
// write post-init user code here
}
return backCommand2;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc=" Generated Getter: okCommand2 ">
/**
* Returns an initiliazed instance of okCommand2 component.
* @return the initialized component instance
*/
public Command getOkCommand2 () {
if (okCommand2 == null) {
// write pre-init user code here
okCommand2 = new Command ("Ok", Command.OK, 0);
// write post-init user code here
//Object finder = new MyFinder(this);
MyFinder finder = new MyFinder(this);
finder.start();
}
return okCommand2;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc=" Generated Getter: SendSplash ">
/**
* Returns an initiliazed instance of SendSplash component.
* @return the initialized component instance
*/
public SplashScreen getSendSplash () {
if (SendSplash == null) {
// write pre-init user code here
SendSplash = new SplashScreen (getDisplay ());
SendSplash.setTitle ("");
SendSplash.setCommandListener (this);
SendSplash.setImage (getImage1 ());
SendSplash.setText ("Sending message");
SendSplash.setTimeout (2000);
// write post-init user code here
Thread t = new Thread(this);
t.start();
}
return SendSplash;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc=" Generated Getter: Send ">
/**
* Returns an initiliazed instance of Send component.
* @return the initialized component instance
*/
public Command getSend () {
if (Send == null) {
// write pre-init user code here
Send = new Command ("Send", Command.OK, 0);
// write post-init user code here
}
return Send;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc=" Generated Getter: image1 ">
/**
* Returns an initiliazed instance of image1 component.
* @return the initialized component instance
*/
public Image getImage1 () {
if (image1 == null) {
// write pre-init user code here
try {
image1 = Image.createImage ("/bluetooth_small.jpg");
} catch (java.io.IOException e) {
e.printStackTrace ();
}
// write post-init user code here
}
return image1;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc=" Generated Getter: start_searchCommand ">
/**
* Returns an initiliazed instance of start_searchCommand component.
* @return the initialized component instance
*/
public Command getStart_searchCommand () {
if (start_searchCommand == null) {
// write pre-init user code here
start_searchCommand = new Command ("Start BT s\u00F8gning", Command.ITEM, 0);
// write post-init user code here
}
return start_searchCommand;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc=" Generated Getter: stop_searchCommand ">
/**
* Returns an initiliazed instance of stop_searchCommand component.
* @return the initialized component instance
*/
public Command getStop_searchCommand () {
if (stop_searchCommand == null) {
// write pre-init user code here
stop_searchCommand = new Command ("Stop BT s\u00F8gning", Command.ITEM, 0);
// write post-init user code here
}
return stop_searchCommand;
}
//</editor-fold>
/**
* Returns a display instance.
* @return the display instance.
*/
public Display getDisplay () {
return Display.getDisplay(this);
}
/**
* Exits MIDlet.
*/
public void exitMIDlet() {
switchDisplayable (null, null);
destroyApp(true);
notifyDestroyed();
}
/**
* Called when MIDlet is started.
* Checks whether the MIDlet have been already started and initialize/starts or resumes the MIDlet.
*/
public void startApp() {
if (midletPaused) {
resumeMIDlet ();
} else {
initialize ();
startMIDlet ();
}
midletPaused = false;
}
/**
* Called when MIDlet is paused.
*/
public void pauseApp() {
midletPaused = true;
}
/**
* Called to signal the MIDlet to terminate.
* @param unconditional if true, then the MIDlet has to be unconditionally terminated and all resources has to be released.
*/
public void destroyApp(boolean unconditional) {
}
public void removeDevice(int i){
choiceGroup.delete(i);
}
public void stop_device_search(){
choiceGroup.deleteAll();
mainFinder.stop();
}
public void start_device_search(){
choiceGroup.deleteAll();
if(mainFinder.searching == false){
mainFinder.start();
}
}
public void addDevice(MyService ms){
String s = ms.getName() + ":" + ms.getAddress();
choiceGroup.append(s, null);
int count = choiceGroup.size();
System.out.println(count);
}
public void run() {
Vector urls = new Vector();
// Synchronize so reconcile() won't run
// at the same time.
synchronized(mainFinder) {
int n = choiceGroup.size();
boolean[] flags = new boolean[n];
choiceGroup.getSelectedFlags(flags);
for (int i = 0; i < n; i++) {
if (flags[i] == true) {
String url = mainFinder.getURL(i);
urls.addElement(url);
}
}
}
for (int i = 0; i < urls.size(); i++) {
String url = (String)urls.elementAt(i);
try { runURL(url); }
catch (IOException ioe) {
System.out.println("BlueChewMIDlet.run(): " + ioe);
}
}
}
private void runURL(String url) throws IOException {
StreamConnection sc = null;
DataOutputStream dataOut = null;
try {
sc = (StreamConnection)
Connector.open(url);
dataOut = new DataOutputStream(
sc.openOutputStream());
LocalDevice bt = LocalDevice.getLocalDevice();
String from = bt.getFriendlyName() + ":" +
bt.getBluetoothAddress();
dataOut.writeUTF(from);
dataOut.writeUTF(textField.getString());
}
finally {
try { if (dataOut != null) dataOut.close(); }
catch (IOException ioe) {}
try { if (sc != null) sc.close(); }
catch (IOException ioe) {}
}
}
}
Finder:
import java.io.IOException;
import java.util.Vector;
import javax.bluetooth.*;
public class MyFinder implements DiscoveryListener {
private MainMidlet midlet;
Vector v_services, v_new_services;
boolean searching, trucking;
int service_search_remaining;
// initialiserer my_finder værdierne.
public MyFinder(MainMidlet Tmidlet) {
midlet = Tmidlet;
v_services = new Vector();
v_new_services = new Vector();
service_search_remaining = 0;
searching = false;
trucking = true;
}
public void start() {
try {
LocalDevice ld = LocalDevice.getLocalDevice();
DiscoveryAgent da = ld.getDiscoveryAgent();
boolean success = da.startInquiry(DiscoveryAgent.GIAC, this);
searching = true;
}
// Checker om inquiriet kan udføres i den nuværende state. Hvis ikke
// dette er muligt, vil en exception blive genereret.
catch (BluetoothStateException bse)
{
System.out.println("start() threw" + bse);
}
}
public void stop(){
try{
trucking = false;
LocalDevice ld = LocalDevice.getLocalDevice();
DiscoveryAgent da = ld.getDiscoveryAgent();
da.cancelInquiry(this);
//searching = false;
}
catch(BluetoothStateException bse){
System.out.println("stop() threw" + bse);
}
}
public String getURL(int i) {
MyService bcs = (MyService)v_services.elementAt(i);
String url = bcs.getURL();
return url;
}
public void deviceDiscovered(RemoteDevice remotedevice, DeviceClass deviceclass) {
try{
LocalDevice ld = LocalDevice.getLocalDevice();
DiscoveryAgent da = ld.getDiscoveryAgent();
UUID[] uuidset = { MyService.BLUECHEW_UUID};
service_search_remaining++;
da.searchServices(null, uuidset, remotedevice, this);
}
catch (IOException ioe){
System.out.println("DeviceDiscovered(): " + ioe);
}
catch (Throwable t) {
System.out.println("DeviceDiscovered(): " + t);
searching = false;
}
}
public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
for (int i = 0; i< servRecord.length;i++){
try{
RemoteDevice rd = servRecord[i].getHostDevice();
String name = rd.getFriendlyName(false);
String address = rd.getBluetoothAddress();
String URL = servRecord[i].getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
MyService bcs = new MyService(name, address, URL);
v_new_services.addElement(bcs);
}
catch (BluetoothStateException bse){
System.out.println("ServiceDiscovered(): " + bse);
}
catch (IOException ioe) {
System.out.println("ServiceDiscovered(): " + ioe);
}
}
System.out.println("services" + v_services.size());
}
public void serviceSearchCompleted(int TransID, int respCode) {
service_search_remaining --;
if( searching==false && service_search_remaining==0) {
reconcile();
try{ Thread.sleep(1000); }
catch(InterruptedException ie){}
if(trucking == true)
start();
}
}
// opdaterer v_services ved at fjerne elementer der ikke er i v_new_services.
public synchronized void reconcile() {
for(int i=0;i<v_services.size();i++){
MyService bcs = (MyService)v_services.elementAt(i);
if(contains(v_new_services, bcs) == false) {
v_services.removeElement(bcs);
midlet.removeDevice(i);
}
}
System.out.println("Test remove v_service " + v_services.size());
for(int i=0;i<v_new_services.size();i++){
MyService bcs = (MyService)v_new_services.elementAt(i);
if((contains(v_services, bcs)) == false){
v_services.addElement(bcs);
midlet.addDevice(bcs);
}
}
System.out.println("Test remove v_service " + v_services.size());
v_new_services.removeAllElements();
}
private boolean contains(Vector v, Object o){
boolean contained = false;
for(int i=0;i< v.size(); i++){
Object oc = v.elementAt(i);
if(oc.equals(o)){
contained = true;
}
}
return contained;
}
public void inquiryCompleted(int arg0) {
searching = false;
}
}