新增 蓝牙读取activity

master
wangh 6 months ago
parent 38edb74d4c
commit d0d8042a70

@ -17,10 +17,9 @@
android:supportsRtl="true"
android:theme="@style/Theme.JinYuRFID"
tools:targetApi="31">
<service
android:name=".MyBluetoothService"
android:enabled="true"
android:exported="true"></service>
<activity
android:name=".BlueToothServerActivity"
android:exported="true"/>
<receiver
android:name=".broadcast.ScanERCodeReceiver"
@ -38,26 +37,25 @@
<activity
android:name=".ReadActivity"
android:exported="true" />
<activity
android:name=".WriteUserActivity"
android:exported="true">
android:name=".ReadBlueToothActivity"
android:exported="true" />
<!-- <intent-filter>-->
<!-- <action android:name="android.intent.action.MAIN" />-->
<!-- <category android:name="android.intent.category.LAUNCHER" />-->
<!-- </intent-filter>-->
</activity>
<activity
android:name=".WriteUserActivity"
android:exported="true" />
<activity
android:name=".ConfigurationTableActivity"
android:exported="false" />
<activity
android:name=".MainActivity"
android:exported="true">
<!-- <intent-filter>-->
<!-- <action android:name="android.intent.action.MAIN" />-->
<!-- <category android:name="android.intent.category.LAUNCHER" />-->
<!-- </intent-filter>-->
<!-- <intent-filter> -->
<!-- <action android:name="android.intent.action.MAIN" /> -->
<!-- <category android:name="android.intent.category.LAUNCHER" /> -->
<!-- </intent-filter> -->
</activity>
</application>

