Получение списка файлов удаленного устройства через BT в Java / Android - PullRequest
0 голосов
/ 02 сентября 2011

Я пытаюсь получить список папок удаленного устройства, используя OBEX;Я пытаюсь подключиться, используя

 String btUrl=btgoep://"+mac_address+":10;authenticate=false;encrypt=false;master=false" 

, но получаю Не поддерживается пока ошибка при звонке

ClientSession conn = (ClientSession) Connector.open(btURL);

Кто-нибудь может мне помочь?

Ответы [ 2 ]

0 голосов
/ 04 марта 2018

Попробуйте это.

private void GetFileNamesViaBTFTP(UUID UUID3)
{
    try
    {

        mBtSocket = mBtDevice.createInsecureRfcommSocketToServiceRecord(UUID3);
    }
    catch (Exception e)
    {

        //e.printStackTrace();
    }

    Thread thread=new Thread(new Runnable() {
            public void run()
            {
                UUID uuid=UUID.fromString("F9EC7BC4-953C-11D2-984E-525400DC9E09");
                ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
                bb.putLong(uuid.getMostSignificantBits());
                bb.putLong(uuid.getLeastSignificantBits());
                byte [] bytes=bb.array();
                Operation putOperation=null;
                Operation getOperation=null;
                //ArrayUtils.reverse(bytes);
                try
                {
                    // 소켓을 연결한다
                    mBtSocket.connect();
                    mSession = new ClientSession((ObexTransport)(mTransport = new BluetoothObexTransport(mBtSocket)));

                    HeaderSet headerset = new HeaderSet();
                    headerset.setHeader(HeaderSet.TARGET, bytes);

                    headerset = mSession.connect(headerset);

                    if (headerset.getResponseCode() == ResponseCodes.OBEX_HTTP_OK)
                    {
                        mConnected = true;
                    }
                    else
                    {
                        mSession.disconnect(headerset);
                    }
                    // Send a file with meta data to the server
                    final byte filebytes[] = "[CLIENT] Hello..".getBytes();
                    final HeaderSet hs = new HeaderSet();
                    hs.setHeader(HeaderSet.NAME, "test.txt");
                    hs.setHeader(HeaderSet.TYPE, "text/plain");
                    hs.setHeader(HeaderSet.LENGTH, new Long((long)filebytes.length));

                    putOperation = mSession.put(hs);

                    mOutput = putOperation.openOutputStream();
                    mOutput.write(filebytes);
                    mOutput.close();
                    putOperation.close();
                    //In order to go the desired folder the OBEX SETPATH command is 
                    //being used 
                    //Prepare the header for the SETPATH command
                    HeaderSet header = new HeaderSet(); 
                    //folder_name is set to the name of the desired folder 
                    //if left blank the root folder will be used 
                    //header.setHeader(HeaderSet.NAME, ""); 
                    //Send the SETPATH command 
                    /*result =*/ mSession.setPath(header, false, false); 
                    final HeaderSet geths = new HeaderSet();
                    //geths.setHeader(HeaderSet.NAME, null);
                    geths.setHeader(HeaderSet.TYPE, "x-obex/folder-listing");
                    //hs.setHeader(HeaderSet.LENGTH, new Long((long)filebytes.length));

                    getOperation = mSession.get(geths);
                    InputStreamReader din = new 
                        InputStreamReader(getOperation.openInputStream(), "UTF-8"); 

                    BufferedReader bufferedReader = new BufferedReader(din); 
                    String tmp2=new String();
                    String line = bufferedReader.readLine(); 
                    while (line != null)
                    { 
                        tmp2 += line;//System.out.println(line); 
                        line = bufferedReader.readLine(); 
                    } 
                    bufferedReader.close(); 

                    getOperation.close();  
                    /*
                     mInput=getOperation.openInputStream();
                     // Retrieve the length of the object being sent back
                     int length = (int) getOperation.getLength();
                     // Create space for the object
                     byte[] obj = new byte[length];
                     // Get the object from the input stream
                     DataInputStream in = getOperation.openDataInputStream();
                     in.read(obj);

                     // End the transaction
                     in.close();
                     */
                    final String ftmp=tmp2;
                    runOnUiThread(new Runnable(){
                            @Override
                            public void run()
                            {
                                //String s=new String(ftmp, "UTF-16");
                                deviceTextEdit.setText(ftmp);
                            }
                        });
                    Xml xml;
                }
                catch (Exception e)
                {
                    //e.printStackTrace();
                }
                finally
                {
                    try
                    {
                        mOutput.close();
                        putOperation.close();
                        mSession.disconnect(null);
                    }
                    catch (IOException e)
                    {}
                    //updateStatus("[CLIENT] Connection Closed");
                }

            }
        });
    thread.start();
}

Теперь ваша задача - проанализировать XML-данные из списка obexfolder.

0 голосов
/ 05 мая 2012

Порт может быть неправильным. Вы должны получить адреса подключения через сервис поиска в DiscoveryListener. В jsr82 это выглядит так:

    private final UUID L2CAP_UUID = new UUID(0x1106);
    public String getOBEXURL(RemoteDevice dev) {
        DiscoveryAgent discoveryAgent = null;
        try {
            LocalDevice localDevice = LocalDevice.getLocalDevice();
            discoveryAgent = localDevice.getDiscoveryAgent();
        }
        catch (Exception e) {
            return null;
        }

        try {
            discoveryAgent.searchServices(null, new UUID[]{L2CAP_UUID}, dev, this);
        } catch (Exception e) {
            return null;
        }

        synchronized (this) {
            try { wait(); }
            catch (Exception e) {}
        }

        switch (respCode) {
            case SERVICE_SEARCH_DEVICE_NOT_REACHABLE:
                ps.println("Remote device could not be reached");
                break;
            case SERVICE_SEARCH_ERROR:
                ps.println("The service search was terminated with error");
                break;
            case SERVICE_SEARCH_NO_RECORDS:
                ps.println("No services found on device");
                break;
            case SERVICE_SEARCH_TERMINATED:
                ps.println("The service search has been canceled by the application and did not complete");
                break;
        }

        return obexURL;
    }

    public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
        obexURL = servRecord[0].getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
    }

    public void serviceSearchCompleted(int transID, int respCode) {
        this.respCode = respCode;
        synchronized (this) { notify(); }
    }
...