簡體   English   中英

將數據從我的App android發送到我的Raspberry PI 3

[英]Send data from my App android to my Raspberry PI 3

嗨,我實際上正在開發應用程序,以在我的Raspberry PI 3的終端上發送命令行。

我想在按下保存按鈕時將命令“ ls”發送到我的RPI3。

手動地,我的對象BluetoothconnectionService遇到了一些問題。 我認為我無法發送數據,因為未在活動“ Accueil”上聲明我的對象? `

BluetoothConnectionService.java:

public class BluetoothConnectionService  {

private static final String TAG = "BluetoothConnectionServ";
private static final String appName = "MYAPP";
private static final UUID MY_UUID_INSECURE = UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66");
private final BluetoothAdapter mBluetoothAdapter;
private ConnectedThread mConnectedThread;
private AcceptThread mInsecureAcceptThread;
private ConnectThread mConnectThread;
private BluetoothDevice mmDevice;
private UUID deviceUUID;

ProgressDialog mProgressDialog;
Context mContext;

public BluetoothConnectionService(Context context) {
    mContext = context;
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    start();
}
private class AcceptThread extends Thread {
    // The local server socket
    private final BluetoothServerSocket mmServerSocket;
    private BluetoothSocket socket = null;
    private InputStream mmInStream;
    private String device;

    public AcceptThread(){
        BluetoothServerSocket tmp = null;

        // Create a new listening server socket
        try{
            tmp = mBluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord(appName, MY_UUID_INSECURE);

            Log.d(TAG, "AcceptThread: Setting up Server using: " + MY_UUID_INSECURE);
        }catch (IOException e){
            Log.e(TAG, "AcceptThread: IOException: " + e.getMessage() );
        }

        mmServerSocket = tmp;
    }

    public void run(){
        Log.d(TAG, "run: AcceptThread Running.");

        BluetoothSocket socket = null;

        try{
            // This is a blocking call and will only return on a
            // successful connection or an exception
            Log.d(TAG, "run: RFCOM server socket start.....");

            socket = mmServerSocket.accept();

            Log.d(TAG, "run: RFCOM server socket accepted connection.");

        }catch (IOException e){
            Log.e(TAG, "AcceptThread: IOException: " + e.getMessage() );
        }

        //talk about this is in the 3rd
        if(socket != null){
            connected(socket,mmDevice);
        }

        Log.i(TAG, "END mAcceptThread ");
    }

    public void cancel() {
        Log.d(TAG, "cancel: Canceling AcceptThread.");
        try {
            mmServerSocket.close();
        } catch (IOException e) {
            Log.e(TAG, "cancel: Close of AcceptThread ServerSocket failed. " + e.getMessage() );
        }
    }

}
private class ConnectThread extends Thread {
    private BluetoothSocket mmSocket;

    public ConnectThread(BluetoothDevice device, UUID uuid) {
        Log.d(TAG, "ConnectThread: started.");
        mmDevice = device;
        deviceUUID = uuid;
    }

    public void run(){
        BluetoothSocket tmp = null;
        Log.i(TAG, "RUN mConnectThread ");

        // Get a BluetoothSocket for a connection with the
        // given BluetoothDevice
        try {
            Log.d(TAG, "ConnectThread: Trying to create InsecureRfcommSocket using UUID: "
                    +MY_UUID_INSECURE );
            tmp = mmDevice.createRfcommSocketToServiceRecord(deviceUUID);
        } catch (IOException e) {
            Log.e(TAG, "ConnectThread: Could not create InsecureRfcommSocket " + e.getMessage());
        }

        mmSocket = tmp;

        // Always cancel discovery because it will slow down a connection
        mBluetoothAdapter.cancelDiscovery();

        // Make a connection to the BluetoothSocket
        try {
            // This is a blocking call and will only return on a
            // successful connection or an exception
            mmSocket.connect();

            Log.d(TAG, "run: ConnectThread connected.");
        } catch (IOException e) {
            // Close the socket
            try {
                mmSocket.close();
                Log.d(TAG, "run: Closed Socket.");
            } catch (IOException e1) {
                Log.e(TAG, "mConnectThread: run: Unable to close connection in socket " + e1.getMessage());
            }
            Log.d(TAG, "run: ConnectThread: Could not connect to UUID: " + MY_UUID_INSECURE );
        }

        //will talk about this in the 3rd video
        connected(mmSocket,mmDevice);
    }
    public void cancel() {
        try {
            Log.d(TAG, "cancel: Closing Client Socket.");
            mmSocket.close();
        } catch (IOException e) {
            Log.e(TAG, "cancel: close() of mmSocket in Connectthread failed. " + e.getMessage());
        }
    }
}

public synchronized void start() {
    Log.d(TAG, "start");

    // Cancel any thread attempting to make a connection
    if (mConnectThread != null) {
        mConnectThread.cancel();
        mConnectThread = null;
    }
    if (mInsecureAcceptThread == null) {
        mInsecureAcceptThread = new AcceptThread();
        mInsecureAcceptThread.start();
    }
}

public void startClient(BluetoothDevice device,UUID uuid){
    Log.d(TAG, "startClient: Started.");

    //initprogress dialog
    mProgressDialog = ProgressDialog.show(mContext,"Connecting Bluetooth"
            ,"Please Wait...",true);

    mConnectThread = new ConnectThread(device, uuid);
    mConnectThread.start();
}

private class ConnectedThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;

    public ConnectedThread(BluetoothSocket socket) {
        Log.d(TAG, "ConnectedThread: Starting.");

        mmSocket = socket;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;
        int error=2;
        int i;

        //dismiss the progressdialog when connection is established
        try{
            mProgressDialog.dismiss();
            error=1;

        }catch (NullPointerException e){
            e.printStackTrace();
            error=0;

        }

        try {
            tmpIn = mmSocket.getInputStream();
            tmpOut = mmSocket.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }

    public void run(){
        byte[] buffer = new byte[1024];  // buffer store for the stream
        int bytes; // bytes returned from read()

        // Keep listening to the InputStream until an exception occurs
        while (true) {

            try {
                // Read from the InputStream
                bytes = mmInStream.read(buffer);
                final String strReceived = new String(buffer,0,bytes);
                final String strByteCnt  = String.valueOf(bytes) + "bytes received. \n";
                // Send the obtained bytes to the UI activity

            } catch (IOException e) {
                Log.e(TAG, "write: Error reading Input Stream. " + e.getMessage() );
                break;
            }
        }
    }

    //Call this from the main activity to send data to the remote device
    public void write(byte[] bytes) {
        try {
            mmOutStream.write(bytes);
        } catch (IOException e) {
            Log.e(TAG, "write: Error writing to output stream. " + e.getMessage() );
        }
    }

    /* Call this from the main activity to shutdown the connection */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
}

private void connected(BluetoothSocket mmSocket, BluetoothDevice mmDevice) {
    Log.d(TAG, "connected: Starting.");

    // Start the thread to manage the connection and perform transmissions
    mConnectedThread = new ConnectedThread(mmSocket);
    mConnectedThread.start();
}

public void write(byte[] out) {
    // Create temporary object
    ConnectedThread r;
    // Synchronize a copy of the ConnectedThread
    Log.d(TAG, "write: Write Called.");
    //perform the write
    mConnectedThread.write(out);
}

}

MainActivity.java:`

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener{

// variables
private static final String TAG = "MainActivity";
private Uri[] mFileUris = new Uri[10];
private static final UUID MY_UUID_INSECURE = UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66");
public ArrayList<BluetoothDevice> mBTDevices = new ArrayList<>();
public DeviceListAdapter mDeviceListAdapter;

// Bluetooth object
BluetoothAdapter mBluetoothAdapter;
BluetoothConnectionService mBluetoothConnection;
BluetoothDevice mBTDevice;

// variables button
Button btnStartConnection;
Button scan;

// Image button
ImageButton btnONOFF;

// Variables affichages
StringBuilder messages;
ListView lvNewDevices;


protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Constructor
    mBTDevices = new ArrayList<>();
    messages = new StringBuilder();
    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);

    // list findViewbyID
    btnONOFF = (ImageButton) findViewById(R.id.bluetooth_on_off);
    scan = (Button) findViewById(R.id.scan);
    btnStartConnection = (Button) findViewById(R.id.Connect);
    lvNewDevices = (ListView) findViewById(R.id.lvNewDevices);

    // divers
    registerReceiver(mBroadcastReceiver4, filter);
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    lvNewDevices.setOnItemClickListener(MainActivity.this);

    // ON/OFF BLUETOOTH

    btnONOFF.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            enableDisableBT();
        }
    });

    // SCAN

    scan.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            btnDiscover();
            btnEnableDisable_Discoverable();

        }
    });

    // CONNECTION

    btnStartConnection.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            startConnection();

        }
    });


}

