2017-07-31 7 views
0

私はBluetoothを使用することに慣れていません。PC(Java)とAndroidの間のBluetooth転送が遅い

StackOverflow(私が今見つけることができない)に関するいくつかの議論を参照すると、Bluetoothスマートフォンに文字列を送信する小さなPCサーバーを作りました。

問題は極端に遅い転送です。

ACLineStatusのような文字列の場合:オンライン

彼らはリアルタイムの情報については、6550ミリ秒を提供しています。 6452

D/PROVA:IL dispositivo E:デスクトップU1VI1GB

D/PROVA:ACLineStatus:オンライン

をログにコードを実行する

E /時間を示すように

どのように転送速度を上げることができますか?

ここ(PC上)サーバーのコードがある

package hello; 
import java.io.BufferedReader; 
import java.io.BufferedWriter; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.OutputStream; 
import java.io.OutputStreamWriter; 
import java.io.PrintWriter; 
import javax.bluetooth.*; 
import javax.microedition.io.*; 
/** 
* Class that implements an SPP Server which accepts single line of 
* message from an SPP client and sends a single line of response to the client. 
*/ 

    //start server 
    private void startServer() throws IOException { 

     //Create a UUID for SPP 
     UUID uuid = new UUID("1101", true); 
     //Create the servicve url 
     String connectionString = "btspp://localhost:" + uuid + ";name=Sample SPP Server"; 

     //open server url 
     StreamConnectionNotifier streamConnNotifier = (StreamConnectionNotifier) Connector.open(connectionString); 

     //Wait for client connection 
     System.out.println("\nServer Started. Waiting for clients to connect..."); 
     StreamConnection connection = streamConnNotifier.acceptAndOpen(); 

     RemoteDevice dev = RemoteDevice.getRemoteDevice(connection); 
     System.out.println("Remote device address: " + dev.getBluetoothAddress()); 
     System.out.println("Remote device name: " + dev.getFriendlyName(true)); 

     //read string from spp client 
     /* InputStream inStream=connection.openInputStream(); 
     BufferedReader bReader=new BufferedReader(new InputStreamReader(inStream)); 
     String lineRead=bReader.readLine(); 
     System.out.println(lineRead);*/ 

     //send response to spp client 
     OutputStream outStream = connection.openOutputStream(); 
     PrintWriter pWriter = new PrintWriter(new OutputStreamWriter(outStream)); 
     pWriter.write(SingletonBatteryStatus.getInstance().getBattery() + "\n"); 
     pWriter.flush(); 
     pWriter.close(); 

     streamConnNotifier.close(); 
    } 


    public void run() { 

     //display local device address and name 
     LocalDevice localDevice = null; 
     try { 
      localDevice = LocalDevice.getLocalDevice(); 
      System.out.println("Address: " + localDevice.getBluetoothAddress()); 
      System.out.println("Name: " + localDevice.getFriendlyName()); 

      BluetoothSPPServer bluetoothSPPServer = new BluetoothSPPServer(); 
      bluetoothSPPServer.startServer(); 
     } catch (BluetoothStateException e) { 
      System.out.println("non c'è il bluetooth"); 
      this.interrupt(); 
      // e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
      this.interrupt(); 
     } 
    } 
} 

ここで(Android上)クライアントコードがある

package com.andrea.provabluetooth; 

import android.bluetooth.BluetoothAdapter; 
import android.bluetooth.BluetoothDevice; 
import android.bluetooth.BluetoothSocket; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.os.Bundle; 
import android.support.design.widget.FloatingActionButton; 
import android.support.design.widget.Snackbar; 
import android.support.v7.app.AlertDialog; 
import android.support.v7.app.AppCompatActivity; 
import android.support.v7.widget.Toolbar; 
import android.util.Log; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.widget.TextView; 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.OutputStream; 
import java.util.UUID; 

public class MainActivity extends AppCompatActivity { 

    private static final int REQUEST_ENABLE_BT = 1; 
    private BluetoothAdapter btAdapter = null; 
    private BluetoothSocket btSocket = null; 
    private OutputStream outStream = null; 
    private TextView out; 