@ -22,7 +22,6 @@ public class AppLoginActivity extends AppCompatActivity {
private Resources resources;
private Configuration config;
private int index;
@Override
@ -30,11 +29,11 @@ public class AppLoginActivity extends AppCompatActivity {
super.onCreate(savedInstanceState);
resources = getResources();
config = resources.getConfiguration();
var languageString = SharedPreferencesUtils.getstring("language", "中文");
getLocaleStringXML(languageString);
resources.updateConfiguration(config, resources.getDisplayMetrics());
var index = Integer.parseInt(SharedPreferencesUtils.getstring("languageIndex", "0"));
changeLanguage(index);
binding = DataBindingUtil.setContentView(this, R.layout.activity_app_login);
binding.appLanguage.setSelection(index);
// 工作模式
var workmode = SharedPreferencesUtils.getInt("workmode", 0);
binding.mainWork.setSelection(workmode);
}
@ -46,29 +45,24 @@ public class AppLoginActivity extends AppCompatActivity {
var value = strings.indexOf(workModeStr);
SharedPreferencesUtils.putInt("workmode", value);
// 选择语言
var s = binding.appLanguage.getSelectedItem().toString();
SharedPreferencesUtils.putstring("language", s);
getLocaleStringXML(s);
resources.updateConfiguration(config, resources.getDisplayMetrics());
var intent = new Intent(this, ReadActivity.class);
Log.e("TAG", "appLoginClick:" + value);
intent.putExtra("work",value);
var index = binding.appLanguage.getSelectedItemPosition();
changeLanguage(index);
var intent = new Intent(this, ReadBlueToothActivity.class);
intent.putExtra("work", value);
SharedPreferencesUtils.putstring("languageIndex", index + "");
intent.putExtra("appType",true);
startActivity(intent);
finish();
}
private void getLocaleStringXML(String languageString) {
if (languageString.equals("中文")) {
private void changeLanguage(int index) {
if (index == 0) {
config.locale = Locale.CHINA;
index = 0;
} else if (languageString.equals("English")) {
} else if (index == 1) {
config.locale = Locale.ENGLISH;
index = 1;
} else {
config.locale = new Locale("vi", "VN");
index = 2;
}
resources.updateConfiguration(config, resources.getDisplayMetrics());
}
}

@ -0,0 +1,102 @@
package com.example.jinyu_rfid;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.io.IOException;
import java.io.InputStream;
import java.util.Set;
import java.util.UUID;
public class BlueToothServerActivity extends AppCompatActivity {
private BluetoothServerSocket serverSocket;
private BluetoothSocket socket;
@RequiresApi(api = Build.VERSION_CODES.S)
@SuppressLint("MissingInflatedId")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_blue_tooth_server);
// 0000110a-0000-1000-8000-00805f9b34fb
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.BLUETOOTH_CONNECT}, 1);
}
// Set<BluetoothDevice> devices = bluetoothAdapter.getBondedDevices();
// D:for (BluetoothDevice bluetoothDevice : devices) {
// Log.e("TAG", bluetoothDevice.getName() + ":" + bluetoothDevice.getUuids()[0].toString());
// /* // if (bluetoothDevice.getAddress().toString().equals("FC:0F:E7:B6:15:2F")) {
// if (bluetoothDevice.getName().equals("AUTOID UTouch")) {
// mmDevice = bluetoothDevice;
// Log.e("TAG", "连接成功");
// break D;
// }*/
// }
try {
// 创建一个BluetoothServerSocket来监听连接请求
serverSocket = bluetoothAdapter.listenUsingRfcommWithServiceRecord(
"abc",
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
// 无限循环以接受连接请求
while (true) {
socket = serverSocket.accept();
// 接收数据
receiveData(socket);
// 关闭socket
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void receiveData(BluetoothSocket socket) {
try {
InputStream inputStream = socket.getInputStream();
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
// 处理接收到的数据
// (buffer, 0, bytesRead) 是接收到的数据
String receivedData = new String(buffer, 0, bytesRead);
Toast.makeText(this, receivedData, Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void stopServer() {
try {
if (serverSocket != null) {
serverSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
stopServer();
}
}

@ -1,16 +0,0 @@
package com.example.jinyu_rfid;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
public class MyBluetoothService extends Service {
public MyBluetoothService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
}

@ -1,9 +1,18 @@
package com.example.jinyu_rfid;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.databinding.DataBindingUtil;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.ParcelUuid;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
@ -23,10 +32,15 @@ import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import okhttp3.RequestBody;
@ -37,6 +51,7 @@ public class ReadActivity extends BaseActivity implements DataReturnCall {
private List<ReadTyreNoResult> list;
private ActivityReadBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@ -46,21 +61,14 @@ public class ReadActivity extends BaseActivity implements DataReturnCall {
list = new ArrayList<>(11);
adapter.setList(list);
binding.setAdapter(adapter);
var workmode = getIntent().getIntExtra("work", 0);
binding.setType(workmode == 1);
// 名称
stringArray = getResources().getStringArray(R.array.project_list);
var appType = getIntent().getBooleanExtra("appType", false);
if (appType) {
// tl-gx4
} else {
rfidModel = new C5106Device(this);
}
rfidModel = new C5106Device(this);
}
// 读取user区
public void readInfo(View view) {
rfidModel.sanUser(80);
}
@ -69,38 +77,10 @@ public class ReadActivity extends BaseActivity implements DataReturnCall {
rfidModel.sanEpc(6);
}
@SuppressLint("NotifyDataSetChanged")
@Override
public void readEpcCodeInfo(String info, boolean state, String stateInfo) {
if (state) {
music.start();
list.clear();
binding.readText.setText(info);
Map<String, String> map = new HashMap<>();
map.put("EpcCode", info);
map.put("token", "123456");
map.put("Language", SharedPreferencesUtils.getstring("languageIndex", "0"));
OkGo.<MyResult>post(url + "/readEPCCode")
.upRequestBody(RequestBody.create(JSON, gson.toJson(map))).execute(new MyRecultCall(dialog, this) {
@Override
public void onSuccess(Response<MyResult> response) {
super.onSuccess(response);
var body = response.body();
if (body.getResultFlag().equals("1")) {
list.addAll(gson.fromJson(body.getJson(), new TypeToken<List<ReadTyreNoResult>>() {
}.getType()));
adapter.notifyDataSetChanged();
} else {
Toast.makeText(ReadActivity.this, body.getJson(), Toast.LENGTH_SHORT).show();
adapter.notifyDataSetChanged();
}
}
});
} else {
binding.readText.setText(null);
}
}
@SuppressLint("NotifyDataSetChanged")
@ -121,7 +101,6 @@ public class ReadActivity extends BaseActivity implements DataReturnCall {
}
adapter.notifyDataSetChanged();
}
//
}

@ -0,0 +1,239 @@
package com.example.jinyu_rfid;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.BluetoothSocket;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.databinding.DataBindingUtil;
import com.example.jinyu_rfid.adapter.ResultAdapter;
import com.example.jinyu_rfid.base.BaseActivity;
import com.example.jinyu_rfid.base.MyRecultCall;
import com.example.jinyu_rfid.base.MyResult;
import com.example.jinyu_rfid.been.ReadTyreNoResult;
import com.example.jinyu_rfid.callback.DataReturnCall;
import com.example.jinyu_rfid.databinding.ActivityBluetoothReadBinding;
import com.example.jinyu_rfid.databinding.ActivityReadBinding;
import com.example.jinyu_rfid.rfid.C5106Device;
import com.example.jinyu_rfid.rfid.RFIDModel;
import com.example.jinyu_rfid.uitls.ASCIIUtil;
import com.example.jinyu_rfid.uitls.SharedPreferencesUtils;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import okhttp3.RequestBody;
public class ReadBlueToothActivity extends BaseActivity {
private ResultAdapter adapter;
private String[] stringArray;
private List<ReadTyreNoResult> list;
private ActivityBluetoothReadBinding binding;
private BluetoothSocket bluetoothSocket;
private InputStream inputStream;
private OutputStream outputStream;
private boolean activityType;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_bluetooth_read);
binding.setTitle(getString(R.string.go_read));
adapter = new ResultAdapter(this);
list = new ArrayList<>(11);
adapter.setList(list);
binding.setAdapter(adapter);
var workmode = getIntent().getIntExtra("work", 0);
activityType = (workmode == 1);// 本地读取user
binding.setType(activityType);// 工作模式
stringArray = getResources().getStringArray(R.array.project_list); // 名称
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// 获取已配对蓝牙设备
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.BLUETOOTH_CONNECT}, 1);
}
Set<BluetoothDevice> devices = mBluetoothAdapter.getBondedDevices();
BluetoothDevice device = null;
for (BluetoothDevice bluetoothDevice : devices) {
Log.e("TAG", bluetoothDevice.getName() + ":" + bluetoothDevice.getUuids()[0].toString());
if (bluetoothDevice.getName().equals("Trans-Logik TL-GX4- 004614")) {
device = bluetoothDevice;
break;
}
}
if (device == null) {
Toast.makeText(context, getString(R.string.bluetooth_open_state), Toast.LENGTH_SHORT).show();
finish();
return;
}
try {
bluetoothSocket = device.createRfcommSocketToServiceRecord(device.getUuids()[0].getUuid());
bluetoothSocket.connect();
Log.e("TAG", "连接成功?:" + bluetoothSocket.isConnected());
if (!bluetoothSocket.isConnected()) {
// 设备未连接
Toast.makeText(context, getString(R.string.bluetooth_open_state), Toast.LENGTH_LONG).show();
finish();
return;
}
inputStream = bluetoothSocket.getInputStream();
outputStream = bluetoothSocket.getOutputStream();
// 启动后台线程接收数据
Thread myThread = new Thread(new Runnable() {
@Override
public void run() {
byte[] buffer = new byte[1024];
int bytesRead;
try {
while ((bytesRead = inputStream.read(buffer)) != -1) {
String receivedData = new String(buffer, 0, bytesRead);
Message message = handler.obtainMessage();
message.obj = receivedData;
handler.sendMessage(message);
}
} catch (IOException e) {
Log.e("TAG", "Error reading from input stream", e);
}
}
});
myThread.start();
} catch (IOException e) {
e.printStackTrace();
disconnect();
}
}
private Handler handler = new Handler() {
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
String receivedData = (String) msg.obj;
Log.e("TAG", "handleMessage:" + receivedData);
if (receivedData.substring(0, 2).equals("GR")){
if (activityType) {
readUserInfo(receivedData.substring(2,receivedData.length()));
}
} else {
binding.readText.setText(null);
}
}
};
// 读取user区
public void readInfo(View view) {
String data = binding.readText.getText().toString() + "\r";
try {
Log.e("TAG", "发送:" + data);
outputStream.write(data.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
public void readEPCInfo(View view) {
}
@SuppressLint("NotifyDataSetChanged")
public void readEpcCodeInfo(String info, boolean state, String stateInfo) {
if (state) {
music.start();
list.clear();
binding.readText.setText(info);
Map<String, String> map = new HashMap<>();
map.put("EpcCode", info);
map.put("token", "123456");
map.put("Language", SharedPreferencesUtils.getstring("languageIndex", "0"));
OkGo.<MyResult>post(url + "/readEPCCode").upRequestBody(RequestBody.create(JSON, gson.toJson(map))).execute(new MyRecultCall(dialog, this) {
@Override
public void onSuccess(Response<MyResult> response) {
super.onSuccess(response);
var body = response.body();
if (body.getResultFlag().equals("1")) {
list.addAll(gson.fromJson(body.getJson(), new TypeToken<List<ReadTyreNoResult>>() {
}.getType()));
adapter.notifyDataSetChanged();
} else {
Toast.makeText(ReadBlueToothActivity.this, body.getJson(), Toast.LENGTH_SHORT).show();
adapter.notifyDataSetChanged();
}
}
});
} else {
binding.readText.setText(null);
}
}
@SuppressLint("NotifyDataSetChanged")
public void readUserInfo(String user) {
list.clear();
binding.readText.setText(user);
music.start();
String info = ASCIIUtil.hex2Str(user);
Log.e("TAG", "readUserInfo:" + info);
var infos = info.split("~");
for (int i = 0; i < 12; i++) {
try {
list.add(new ReadTyreNoResult(i, stringArray[i], infos[i]));
}catch (Exception er){
}
}
adapter.notifyDataSetChanged();
}
private void disconnect() {
try {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
if (bluetoothSocket != null) {
bluetoothSocket.close();
}
} catch (IOException e) {
Log.e("TAG", "Error closing socket", e);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
disconnect();
}
}

@ -53,7 +53,6 @@ public class WriteUserActivity extends BaseActivity implements DataReturnCall, P
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_write_user);
intent1 = new Intent(this, ReadActivity.class);
intent1.putExtra("work", 1);
intent2 = new Intent(this, ConfigurationTableActivity.class);
ScanERCodeReceiver scanERCodeReceiver = new ScanERCodeReceiver(this);
registerReceiver(scanERCodeReceiver, new IntentFilter("com.rfid.SCAN"));
@ -208,7 +207,6 @@ public class WriteUserActivity extends BaseActivity implements DataReturnCall, P
@Override
public boolean onMenuItemClick(MenuItem item) {
if (item.getItemId() == R.id.menu_read) {
startActivity(intent1);
} else {
startActivity(intent2);

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".BlueToothServerActivity">
</androidx.constraintlayout.widget.ConstraintLayout>

@ -0,0 +1,80 @@
<?xml version="1.0" encoding="utf-8"?>
<layout 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">
<data>
<variable
name="title"
type="String" />
<variable
name="adapter"
type="com.example.jinyu_rfid.adapter.ResultAdapter" />
<variable
name="type"
type="Boolean" />
<import type="android.view.View" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".ReadActivity">
<include
layout="@layout/toolbar"
app:title="@{title}" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="45dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="8dp">
<TextView
style="@style/text_name"
android:layout_width="120dp"
android:layout_height="match_parent"
android:text="@string/scanning_area" />
<EditText
android:id="@+id/read_text"
style="@style/text_name"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/san_text" />
</LinearLayout>
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:adapter="@{adapter}"
android:padding="8dp"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" />
<Button
android:layout_width="match_parent"
android:layout_height="55dp"
android:layout_margin="10dp"
android:onClick="readInfo"
android:text="@string/go_read"
android:textSize="18sp"
android:visibility="@{type?View.VISIBLE:View.GONE}" />
<Button
android:layout_width="match_parent"
android:layout_height="55dp"
android:layout_margin="10dp"
android:onClick="readEPCInfo"
android:text="@string/read_epc"
android:textSize="18sp"
android:visibility="@{type?View.GONE:View.VISIBLE}" />
</LinearLayout>
</layout>

@ -13,9 +13,7 @@
name="adapter"
type="com.example.jinyu_rfid.adapter.ResultAdapter" />
<variable
name="type"
type="Boolean" />
<import type="android.view.View" />
</data>
@ -63,17 +61,7 @@
android:layout_margin="10dp"
android:onClick="readInfo"
android:text="@string/go_read"
android:textSize="18sp"
android:visibility="@{type?View.VISIBLE:View.GONE}" />
<Button
android:layout_width="match_parent"
android:layout_height="55dp"
android:layout_margin="10dp"
android:onClick="readEPCInfo"
android:text="@string/read_epc"
android:textSize="18sp"
android:visibility="@{type?View.GONE:View.VISIBLE}" />
android:textSize="18sp" />
</LinearLayout>

@ -35,4 +35,5 @@
<string name="standalone_mode">"standalone mode "</string>
<string name="scanning_area">scanning area</string>
<string name="dialog_button_text">I see</string>
<string name="bluetooth_open_state">Bluetooth not connected, program exits</string>
</resources>

@ -36,4 +36,5 @@
<string name="standalone_mode">Chế độ đơn</string>
<string name="scanning_area">Khu vực quét</string>
<string name="dialog_button_text">Tôi biết rồi</string>
<string name="bluetooth_open_state">Bluetooth không kết nối, chương trình thoát</string>
</resources>

@ -34,5 +34,6 @@
<string name="net_model">网络模式</string>
<string name="standalone_mode">单机模式</string>
<string name="scanning_area">扫描区域</string>
<string name="dialog_button_text">我知道了</string>>
<string name="dialog_button_text">我知道了</string>
<string name="bluetooth_open_state">蓝牙未连接,程序退出</string>>
</resources>
Loading…
Cancel
Save