java-me蓝牙文件发送

时间:2010-08-23 19:38:08

标签: java-me bluetooth

我有两部手机,我想在这两部手机之间交换文件。 Device A调用java app,它将扫描范围内可用的蓝牙设备,将它们显示在列表中,用户可以选择一个设备并点击发送。

我写了下面的代码,它不能正常工作。

package hello;

import java.io.*;
import java.util.Vector;
import javax.bluetooth.*;
import javax.microedition.io.*;
import javax.microedition.io.StreamConnection.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
import javax.obex.*;
import javax.obex.ResponseCodes;

public class MyMidlet extends MIDlet  implements CommandListener, DiscoveryListener
{

    public Command cmdSend;
    public Command cmdScan;
    public TextBox myText;
    public List devList;
    public Form myForm;
    private LocalDevice localDev;
    private DiscoveryAgent dAgent;
    private ServiceRecord servRecord;
    private Vector myVector;
        private ClientSession connection = null;
    private String url = null;
    private Operation op = null;
    private boolean cancelInvoked = false;

    public MyMidlet()
    {
        cmdSend = new Command("Send", 2, 0);
        cmdScan = new Command("Scan", 5, 0);
    }

    public void startApp()
    {
        if(myText == null)
        {
        myText = new TextBox("Dummy Text", "Hello", 10, 0);
        myText.addCommand(cmdScan);
        myText.setCommandListener(this);
         Display.getDisplay(this).setCurrent(myText);
        }
    }

    public void pauseApp(){}
    public void destroyApp(boolean flag)  { }

    public void commandAction(Command command, Displayable displayable)
    {
        if(command == cmdScan)
        {
            if(myForm == null) { myForm = new Form("Scanning"); }
            else {
                for(int i = 0; i < myForm.size(); i++)  myForm.delete(i);

               }
            myForm.append("Scanning for bluetooth devices..");
            Display.getDisplay(this).setCurrent(myForm);
            if(devList == null)
            {
                devList = new List("Devices", 3);
                devList.addCommand(cmdSend);
                devList.setCommandListener(this);
            } else
            {
                for(int j = 0; j < devList.size(); j++)  devList.delete(j);

            }
            if(myVector == null) myVector = new Vector();
            else  myVector.removeAllElements();
            try
            {
                if(localDev == null)
                {
                    localDev = LocalDevice.getLocalDevice();
                    localDev.setDiscoverable(0x9e8b33);
                    dAgent = localDev.getDiscoveryAgent();
                }

                dAgent.startInquiry(0x9e8b33, this);
            }
            catch(BluetoothStateException bluetoothstateexception)
            {
                myForm.append("Please check your bluetooth is turn-on");
            }
        }
        if(command == cmdSend)
        {
            myForm.setTitle("Sending");
            for(int k = 0; k < myForm.size(); k++)  myForm.delete(k);

            myForm.append("Sending application..");
            Display.getDisplay(this).setCurrent(myForm);
            try
            {
                RemoteDevice remotedevice = (RemoteDevice)myVector.elementAt(devList.getSelectedIndex());
                dAgent.searchServices(null, new UUID[] {new UUID(4358L)}, remotedevice, this);
                return;
            }
            catch(BluetoothStateException bluetoothstateexception1)
            {
                myForm.append("could not open bluetooth: " + bluetoothstateexception1.toString());
            }
        }
    }

    public void deviceDiscovered(RemoteDevice remotedevice, DeviceClass deviceclass)
    {
        try
        {
           devList.append(remotedevice.getFriendlyName(false), null);
        }
        catch(IOException _ex)
        {
            devList.append(remotedevice.getBluetoothAddress(), null);
        }
        myVector.addElement(remotedevice);
    }

    public void servicesDiscovered(int i, ServiceRecord aservicerecord[])
    {
        servRecord = aservicerecord[0];
    }

    public void serviceSearchCompleted(int i, int j)
    {
        if(j != 1) myForm.append("service search not completed: " + j);
        try
        {
            byte[] fileContent = "Raxit Sheth -98922 38248".getBytes();
            String s=servRecord.getConnectionURL(0, false);
            myForm.append("Debug 0");
            connection = (ClientSession) Connector.open(s);
            myForm.append("Debug1");
            HeaderSet headerSet = connection.connect(null);

            myForm.append("Debug1.1");
            headerSet.setHeader(HeaderSet.NAME, "a.txt");
            headerSet.setHeader(HeaderSet.TYPE, "text/plain");
            headerSet.setHeader(HeaderSet.LENGTH, new Long(fileContent.length));
            myForm.append("Debug1.2");
            //op = connection.put(headerSet); throwing java.lang.IllegalArgument.Exception
            op = connection.put(null);
            myForm.append("Debug1.2.1");
            op.sendHeaders(headerSet);
            myForm.append("Debug1.3");
            OutputStream out = op.openOutputStream();
            myForm.append("Debug2");
            //sending data
            myForm.append("Debug3");
            out.write(fileContent);
            myForm.append("Debug4");
            //int responseCode = op.getResponseCode();
            //myForm.append("resp code="+responseCode);

            out.close();
            op.close();
            connection.close();
            myForm.append("Done");
            //i was expecting this will send  a.txt file with content Raxit Sheth -98922 38248
            //to remote device's inbox/gallery/bluetooth folder
        }
        catch(Exception ex) {  myForm.append(ex.toString());   }
    }

    public void inquiryCompleted(int i)
    {
        Display.getDisplay(this).setCurrent(devList);
    }  
}

1 个答案:

答案 0 :(得分:0)

您的问题几乎肯定是您正在使用commandAction()方法开始蓝牙扫描。这是一个系统生命周期方法,需要快速返回。尝试在此线程中执行阻塞操作(例如蓝牙扫描)可能会占用手机需要执行其他操作的资源,例如实际扫描!

重构以便在新线程中执行扫描,然后重试。