    // Well known SPP UUID 
    private static final UUID MY_UUID = 
      UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); 

    // Insert your server's MAC address 
    private static String address = "3C:F8:62:50:AE:9B"; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
     setSupportActionBar(toolbar); 

     FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); 
     fab.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) 
         .setAction("Action", null).show(); 
      } 
     }); 

     out = (TextView) findViewById(R.id.textView); 

     reciveMessage(); 
    } 

    private void reciveMessage(){ 
     out.setText("Prova Bluetooth\n\n"); 


     btAdapter = BluetoothAdapter.getDefaultAdapter(); 

     CheckBTState(); 
     BluetoothDevice device = btAdapter.getRemoteDevice(address); 

     // Two things are needed to make a connection: 
     // A MAC address, which we got above. 
     // A Service ID or UUID. In this case we are using the 
     //  UUID for SPP. 
     try { 
      btSocket = device.createRfcommSocketToServiceRecord(MY_UUID); 
     } catch (IOException e) { 
      AlertBox("1Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + "."); 
     } 

     // Discovery is resource intensive. Make sure it isn't going on 
     // when you attempt to connect and pass your message. 
     btAdapter.cancelDiscovery(); 

     // Establish the connection. This will block until it connects. 
     try { 
      btSocket.connect(); 
      out.append("\n...Connessione stabilita e data link aperto..."); 
     } catch (IOException e) { 
      try { 
       btSocket.close(); 
      } catch (IOException e2) { 
       AlertBox("2Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + "."); 
      } 
     } 

     InputStream inStream; 
     try { 
      inStream = btSocket.getInputStream(); 
      BufferedReader bReader = new BufferedReader(new InputStreamReader(inStream)); 
      long startTime = System.currentTimeMillis(); 
      String lineRead = bReader.readLine(); 
      long stopTime = System.currentTimeMillis(); 
      Log.e("time to execute code", stopTime - startTime + ""); 
      Log.d("prova", "il dispositivo è: " + device.getName()); 
      out.append("\n\n" + lineRead); 
      Log.d("prova", lineRead); 
     } catch (IOException e) { 
      Log.d("prova", "il dispositivo non è: " + device.getName()); 
      //e.printStackTrace(); 
     } 

     try { 
      btSocket.close(); 
     } catch (IOException e2) { 
      AlertBox("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + "."); 
     } 
    } 

    private void CheckBTState() { 
     // Check for Bluetooth support and then check to make sure it is turned on 

     // Emulator doesn't support Bluetooth and will return null 
     if (btAdapter == null) { 
      AlertBox("5Fatal Error", "Bluetooth Not supported. Aborting."); 
     } else { 
      if (btAdapter.isEnabled()) { 
       out.append("\n...Bluetooth is enabled..."); 
      } else { 
       //Prompt user to turn on Bluetooth 
       Intent enableBtIntent = new Intent(btAdapter.ACTION_REQUEST_ENABLE); 
       startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); 
      } 
     } 
    } 

    public void AlertBox(String title, String message) { 
     new AlertDialog.Builder(this) 
       .setTitle(title) 
       .setMessage(message + " Press OK to exit.") 
       .setPositiveButton("OK", new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface arg0, int arg1) { 
         finish(); 
        } 
       }).show(); 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.menu_main, menu); 
     return true; 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     // Handle action bar item clicks here. The action bar will 
     // automatically handle clicks on the Home/Up button, so long 
     // as you specify a parent activity in AndroidManifest.xml. 
     int id = item.getItemId(); 

     //noinspection SimplifiableIfStatement 
     if (id == R.id.action_settings) { 
      return true; 
     } 

     return super.onOptionsItemSelected(item); 
    } 
} 

もう一つの小さな質問:私は、UUIDを変更しませんでしたが、I私はそれがスタックオーバーフロー上の別の質問で見つかったコードでそれを見つけたので、それを得ました。私はそれを残すことができますか私はそれを変更する必要がありますか?私がそれを変更しなければならない場合、どうすればいいですか?あなたの計り知れない忍耐

答えて

0

ため

おかげで、それは、誰かを助けることができるだけで、接続を閉じない場合は、約6秒で接続を確立することです。接続を閉じないと、次の投稿は瞬時に表示されます。

関連する問題