Bonjour/ Bonsoir

Je vais faire des explications assez breves, car j'écrie ce message à 04:55, les insomnie sont enfin parti, je tombe de fatigue (enfin...)

Bref donc, je dois réaliser (pour mes études, c'est notée a l'examen) une application Android ce connectant à un autre périphérique via Bluetooth, et afficher (oui juste afficher) ce que je reçois.

Sachant que je n'ai pas fait précédemment de java, que les profs on "oublier" de faire du Java/Android en cours, donc j'ai apprit par mes propres moyens, et je suis arriver a un résultat (non final) qui me plais beaucoup pour l'instant.

Je cherche les petites coquilles, les problèmes qu'il peux arriver, et également les choses que j'ai fait qui sont contre productif (ne pas respecter des standards par exemple)

Voici le codes (Visual Studio Stable 2.3.2) :

MainActivity.java
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package fr.vampire142.pibluetooth;
 
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
 
import java.util.ArrayList;
import java.util.Set;
import java.util.StringTokenizer;
 
public class MainActivity extends AppCompatActivity {
 
    private static final int REQUEST_ENABLE_BT = 3;
 
    public BluetoothAdapter btAdapter;
 
    public String btAddrSelected;
    private String btNameSelected;
    private TextView textInfo;
    private ListView listDevicePaired;
    private ArrayList<String> mDeviceList = new ArrayList<>();
 
    // String pour le debugger
    private static final String TAG = "MainActivity";
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        textInfo = (TextView) findViewById(R.id.textInfo);
        listDevicePaired = (ListView) findViewById(R.id.listDevicePaired);
 
        checkBTState();
 
        listDevicePaired.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
 
                String btNameAddress = (String) parent.getItemAtPosition(position);
 
                StringTokenizer tokens = new StringTokenizer(btNameAddress, "\n");
                btNameSelected = tokens.nextToken();
                btAddrSelected = tokens.nextToken();
                Log.i(TAG, "Nom client :" + btNameSelected + "\nAdresse client :" + btAddrSelected);
 
                // Creation de l'intent et connection au périphérique
 
                Intent connectIntent = new Intent(MainActivity.this, ConnectToDevice.class);
                connectIntent.putExtra("Name", btNameSelected);
                connectIntent.putExtra("Address", btAddrSelected);
                startActivity(connectIntent);
 
 
            }
        });
    }
 
    private void checkBTState() {
        btAdapter = BluetoothAdapter.getDefaultAdapter();
        if (btAdapter == null) {
            // device doesn't support bluetooth
        } else {
            // bluetooth is off, ask user to on it.
            if (!btAdapter.isEnabled()) {
                Intent enableAdapter = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableAdapter, REQUEST_ENABLE_BT);
            } else {
                showPairedDevices();
            }
        }
    }
 
    private void showPairedDevices() {
        Set<BluetoothDevice> all_devices = btAdapter.getBondedDevices();
        if (all_devices.size() > 0) {
            for (BluetoothDevice currentDevice : all_devices) {
                mDeviceList.add(currentDevice.getName() + "\n" + currentDevice.getAddress());
            }
        }
        final ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, mDeviceList);
        listDevicePaired.setAdapter(adapter);
    }
 
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
 
        if (resultCode == Activity.RESULT_OK) {
            showPairedDevices();
        } else {
            Log.d(TAG, "Bluetooth désactivé");
            finish();
        }
    }
 
 
}
activity_main.xml
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="fr.vampire142.pibluetooth.MainActivity">
 
    <TextView
        android:id="@+id/textInfo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="16dp"
        android:text="@string/listBluetoothDevice"
        android:textSize="18sp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        app:layout_constraintHorizontal_bias="0.0"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp" />
 
    <ListView
        android:id="@+id/listDevicePaired"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textInfo"
        app:layout_constraintVertical_bias="1.0" />
 
</android.support.constraint.ConstraintLayout>
ConnectToDevice.java
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
package fr.vampire142.pibluetooth;
 
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.ToggleButton;
 
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
 
public class ConnectToDevice extends AppCompatActivity {
 
    // Récupération du choix de l'utilisateur
    private String nameRaspberry;
    private String addrRaspberry;
 
    // Composant Bluetooth
    boolean stateBluetooth = false;
    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothSocket mmSocket;
    private BluetoothDevice mmDevice;
 
    // UUID pour ce RFCOMM
    private String wellKnowUUID = "00001101-0000-1000-8000-00805F9B34FB";
 
    // Flux de donnée entrant
    private InputStream mmInputStream = null;
 
    // Thread pour la connexion et déconnexion
    Thread recvDataThread, connectBTThread;
    boolean stopConnect, stoprecvData;
    boolean socketCreated = false;
    byte[] mmBuffer;
    int nbrBytes;
 
    // Stockage des données
    boolean detailedInfo = false;
    private String noFormattedOutput;
    private String formattedOutput;
 
    // Definition de l'interface
    private TextView textViewer;
    private TextView dataType;
    private TextView textDeviceFound;
    private ToggleButton buttonDisConnect;
    private Switch switchType;
 