// 4 BroadcastReceiver

// Create a BroadcastReceiver for ACTION_FOUND
private final BroadcastReceiver mBroadcastReceiver1 = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        // When discovery finds a device
        if (action.equals(mBluetoothAdapter.ACTION_STATE_CHANGED)) {
            final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, mBluetoothAdapter.ERROR);

            switch(state){
                case BluetoothAdapter.STATE_OFF:
                    Log.d(TAG, "onReceive: STATE OFF");
                    break;
                case BluetoothAdapter.STATE_TURNING_OFF:
                    Log.d(TAG, "mBroadcastReceiver1: STATE TURNING OFF");
                    break;
                case BluetoothAdapter.STATE_ON:
                    Log.d(TAG, "mBroadcastReceiver1: STATE ON");
                    break;
                case BluetoothAdapter.STATE_TURNING_ON:
                    Log.d(TAG, "mBroadcastReceiver1: STATE TURNING ON");
                    break;
            }
        }

    }
};

private final BroadcastReceiver mBroadcastReceiver2 = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();

        if (action.equals(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED)) {

            int mode = intent.getIntExtra(BluetoothAdapter.EXTRA_SCAN_MODE, BluetoothAdapter.ERROR);

            switch (mode) {
                //Device is in Discoverable Mode
                case BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE:
                    Log.d(TAG, "mBroadcastReceiver2: Discoverability Enabled.");
                    break;
                //Device not in discoverable mode
                case BluetoothAdapter.SCAN_MODE_CONNECTABLE:
                    Log.d(TAG, "mBroadcastReceiver2: Discoverability Disabled. Able to receive connections.");
                    break;
                case BluetoothAdapter.SCAN_MODE_NONE:
                    Log.d(TAG, "mBroadcastReceiver2: Discoverability Disabled. Not able to receive connections.");
                    break;
                case BluetoothAdapter.STATE_CONNECTING:
                    Log.d(TAG, "mBroadcastReceiver2: Connecting....");
                    break;
                case BluetoothAdapter.STATE_CONNECTED:
                    Log.d(TAG, "mBroadcastReceiver2: Connected.");
                    break;
            }

        }
    }
};
private BroadcastReceiver mBroadcastReceiver3 = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();
        Log.d(TAG, "onReceive: ACTION FOUND.");

        if (action.equals(BluetoothDevice.ACTION_FOUND)){
            BluetoothDevice device = intent.getParcelableExtra (BluetoothDevice.EXTRA_DEVICE);
            mBTDevices.add(device);
            Log.d(TAG, "onReceive: " + device.getName() + ": " + device.getAddress());
            mDeviceListAdapter = new DeviceListAdapter(context, R.layout.device_adapter_view, mBTDevices);
            lvNewDevices.setAdapter(mDeviceListAdapter);
        }
    }
};

