Boa Tarde!
Sou novo na programacao J2ME e gostaria de sabe se tambem seria possivel
trabalhar com varias classes aproveitando a mesma ideia do JAVA desktop.
enfim Estou tentando desenvolver um programa baseado nos exemplos de codigos que estao abaixo
voltado para o bluetooth. O objetivo é mandar um String(sinal d comando para o microcontrolador ArduinoBT) e estou com duvina na hora de chamar a classe
BluetoothConnectionClient ao pressionar na opcao abrir
obrigado a todos que tentaram me ajudar e desculpe pelos erros d portugues mas estou usando teclado US!
classe principal
// gostaria de saber como q eu faco a chamada da classe BluetoothConnectionClient quando eu pressionar os botoes abrir e desligar
package src;
import java.io.IOException;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.ItemStateListener;
import javax.microedition.lcdui.Choice;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.ImageItem;
import javax.microedition.lcdui.List;
import src.BluetoothConnectionClient;
public class Test extends MIDlet implements CommandListener,ItemStateListener {
private Display display;
private List opcoesItens;
private Command sair;
private Command voltar;
private Command fechar;
private Command abrir;
private BluetoothConnectionClient bluetoothConnectionClient;
public Test() {
System.out.println("entrou --- ");
opcoesItens=new List("Lista de Tipos Itens", Choice.IMPLICIT);
sair= new Command("Sair",Command.EXIT,0);
voltar=new Command("Voltar",Command.OK,1);
fechar=new Command("Fechar",Command.OK,1);
abrir=new Command("Abrir",Command.OK,1);
}
protected void startApp(){
System.out.println("entrou");
display= Display.getDisplay(this);
opcoesItens.append("ImageItem",null);
opcoesItens.addCommand(sair);
opcoesItens.addCommand(voltar);
opcoesItens.addCommand(abrir);
opcoesItens.addCommand(fechar);
opcoesItens.setCommandListener(this);
display.setCurrent(opcoesItens);
this.exemploImagemItem();
System.out.println("fim");
}
public void exemploImagemItem(){
System.out.println("entrou no metodo imagem item");
Form form =new Form("ImagemItem");
try{
Image cima=Image.createImage("/src/imagem.png");// caminho do diretorio da imagem
form.append(new ImageItem("Center",cima,ImageItem.LAYOUT_CENTER,null));
}catch(IOException ex){
ex.printStackTrace();
form.append("Erro ao abrir Imagens");
}
form.addCommand(sair);
form.addCommand(voltar);
form.addCommand(abrir);
form.addCommand(fechar);
form.setCommandListener(this);
display.setCurrent(form);
}
protected void pauseApp() {
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
notifyDestroyed();
}
public void itemStateChanged(Item arg0) {
// TODO Auto-generated method stub
}
public void commandAction(Command arg0, Displayable arg1) {
if (arg0==sair){
try{
destroyApp(true);
}catch (Exception e){
e.printStackTrace();
}
}else if(arg0==voltar){
display.setCurrent(opcoesItens);
}else if(arg0==fechar){
display.setCurrent(opcoesItens);
}else if(arg0==abrir){
display.setCurrent(opcoesItens);
}
}
}
//classe do cliente conexao bluetooth
package src;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Vector;
import javax.bluetooth.BluetoothStateException;
import javax.bluetooth.DataElement;
import javax.bluetooth.DeviceClass;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;
import javax.bluetooth.UUID;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
/**
* This class is responsible for establishing the bluetooth connection acting as
* a client. It is also responsible for searching for servers in the network.
*
*/
public class BluetoothConnectionClient extends BluetoothConnection implements // esta linha chama a classe BluetoothConnection
DiscoveryListener {
// Stores the servers address.
private Hashtable serverAddress;
// Stores the names of the opponents.
private Vector opponentNames;
// Bluetooth transaction ID of the actual service search.
private int actualTransID = 0;
// 'True' if the search was canceled.
private boolean searchCanceled;
// Actual device under service search.
private int actualDevice;
//The devices discovered during the inquiry.
private RemoteDevice[] devicesDiscovered;
/**
* Creates a BluetoothConnectionClient.
*/
public BluetoothConnectionClient() {
System.out.println("chamou a classe bluetoothConnectionClient");
}
/**
* Searches for new servers.
*
* @return A vector containing strings with the player names of the servers
* found.
* @throws BluetoothStateException
* if a bluetooth error is raised.
* @throws SearchCanceledException
* if the search is canceled before finishing.
*/
public Vector search() throws BluetoothStateException,
SearchCanceledException {
opponentNames = new Vector();
serverAddress = new Hashtable();
localDevice = LocalDevice.getLocalDevice();
DiscoveryAgent discoveryAgent = localDevice.getDiscoveryAgent();
discoveryAgent.startInquiry(DiscoveryAgent.GIAC, this);
synchronized (this) {
try {
this.wait();
} catch (InterruptedException ignored) {
}
}
if (searchCanceled) {
throw new SearchCanceledException();
}
return opponentNames;
}
/**
* deviceDiscovered method called when a device is discovered in the inquiry.
* See javax.bluetooth.DiscoveryListener#deviceDiscovered()
*/
public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
}
/**
* callBack method called when a server is found.
*
* @param transID
* The transaction ID of the service search that is posting the
* result
* @param servRecord
* a list of services found during the search request
*/
public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
for (int i = 0; i < servRecord.length; i++) {
DataElement data = servRecord[i].getAttributeValue(PLAYER_NAME_KEY);
opponentNames.addElement(data.getValue());
//Record the server address.
serverAddress.put(data.getValue(), servRecord[i].getConnectionURL(
0, false));
}
}
/**
* serviceSearchCompleted method called when a service search is completed or was
* terminated because an error occurred or was canceled.
*
* @param transID
* the transaction ID identifying the request which initiated the
* service search
* @param respCode
* the response code that indicates the status of the transaction
*
*/
public void serviceSearchCompleted(int transID, int respCode) {
if (++actualDevice >= devicesDiscovered.length) {
synchronized (this) {
this.notify();
}
} else if (respCode == SERVICE_SEARCH_TERMINATED) {
searchCanceled = true;
synchronized (this) {
this.notify();
}
} else {
searchServiceOnDevice(actualDevice);
}
}
/**
* inquiryCompleted method called when an inquiry is completed.
*
* @param discType
* the type of request that was completed; either
* INQUIRY_COMPLETED, INQUIRY_TERMINATED, or INQUIRY_ERROR
*/
public void inquiryCompleted(int discType) {
if (discType == INQUIRY_COMPLETED) {
DiscoveryAgent discoveryAgent = localDevice.getDiscoveryAgent();
devicesDiscovered = discoveryAgent
.retrieveDevices(DiscoveryAgent.CACHED);
if (devicesDiscovered != null) {
actualDevice = 0;
searchServiceOnDevice(actualDevice);
} else {
synchronized (this) {
this.notify();
}
}
} else if (discType == INQUIRY_TERMINATED) {
searchCanceled = true;
synchronized (this) {
this.notify();
}
}
}
// Searches for a service in an specific device.
private void searchServiceOnDevice(int device) {
DiscoveryAgent discoveryAgent = localDevice.getDiscoveryAgent();
try {
actualTransID = discoveryAgent
.searchServices(new int[] { PLAYER_NAME_KEY },
new UUID[] { RFCOMM_UUID },
devicesDiscovered[device], this);
} catch (BluetoothStateException e) {
e.printStackTrace();
synchronized (this) {
this.notify();
}
}
}
/**
* Run the client mode and sends a success message when the
* connection is established.
*
* @see java.lang.Runnable#run()
*/
public void run() {
try {
conn = (StreamConnection) Connector.open((String) serverAddress
.get(playerName));
fireConnectionEstablishedEvent();
} catch (IOException e) {
fireConnectionErrorEvent(e);
}
}
/**
* Stops the server.
*/
public void stop() {
if (conn == null && localDevice != null) {
DiscoveryAgent discoveryAgent = localDevice.getDiscoveryAgent();
discoveryAgent.cancelInquiry(this);
discoveryAgent.cancelServiceSearch(actualTransID);
} else {
try {
conn.close();
} catch (Exception ignored) {
}
}
}
}
// codigo de conexao
package src;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.UUID;
import javax.microedition.io.StreamConnection;
/**
* This class is responsible for establishing the bluetooth connection. It has
* the common code between a bluetooth client and a server, and must be extended
* with the properly behaviour.
*
*/
public abstract class BluetoothConnection implements Runnable {
/**
* The object that represents the local device.
*/
protected LocalDevice localDevice;
/**
* The name of the player.
*/
protected String playerName;
/**
* Attribute value that will be retrieved on services which have the RFCOMM_UUID.
*/
public static final int PLAYER_NAME_KEY = 51;
/**
* Shared UUID by server and client.
*/
protected static final UUID RFCOMM_UUID = new UUID(0x7C3434CC);
/**
* The object that represents the connection.
*/
protected StreamConnection conn;
/**
* The Server URL.
*/
protected static String serverUrl = "btspp://localhost:"
+ RFCOMM_UUID.toString() + ";name=tictactoe;authorize=false";
/**
* Thread of the connection.
*/
private Thread thread;
/**
* Listener of the connection.
*/
//private ConnectionListener listener;
/**
* Retrieves a DataInputStream
*
* @return The stream used to receive data from another device.
* @throws IOException
* if an I/O error is raised.
*/
public DataInputStream getDataInputStream() throws IOException {
return conn.openDataInputStream();
}
/**
* Retrieves the DataOutputStream
*
* @return The stream used to send data to another device.
* @throws IOException
* if an I/O error is raised.
*/
public DataOutputStream getDataOutputStream() throws IOException {
return conn.openDataOutputStream();
}
/**
* Starts the process of establishing a bluetooth connection.
*
* @param playerName
* A string containing the name of this player.
* @param listener
* The object that will receive connection events.
*/
/*
public void start(String playerName, ConnectionListener listener) {
this.listener = listener;
this.playerName = playerName;
thread = new Thread(this);
thread.start();
} */
/**
* Stops the connection.
*/
public abstract void stop();
/**
* Sends an event to the listener informing that the connection was
* established.
*/
protected void fireConnectionEstablishedEvent() {
// listener.connectionEstablished();
}
/**
* Sends an event to the listener informing if a connection error happens.
*/
protected void fireConnectionErrorEvent(Exception e) {
// listener.connectionError(e);
}
}