    // Debugger
    private static final String TAG = "ConnectToDevice";
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_connect_to_device);
 
        Bundle bundle = getIntent().getExtras();
 
        nameRaspberry = bundle.getString("Name");
        addrRaspberry = bundle.getString("Address");
 
        dataType = (TextView) findViewById(R.id.textType);
        textDeviceFound = (TextView) findViewById(R.id.textDeviceFound);
        textViewer = (TextView) findViewById(R.id.textViewer);
        switchType = (Switch) findViewById(R.id.switchType);
        buttonDisConnect = (ToggleButton) findViewById(R.id.toggleButton);
 
        textDeviceFound.setText(R.string.state);
        textDeviceFound.append(" " + nameRaspberry);
 
        switchType.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    dataType.setText(R.string.DetailedChosen);
                    detailedInfo = true;
 
                } else {
                    dataType.setText(R.string.RawChosen);
                    detailedInfo = false;
                }
            }
        });
 
        buttonDisConnect.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    findDevice();
                    openBT();
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
 
                            try {
                                Thread.sleep(10);
                            } catch (InterruptedException ex) {
                            }
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    receivData();
                                }
                            });
                        }
                    });
                } else {
                    closeBT();
                }
            }
        });
    }
 
    private void findDevice() {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
 
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        for (BluetoothDevice device : pairedDevices) {
            if (Objects.equals(device.getName(), nameRaspberry)) {
                Log.i(TAG, "openBT: " + "\n" +
                        "nameRaspberry: " + nameRaspberry + "\n" +
                        "addrRaspberry: " + addrRaspberry);
                mmDevice = device;
                break;
            }
        }
    }
 
    private void openBT() {
        final UUID uuidRFCOMM = UUID.fromString(wellKnowUUID);
        stopConnect = false;
 
        connectBTThread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (!Thread.currentThread().isInterrupted() && !stopConnect) {
 
                    try {
                        mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuidRFCOMM);
                        mmSocket.connect();
                        mmInputStream = mmSocket.getInputStream();
                    } catch (IOException ex) {
 
                        Log.e(TAG, "Socket's create() method failed", ex);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                textDeviceFound.setTextColor(Color.RED);
                                textDeviceFound.setText(R.string.ConnectError);
                            }
                        });
                        stopConnect = true;
                        switchType.setChecked(false);
                    }
                    socketCreated = true;
                }
 
            }
        });
        connectBTThread.start();
    }
 
    private void receivData() {
        recvDataThread = new Thread(new Runnable() {
            @Override
            public void run() {
 
                InputStream tmpInStream = null;
                try {
                    tmpInStream = mmSocket.getInputStream();
                } catch (IOException ex) {
                    Log.e(TAG, "Error init InputStream ", ex);
                }
 
                while (true) {
                    try {
                        assert tmpInStream != null;
                        nbrBytes = tmpInStream.read(mmBuffer);
                    } catch (IOException ex) {
                        Log.e(TAG, "Read InputStream error: ", ex);
                        break;
                    }
                    mmInputStream = tmpInStream;
                }
            }
        });
 
 
        if (detailedInfo) {
            textViewer.setText(formattedOutput);
        } else {
            textViewer.setText(noFormattedOutput);
        }
 
    }
 
    private void closeBT() {
 
        if (stateBluetooth)
            try {
                stopConnect = true;
                stoprecvData = true;
                mmInputStream.close();
                mmSocket.close();
            } catch (IOException e) {
                textViewer.setText(R.string.ConnectError);
            }
 
    }
}
activity_connect_to_device.xml
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:layout_editor_absoluteY="81dp"
    tools:layout_editor_absoluteX="0dp"
    tools:context="fr.vampire142.pibluetooth.ConnectToDevice">
 
    <Switch
        android:id="@+id/switchType"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginTop="16dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:ignore="RtlHardcoded" />
 
    <TextView
        android:id="@+id/labelDecodage"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        android:text="@string/switchState"
        android:textSize="20sp"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintHorizontal_chainStyle="spread_inside"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toLeftOf="@+id/switchType"
        app:layout_constraintTop_toTopOf="parent"
        tools:ignore="RtlHardcoded" />
 
    <ToggleButton
        android:id="@+id/toggleButton"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="@string/toggleButton"
        android:textOff="@string/btnConnectionString"
        android:textOn="@string/btnDisconnectionString"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/labelDecodage"
        android:layout_marginLeft="16dp"
        app:layout_constraintHorizontal_bias="0.0"
        android:layout_marginRight="16dp"
        android:layout_marginStart="16dp"
        android:layout_marginEnd="16dp" />
 
    <TextView
        android:id="@+id/textViewer"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:maxLines="15"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textDeviceFound"
        app:layout_constraintVertical_bias="0.0"
        tools:ignore="LabelFor" />
 
    <TextView
        android:id="@+id/textDeviceFound"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginTop="8dp"
        android:textAlignment="center"
        android:textSize="20sp"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textType" />
 
    <TextView
        android:id="@+id/textType"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="@string/RawChosen"
        android:textSize="20sp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/toggleButton"
        app:layout_constraintHorizontal_bias="0.0"
        android:layout_marginRight="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginStart="16dp"
        android:layout_marginEnd="16dp" />
 
</android.support.constraint.ConstraintLayout>

Voila, sa fait quand même un gros paquet

Voici en gros, pour simplifier ce qui m'interesse :

  • Mes érreurs
  • Non respects de standards
  • La bonne gestion des threads (oui la mienne est.... PARTICULIERE...


Merci d'avance pour votre aide précieuse ^^

Sur ce, je vais enfin me coucher, rendez vous dans ~6h