/**
 * Broadcast Receiver that detects bond state changes (Pairing status changes)
 */
private final BroadcastReceiver mBroadcastReceiver4 = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();

        if(action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)){
            BluetoothDevice mDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            //3 cases:
            //case1: bonded already
            if (mDevice.getBondState() == BluetoothDevice.BOND_BONDED){
                Log.d(TAG, "BroadcastReceiver: BOND_BONDED.");
                //inside BroadcastReceiver4
                mBTDevice = mDevice;
            }
            //case2: creating a bone
            if (mDevice.getBondState() == BluetoothDevice.BOND_BONDING) {
                Log.d(TAG, "BroadcastReceiver: BOND_BONDING.");
            }
            //case3: breaking a bond
            if (mDevice.getBondState() == BluetoothDevice.BOND_NONE) {
                Log.d(TAG, "BroadcastReceiver: BOND_NONE.");
            }
        }
    }
};

//create method for starting connection
public void startConnection(){
    startBTConnection(mBTDevice,MY_UUID_INSECURE);
    goToAcceuil();
}


public void startBTConnection(BluetoothDevice device, UUID uuid){
    Log.d(TAG, "startBTConnection: Initializing RFCOM Bluetooth Connection.");
    mBluetoothConnection.startClient(device,uuid);
}

