回答編集履歴

1

コード追加

2023/02/28 12:09

投稿

Yamagchi
Yamagchi

スコア1

test CHANGED
@@ -1 +1,256 @@
1
1
  こちら自分の方で書き間違えや実装追加をして直すことが出来ましたありがとうございます。
2
+ ```
3
+ package com.wabsarva.wings.android.bluetoothledarduinoandroid;
4
+
5
+ import androidx.appcompat.app.AppCompatActivity;
6
+ import androidx.core.app.ActivityCompat;
7
+
8
+ import android.bluetooth.BluetoothAdapter;
9
+ import android.bluetooth.BluetoothDevice;
10
+ import android.bluetooth.BluetoothSocket;
11
+ import android.content.pm.PackageManager;
12
+ import android.os.Bundle;
13
+ import android.os.Handler;
14
+ import android.os.Message;
15
+ import android.util.Log;
16
+ import android.view.View;
17
+ import android.widget.Button;
18
+ import android.widget.TextView;
19
+
20
+ import java.io.IOException;
21
+ import java.io.InputStream;
22
+ import java.io.OutputStream;
23
+ import java.util.Set;
24
+ import java.util.TreeMap;
25
+ import java.util.UUID;
26
+
27
+ public class MainActivity extends AppCompatActivity implements Runnable, View.OnClickListener {
28
+
29
+ //tag
30
+ private static final String TAG = "BluetoothSample";
31
+ //Bluetooth Adapter
32
+ private BluetoothAdapter mAdapter;
33
+
34
+ //Bluetooth device
35
+ private BluetoothDevice mDevice;
36
+
37
+ //Bluetooth UUID(固定)
38
+ private final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
39
+
40
+ //デバイス名 環境に合わせて変更
41
+ private final String DEVICE_NAME = "HC-05";
42
+
43
+ //Soket
44
+ private BluetoothSocket mSocket;
45
+
46
+ //Thread
47
+ private Thread mThread;
48
+
49
+ //Threadの状態を表す
50
+ private boolean isRunning;
51
+
52
+ //接続ボタン
53
+ private Button connectButton;
54
+
55
+ //書き込みボタン
56
+ private Button writeButton;
57
+
58
+ //Status
59
+ private TextView mStatusTextView;
60
+
61
+ //Bluetoothから受信した値
62
+ private TextView mInputTextView;
63
+
64
+ //Action(ステータス表示)
65
+ private static final int VIEW_STATUS = 0;
66
+
67
+ //Action(取得文字列)
68
+ private static final int VIEW_INPUT = 1;
69
+
70
+ //Connect確認フラグ
71
+ private boolean connectFlg = false;
72
+
73
+ //BluetoothのOUTputStream
74
+ OutputStream mmOutputStream = null;
75
+
76
+
77
+ @Override
78
+ protected void onCreate(Bundle savedInstanceState) {
79
+ super.onCreate(savedInstanceState);
80
+ //Layoutにて設定したビューの表示
81
+ setContentView(R.layout.activity_main);
82
+
83
+ // TextViewの設定(Layoutにて設定したものを関連付け)
84
+ mInputTextView = (TextView) findViewById(R.id.inputValue);
85
+ mStatusTextView = (TextView) findViewById(R.id.statusValue);
86
+
87
+ // Buttonの設定(Layoutにて設定したものを関連付け)
88
+ connectButton = (Button) findViewById(R.id.connectButton);
89
+ writeButton = (Button) findViewById(R.id.writeButton);
90
+
91
+ // ボタンのイベント設定
92
+ connectButton.setOnClickListener(this);
93
+ writeButton.setOnClickListener(this);
94
+
95
+ // Bluetoothのデバイス名を取得
96
+ // DVICE_NAMEでデバイス名を定義
97
+ mAdapter = BluetoothAdapter.getDefaultAdapter();
98
+ mStatusTextView.setText("SearchDevice");
99
+ if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
100
+ // TODO: Consider calling
101
+ // ActivityCompat#requestPermissions
102
+ // here to request the missing permissions, and then overriding
103
+ // public void onRequestPermissionsResult(int requestCode, String[] permissions,
104
+ // int[] grantResults)
105
+ // to handle the case where the user grants the permission. See the documentation
106
+ // for ActivityCompat#requestPermissions for more details.
107
+ return;
108
+ }
109
+ Set<BluetoothDevice> devices = mAdapter.getBondedDevices();
110
+ for (BluetoothDevice device : devices) {
111
+
112
+ if (device.getName().equals(DEVICE_NAME)) {
113
+ mStatusTextView.setText("find: " + device.getName());
114
+ mDevice = device;
115
+ }
116
+ }
117
+ }
118
+
119
+ // 別のアクティビティが起動した場合の処理
120
+ @Override
121
+ protected void onPause() {
122
+ super.onPause();
123
+
124
+ isRunning = false;
125
+ connectFlg = false;
126
+
127
+ try {
128
+ mSocket.close();
129
+ } catch (Exception e) {
130
+ }
131
+ }
132
+
133
+ // スレッド処理(connectボタン押下後に実行)
134
+ @Override
135
+ public void run() {
136
+ InputStream mmInStream = null;
137
+
138
+ Message valueMsg = new Message();
139
+ valueMsg.what = VIEW_STATUS;
140
+ valueMsg.obj = "connecting...";
141
+ mHandler.sendMessage(valueMsg);
142
+
143
+ try {
144
+
145
+ // 取得したデバイス名を使ってBluetoothでSocket接続
146
+ if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
147
+ // TODO: Consider calling
148
+ // ActivityCompat#requestPermissions
149
+ // here to request the missing permissions, and then overriding
150
+ // public void onRequestPermissionsResult(int requestCode, String[] permissions,
151
+ // int[] grantResults)
152
+ // to handle the case where the user grants the permission. See the documentation
153
+ // for ActivityCompat#requestPermissions for more details.
154
+ return;
155
+ }
156
+ mSocket = mDevice.createRfcommSocketToServiceRecord(MY_UUID);
157
+ mSocket.connect();
158
+ mmInStream = mSocket.getInputStream();
159
+ mmOutputStream = mSocket.getOutputStream();
160
+
161
+ // InputStreamのバッファを格納
162
+ byte[] buffer = new byte[1024];
163
+ // 取得したバッファのサイズを格納
164
+ int bytes;
165
+ valueMsg = new Message();
166
+ valueMsg.what = VIEW_STATUS;
167
+ valueMsg.obj = "connected.";
168
+ mHandler.sendMessage(valueMsg);
169
+
170
+ connectFlg = true;
171
+
172
+ while(isRunning){
173
+
174
+ // InputStreamの読み込み
175
+ bytes = mmInStream.read(buffer);
176
+ Log.i(TAG,"bytes="+bytes);
177
+ // String型に変換
178
+ String readMsg = new String(buffer, 0, bytes);
179
+
180
+ // null以外なら表示
181
+ if(readMsg.trim() != null && !readMsg.trim().equals("")){
182
+ Log.i(TAG,"value="+readMsg.trim());
183
+
184
+ valueMsg = new Message();
185
+ valueMsg.what = VIEW_INPUT;
186
+ valueMsg.obj = readMsg;
187
+ mHandler.sendMessage(valueMsg);
188
+ }
189
+ }
190
+ }
191
+ // エラー処理
192
+ catch(Exception e){
193
+
194
+ valueMsg = new Message();
195
+ valueMsg.what = VIEW_STATUS;
196
+ valueMsg.obj = "Error1:" + e;
197
+ mHandler.sendMessage(valueMsg);
198
+
199
+ try{
200
+ mSocket.close();
201
+ }catch(Exception ee){}
202
+ isRunning = false;
203
+ connectFlg = false;
204
+ }
205
+ }
206
+
207
+ // ボタン押下時の処理
208
+ @Override
209
+ public void onClick(View v) {
210
+ if(v.equals(connectButton)) {
211
+ // 接続されていない場合のみ
212
+ if (!connectFlg) {
213
+ mStatusTextView.setText("try connect");
214
+
215
+ mThread = new Thread(this);
216
+ // Threadを起動し、Bluetooth接続
217
+ isRunning = true;
218
+ mThread.start();
219
+ }
220
+ } else if(v.equals(writeButton)) {
221
+ // 接続中のみ書込みを行う
222
+ if (connectFlg) {
223
+ try {
224
+ // Writeボタン押下時、'2'を送信
225
+ mmOutputStream.write("2".getBytes());
226
+ // 画面上に"Write:"を表示
227
+ mStatusTextView.setText("Write:");
228
+ } catch (IOException e) {
229
+ Message valueMsg = new Message();
230
+ valueMsg.what = VIEW_STATUS;
231
+ valueMsg.obj = "Error2:" + e;
232
+ mHandler.sendMessage(valueMsg);
233
+ }
234
+ } else {
235
+ mStatusTextView.setText("Please push the connect button");
236
+ }
237
+ }
238
+ }
239
+
240
+ //描画処理はHandlerでおこなう
241
+ Handler mHandler = new Handler() {
242
+ @Override
243
+ public void handleMessage(Message msg) {
244
+ int action = msg.what;
245
+ String msgStr = (String)msg.obj;
246
+ if(action == VIEW_INPUT){
247
+ mInputTextView.setText(msgStr);
248
+ }
249
+ else if(action == VIEW_STATUS){
250
+ mStatusTextView.setText(msgStr);
251
+ }
252
+ }
253
+ };
254
+ }
255
+
256
+ ```