5

我想在 J2ME 应用程序中使用蓝牙在打印机上打印一些数据。我可以完美地打印数据,但完成打印功能后,打印机会自动关闭。我的意思是与设备的连接丢失,当我关闭应用程序时,它会自动打开。我不明白为什么打印一次后连接丢失。如果有人有任何想法,请帮助我。谢谢。

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mobifin;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import com.sun.lwuit.Command;
import com.sun.lwuit.Component;
import com.sun.lwuit.Dialog;
import com.sun.lwuit.Display;
import com.sun.lwuit.Font;
import com.sun.lwuit.Form;
import com.sun.lwuit.Label;
import com.sun.lwuit.List;
import com.sun.lwuit.TextArea;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.list.ListCellRenderer;
import com.sun.lwuit.plaf.Border;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.Vector;
import javax.bluetooth.BluetoothStateException;
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;

/**
 *
 * @author riddhi.barbhaya
 */
public class PrintScreen extends Form implements ActionListener, ListCellRenderer, DiscoveryListener {

    String title;
    Form form, info;
    MobifinMidlet parent;
    Command cmd_exit = new Command("Exit", 1);
    Command cmd_Print = new Command("Print", 1);
    LocalDevice bluetooth;
    String blueStr;
    List activeDevice = new List();
    List activeServices = new List();
    DiscoveryAgent disAgent;
    Vector deviceFound;
    private ServiceRecord[] servicesFound = null;
    private boolean Dflag;
    private String connectionURL;
    private boolean srviceDisFlag;
    private DataInputStream ioDataInputStream;
    StreamConnection sc;
//    private Command cmdinfo, select;
    Display display;
    Label lbl = new Label("Searching for devices...");
    Label l1;
    int device = 0;
    String msg;

    public PrintScreen(MobifinMidlet parent, String title, String message) {
        this.title = title;
        this.setTitle(title);
        this.parent = parent;
        this.msg = message;

        this.addComponent(lbl);

        activeDevice.setListCellRenderer(this);

        this.addCommandListener(this);
        this.addComponent(activeDevice);
        this.addComponent(activeServices);


        try {
            bluetooth = LocalDevice.getLocalDevice();
        } catch (BluetoothStateException ex) {
            ex.printStackTrace();
        }
        blueStr = bluetooth.getFriendlyName();
        disAgent = bluetooth.getDiscoveryAgent();
        deviceFound = new Vector();
        try {
            disAgent.startInquiry(DiscoveryAgent.GIAC, this);
        } catch (BluetoothStateException ex) {
            ex.printStackTrace();
            showMessageDialog("Exception", "Exception in start app");
        }
        if (Dflag) {
            disAgent.cancelInquiry(this);
        }

    }

    public void dosearchServies(RemoteDevice device) {
        int[] attributes = {0x100, 0x101, 0x102};
        UUID[] uuids;
        UUID RFCOMM_UUID = new UUID(0x1101); // RFCOMM service
        uuids = new UUID[1];
        uuids[0] = RFCOMM_UUID;
        disAgent = bluetooth.getDiscoveryAgent();
        try {
            disAgent.searchServices(null, uuids, device, this);
        } catch (Exception e) {
            e.printStackTrace();
//            showMessageDialog("Error", "Error");
        }
    }

    public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
        try {
            String deviceaddress = null;
            try {
                deviceaddress = btDevice.getBluetoothAddress();//btDevice.getFriendlyName(true);
                System.out.println("Device Address is>>" + deviceaddress);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            String str;
            str = btDevice.getFriendlyName(true);
            activeDevice.addItem(str);
            deviceFound.addElement(btDevice);
            System.out.println("----");
            //   dosearchServies(btDevice);
        } catch (IOException ex) {
            showMessageDialog("Exception", "Exception in device discovered");
            ex.printStackTrace();
        }
    }

    public void showMessageDialog(String title, String message) {
        Dialog dialog = new Dialog("Alert");
        dialog.setScrollable(false);
        dialog.setIsScrollVisible(false);
        dialog.setTimeout(2000); // set timeout milliseconds
        dialog.setPreferredH(100);
        dialog.setPreferredW(100);

        TextArea textarea = new TextArea(2, 30, TextArea.UNEDITABLE) {

            public int getRows() {
                if (isGrowByContent()) {
                    return getLines();
                } else {
                    return super.getRows();
                }
            }
        };
        textarea.getStyle().setBorder(Border.createLineBorder(0));
        textarea.getStyle().setFont(Font.createSystemFont(Font.FACE_SYSTEM, Font.STYLE_PLAIN, Font.SIZE_MEDIUM));
        textarea.getStyle().setBorder(Border.createLineBorder(0));
        textarea.setGrowByContent(true);
        textarea.setFocusable(false);
        textarea.setIsScrollVisible(false);
        textarea.setText(message);

        dialog.setTitle(title);

        dialog.addComponent(textarea);
        dialog.show(0, 120, 10, 10, true);
    }

