Skip to content
anttivu edited this page Feb 28, 2014 · 1 revision

package androidi.bluetooth;

import android.app.Activity; import android.os.Bundle; import android.bluetooth.BluetoothAdapter; import android.content.Intent; import android.bluetooth.BluetoothDevice; import java.util.Set; import android.bluetooth.BluetoothSocket; import java.util.UUID; import java.io.IOException; import java.io.InputStream;

public class MainActivity extends Activity { private int REQUEST_ENABLE_BT = 1; BluetoothAdapter mBluetoothAdapter; BluetoothDevice arduinoDevice; BluetoothSocket nmSocket; private InputStream mmInputStream; /** Called when the activity is first created. */ @Override

public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    setUpBluetooth(); //kutsu omaan aliohjelmaan
    findArduino();
    connectArduino();
    
}
private void connectArduino() {
    BluetoothSocket tmp = null;
    UUID uuid = UUID.fromString("00001101-"
            + "0000-1000-8000-"
    +"00805f9b34fb");
    InputStream tmpIn = null;
    /*
    yllä oleva koodi lienee arduino-bluetooth-laitteen uuid
    */
    */
    try {
        tmp = arduinoDevice.createInsecureRfcommSocketToServiceRecord(uuid);
        tmpIn = socket.getInputStream();
        
    } catch (IOException e) {}
    nmSocket = tmp;
    mmInputStream = tmpIn;
    
    /*
    Kotitehtävä:
    a)yhdistä socket
    b) luo input stream
    c) aloita socketista lukeminen, tee tätä varten oma funktio
    vinkki: Google: arduino+android+bluetooth
    */
    
}
private void setUpBluetooth() {

mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); //haetaan fyysistä bluetooth-laitetta vastaava ohjelmallinen toteutus //Jos haku ei onnistu(paluuarvo on null) ei laitteessa ole bluetoothia if (mBluetoothAdapter == null) // Device does not support Bluetooth

    if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);

}

    }  
private void findArduino (){
    Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();

// If there are paired devices if (pairedDevices.size() > 0) { // Loop through paired devices for (BluetoothDevice device : pairedDevices) { if (device.getName().equals("Arduino")) arduinoDevice = device; } }

}
}

Clone this wiki locally