public void enableDisableBT(){
    if(mBluetoothAdapter == null){
        Log.d(TAG, "enableDisableBT: Does not have BT capabilities.");
    }
    if(!mBluetoothAdapter.isEnabled()){
        Log.d(TAG, "enableDisableBT: enabling BT.");
        Intent enableBTIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivity(enableBTIntent);

        IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
        registerReceiver(mBroadcastReceiver1, BTIntent);
    }
    if(mBluetoothAdapter.isEnabled()){
        Log.d(TAG, "enableDisableBT: disabling BT.");
        mBluetoothAdapter.disable();

        IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
        registerReceiver(mBroadcastReceiver1, BTIntent);
    }

}

public void btnEnableDisable_Discoverable() {
    Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
    discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
    startActivity(discoverableIntent);
    IntentFilter intentFilter = new IntentFilter(mBluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
    registerReceiver(mBroadcastReceiver2,intentFilter);

}

public void btnDiscover() {
    Log.d(TAG, "btnDiscover: Looking for unpaired devices.");

    if(mBluetoothAdapter.isDiscovering()){
        mBluetoothAdapter.cancelDiscovery();
        Log.d(TAG, "btnDiscover: Canceling discovery.");

        //check BT permissions in manifest
        checkBTPermissions();

        mBluetoothAdapter.startDiscovery();
        IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
    }
    if(!mBluetoothAdapter.isDiscovering()){

        //check BT permissions in manifest
        checkBTPermissions();

        mBluetoothAdapter.startDiscovery();
        IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
    }
}

/**
 * This method is required for all devices running API23+
 * Android must programmatically check the permissions for bluetooth. Putting the proper permissions
 * in the manifest is not enough.
 *
 * NOTE: This will only execute on versions > LOLLIPOP because it is not needed otherwise.
 */
private void checkBTPermissions() {
    if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
        int permissionCheck = this.checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATION");
        permissionCheck += this.checkSelfPermission("Manifest.permission.ACCESS_COARSE_LOCATION");
        if (permissionCheck != 0) {

            this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1001); //Any number
        }
    }else{
        Log.d(TAG, "checkBTPermissions: No need to check permissions. SDK version < LOLLIPOP.");
    }
}


@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
    //first cancel discovery because its very memory intensive.
    mBluetoothAdapter.cancelDiscovery();

    Log.d(TAG, "onItemClick: You Clicked on a device.");
    String deviceName = mBTDevices.get(i).getName();
    String deviceAddress = mBTDevices.get(i).getAddress();

    Log.d(TAG, "onItemClick: deviceName = " + deviceName);
    Log.d(TAG, "onItemClick: deviceAddress = " + deviceAddress);

    //create the bond.
    //NOTE: Requires API 17+? I think this is JellyBean
    if(Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2){
        Log.d(TAG, "Trying to pair with " + deviceName);

        mBTDevices.get(i).createBond();

        mBTDevice = mBTDevices.get(i);
        mBluetoothConnection = new BluetoothConnectionService(MainActivity.this);
    }
}

public void goToAcceuil (){
    Intent intent = new Intent (this,Accueil.class);
    intent.putExtra("DEVICE_NAME", mBTDevice.getName());
    intent.putExtra("DEVICE_ADRESS", mBTDevice.getAddress());
    intent.putExtra("mBTDevice",mBTDevice);
    //intent.putExtra("mBluetoothConnection",mBluetoothConnection);
    startActivity(intent);
}