    public void actionPerformed(ActionEvent ae) {
        Command c = ae.getCommand();
        String str;
        if (c.equals(cmd_exit)) {
            MainMenu mainmenu = new MainMenu("Menu", parent);
            mainmenu.show();
        }
        else if (c.equals(cmd_Print)) {
            try {
                device = activeDevice.getSelectedIndex();
                dosearchServies((RemoteDevice) deviceFound.elementAt(device));
            } catch (Exception e) {
                showMessageDialog("Exception", "Exception in command print");
                e.printStackTrace();
            }

        }

    }

    private synchronized int a(int p) {
        int i = p;
        notifyAll();
        return i;
    }

    public Component getListCellRendererComponent(List list, Object value, int i, boolean isSelected) {
        Label l = new Label(value.toString());
        if (isSelected == true) {
            l.setFocus(true);
            l.setGap(0);
            l.getStyle().setFont(Font.createSystemFont(Font.FACE_SYSTEM, Font.STYLE_BOLD, Font.SIZE_MEDIUM));
        } else {
            l.setFocus(false);
            l.setGap(0);
            l.getStyle().setFont(Font.createSystemFont(Font.FACE_SYSTEM, Font.STYLE_BOLD, Font.SIZE_MEDIUM));
            return l;
        }
        return l;
    }

    public Component getListFocusComponent(List list) {
        return null;
    }

    public void serviceSearchCompleted(int i, int i1) {
        switch (i) {
            case DiscoveryListener.SERVICE_SEARCH_COMPLETED:
                srviceDisFlag = true;
                break;
            case DiscoveryListener.SERVICE_SEARCH_DEVICE_NOT_REACHABLE:
                break;
            case DiscoveryListener.SERVICE_SEARCH_ERROR:
                break;
            case DiscoveryListener.SERVICE_SEARCH_NO_RECORDS:
                break;
            case DiscoveryListener.SERVICE_SEARCH_TERMINATED:
                break;
        }
        this.setTitle("Select Device For printing Selection");


        int service = activeServices.getSelectedIndex();
        connectionURL = servicesFound[service].getConnectionURL(0, false);
        printmethod(connectionURL);

    }

    public void inquiryCompleted(int discType) {
        if (discType != DiscoveryListener.INQUIRY_COMPLETED) {

        } else {
            this.removeComponent(lbl);
            this.addCommand(cmd_Print);
            this.addCommand(cmd_exit);

            revalidate();
        }
        Dflag = true;

        try {
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void printmethod(String connection_u) {
        try {
            try {
                StreamConnection connection = (StreamConnection) Connector.open(connection_u);
                byte[] buffer = new byte[100];
                InputStream is = connection.openInputStream();
                OutputStream os = connection.openOutputStream();
                OutputStreamWriter ow = new OutputStreamWriter(os, "US-ASCII");
                InputStreamReader ir = new InputStreamReader(is, "US-ASCII");
                ow.write(msg);
                ow.flush();
                ow.close();
                connection.close();
                showMessageDialog("", "Please Wait Printing is in Progress");

                MainMenu menu=new MainMenu("Menu", parent);
                menu.show();


                System.out.println("-4-");
                System.out.println("-5-");
            } catch (Exception e) {
                System.out.println("Error " + e);
                showMessageDialog("Exception", e.toString());
            }

            int i2 = 0;
            System.out.println("-0-");

    }

    public void servicesDiscovered(int i, ServiceRecord[] srs) {
        servicesFound = srs;
    }

    public void addText(String text) {
        TextArea t = new TextArea(2, 30, TextArea.UNEDITABLE) {

            public int getRows() {
                if (isGrowByContent()) {
                    return getLines();
                } else {
                    return super.getRows();
                }
            }
        };
        t.getStyle().setBorder(Border.createLineBorder(0));
        t.setGrowByContent(true);
        t.setText(text);
        this.addComponent(t);
    }
}
4

0 回答 0