protected void onDestroy() {
    Log.d(TAG, "onDestroy: called.");
    super.onDestroy();
    unregisterReceiver(mBroadcastReceiver1);
    unregisterReceiver(mBroadcastReceiver2);
    unregisterReceiver(mBroadcastReceiver3);
    unregisterReceiver(mBroadcastReceiver4);
}

}

Accueil.java:

public class Accueil extends AppCompatActivity {

// Bluetooth
BluetoothConnectionService mBluetoothConnection;
BluetoothDevice mBTDevice;

// String
String name_device1;
String adress_device1;
String freq_value1;
String item_spin1;
String item_spin;

// Image Button
ImageButton btn_back;
ImageButton btn_accueil;
ImageButton btn_voice;
ImageButton btn_scan;
ImageButton btn_settings;

// Button
Button btn_send_freq;

// Textview
TextView name_device;
TextView adress_device;

// Edit Text
EditText freq_value;

// List
ArrayAdapter<String> adapter;
List<String> list;

// Spinner
Spinner spinner1;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_accueil);

    // Variables from other activity
    name_device1= getIntent().getStringExtra("DEVICE_NAME");
    adress_device1=getIntent().getStringExtra("DEVICE_ADRESS");
    mBTDevice=getIntent().getExtras().getParcelable("mBTDevice");
    //mBluetoothConnection=getIntent().getExtras().getParcelable("mBluetoothConnection");
    freq_value1=getIntent().getStringExtra("VALUE_FREQ");
    item_spin1=getIntent().getStringExtra("VALUE_SPIN");

    // findView by ID
    name_device= (TextView) findViewById(R.id.name_device2);
    adress_device= (TextView) findViewById(R.id.adress_device2);
    btn_back = (ImageButton) findViewById(R.id.back1);
    btn_accueil = (ImageButton) findViewById(R.id.accueil1);
    btn_voice = (ImageButton) findViewById(R.id.voice1);
    btn_scan = (ImageButton) findViewById(R.id.scan1);
    btn_settings= (ImageButton) findViewById(R.id.settings1);
    btn_send_freq = (Button) findViewById(R.id.send_freq1);
    freq_value = (EditText) findViewById(R.id.value_freq1);
    spinner1=(Spinner) findViewById(R.id.spinner_freq);

    // SetText
    name_device.setText(name_device1);
    adress_device.setText(adress_device1);
    freq_value.setText(freq_value1);

    // Spinner
    list=new ArrayList<String>();
    list.add("MHz");
    list.add("GHz");

    adapter= new ArrayAdapter<String>(this,R.layout.spinner_item,list);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner1.setAdapter(adapter);


    btn_send_freq.setOnClickListener(new View.OnClickListener() { // Bouton Save
        @Override
        public void onClick(View view) {
            send_freq();
        }
    });

    btn_back.setOnClickListener(new View.OnClickListener() { // Bouton RETOUR
        @Override
        public void onClick(View view) {
            gotoBack();

        }
    });

    btn_accueil.setOnClickListener(new View.OnClickListener() { // Bouton ACCUEIL
        @Override
        public void onClick(View view) {
            gotoAccueil();
        }
    });

    btn_voice.setOnClickListener(new View.OnClickListener() { // Bouton VOICE
        @Override
        public void onClick(View view) {
            gotoVoice();
        }
    });

    btn_scan.setOnClickListener(new View.OnClickListener() { // Bouton SCAN
        @Override
        public void onClick(View view) {
            gotoScan();
        }
    });

    btn_settings.setOnClickListener(new View.OnClickListener() { // Bouton SETTINGS
        @Override
        public void onClick(View view) {
            gotoSettings();
        }
    });

}

// Fonction

public void send_freq() 
{
    byte[] bytesToSend="sudo rm azertyy".getBytes();
    mBluetoothConnection.write(bytesToSend);
    byte[] NewLine = "\n".getBytes();
    mBluetoothConnection.write(NewLine);
}

// Fonctions onglets

public void gotoBack() // Onglet PRECEDENT
{
    Intent intent = new Intent (this,MainActivity.class);
    startActivity(intent);
}

public void gotoAccueil() // Onglet ACCUEIL
{
    Intent intent = new Intent (this,Accueil.class);
    // get selected vale and start new activity
    item_spin= spinner1.getSelectedItem().toString();
    intent.putExtra("DEVICE_NAME", mBTDevice.getName());
    intent.putExtra("DEVICE_ADRESS", mBTDevice.getAddress());
    intent.putExtra("VALUE_FREQ", freq_value.getText().toString());
    intent.putExtra("VALUE_SPIN", item_spin);
    intent.putExtra("mBTDevice",mBTDevice);
    startActivity(intent);
}

public void gotoVoice() // Onglet VOICE
{
    Intent intent = new Intent (this,voice.class);
    // get selected vale and start new activity
    item_spin= spinner1.getSelectedItem().toString();
    intent.putExtra("DEVICE_NAME", mBTDevice.getName());
    intent.putExtra("DEVICE_ADRESS", mBTDevice.getAddress());
    intent.putExtra("VALUE_FREQ", freq_value.getText().toString());
    intent.putExtra("VALUE_SPIN", item_spin);
    intent.putExtra("mBTDevice",mBTDevice);
    startActivity(intent);
}

public void gotoScan() // Onglet SCAN
{
    Intent intent = new Intent (this,Scan.class);
    // get selected vale and start new activity
    item_spin= spinner1.getSelectedItem().toString();
    intent.putExtra("DEVICE_NAME", mBTDevice.getName());
    intent.putExtra("DEVICE_ADRESS", mBTDevice.getAddress());
    intent.putExtra("VALUE_FREQ", freq_value.getText().toString());
    intent.putExtra("VALUE_SPIN", item_spin);
    intent.putExtra("mBTDevice",mBTDevice);
    startActivity(intent);
}

public void gotoSettings() // Onglet SETTINGS
{
    Intent intent = new Intent (this,connection.class);
    // get selected vale and start new activity
    item_spin= spinner1.getSelectedItem().toString();
    intent.putExtra("DEVICE_NAME", mBTDevice.getName());
    intent.putExtra("DEVICE_ADRESS", mBTDevice.getAddress());
    intent.putExtra("VALUE_FREQ", freq_value.getText().toString());
    intent.putExtra("VALUE_SPIN", item_spin);
    intent.putExtra("mBTDevice",mBTDevice);
    startActivity(intent);
}

}

使用此功能,我想在RPI3的終端上發送“ ls”:

 public void send_freq() 
{
    byte[] bytesToSend="ls".getBytes();
    mBluetoothConnection.write(bytesToSend);
    byte[] NewLine = "\n".getBytes();
    mBluetoothConnection.write(NewLine);
}

但我不明白,我有這樣的錯誤: 在此處輸入圖片描述

我嘗試使用Parcelable解決此問題,但沒有成功... 在此處輸入圖片描述

所以我的代碼不起作用。 我的應用程序一直崩潰...

謝謝你的幫助 !

據我了解,您在MainActivity.java中有一個按鈕,可以通過Intent打開另一個Activity(Accueil.java) 這樣做時,您將發送帶有附加內容的Intent ,以在它們之間傳輸數據。

如果Intent實現了Parcelable接口,則它只能將一個對象作為額外對象。

在這里,您嘗試添加未實現Parcelable的 BluetoothConnectionService 您將其注釋掉,因為它給了您屏幕截圖中顯示的錯誤。

//intent.putExtra("mBluetoothConnection",mBluetoothConnection);

這意味着在Accueil.java中,您的mBluetoothConnection將為null,從而導致您的應用程序崩潰。

//mBluetoothConnection=getIntent().getExtras().getParcelable("mBluetoothConnection");

解決這個問題的方法是

  • 找到一種使BluetoothConnectionService實現Parcelable的方法
  • 如果可能,請重新實例化BluetoothConnectionService

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM