我想构建一个应用程序,其中 2 个 android 设备通过蓝牙相互连接。让设备 1 和设备 2。现在,如果设备 1 向设备 2 发送电池百分比请求,则设备 2 的电池百分比将显示给设备 1 应用程序.我完成了连接部分(蓝牙连接),但卡在电池部分。它只是显示设备 1 的电池。请帮助解决这个问题。我在这里过了总代码。 Activity_main.xml:
<?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=".MainActivity">
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="31dp"
android:layout_marginTop="96dp"
android:layout_marginBottom="4dp"
android:text="lisen"
app:layout_constraintBottom_toTopOf="@+id/_dynamic"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="UnknownId" />
<Button
android:id="@+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="17dp"
android:layout_marginTop="3dp"
android:text="List Devices"
app:layout_constraintStart_toEndOf="@+id/button3"
app:layout_constraintTop_toTopOf="@+id/button3" />
<TextView
android:id="@+id/textView2"
android:layout_width="100dp"
android:layout_height="37dp"
android:layout_marginStart="12dp"
android:text="status"
app:layout_constraintBaseline_toBaselineOf="@+id/button4"
app:layout_constraintStart_toEndOf="@+id/button4" />
<ListView
android:id="@+id/listview"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="1dp"
android:layout_marginTop="144dp"
android:layout_marginEnd="1dp"
android:layout_marginBottom="139dp"
app:layout_constraintBottom_toTopOf="@+id/editTextTextPersonName"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/textView"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="4dp"
android:layout_marginEnd="4dp"
android:layout_marginBottom="103dp"
android:text="Message"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/listview"
app:layout_constraintVertical_bias="1.0" />
<EditText
android:id="@+id/editTextTextPersonName"
android:layout_width="284dp"
android:layout_height="60dp"
android:layout_marginBottom="42dp"
android:ems="10"
android:inputType="textPersonName"
app:layout_constraintBottom_toBottomOf="parent"
tools:ignore="MissingConstraints"
tools:layout_editor_absoluteX="2dp" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="20dp"
android:layout_marginBottom="55dp"
android:text="Send"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@+id/editTextTextPersonName"
tools:ignore="MissingConstraints" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="52dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="42dp"
android:text="Battery_status"
app:layout_constraintEnd_toStartOf="@+id/textView3"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/textView3"
android:layout_width="134dp"
android:layout_height="49dp"
android:layout_marginTop="14dp"
android:layout_marginEnd="80dp"
android:layout_marginBottom="76dp"
app:layout_constraintBottom_toTopOf="@+id/listview"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@+id/button2"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
main_activity.java
package com.example.connect_bluetooth;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Switch;
import android.widget.TextView;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
Button listen,listDevices,send,battery;
TextView status,msg_box;
ListView listView;
EditText write_msg;
BluetoothAdapter bluetoothAdapter;
BluetoothDevice[]btarray;
SendReceive sendReceive;
ArrayList list=new ArrayList();
static final int STATE_LISTENING=1;
static final int STATE_CONNECTING=2;
static final int STATE_CONNECTED=3;
static final int STATE_CONNECTION_FAILED=4;
static final int STATE_MESSAGE_RECEIVE=5;
private static final String APP_NAME="Bluetooth_connection";
private static final UUID MY_UUID=UUID.fromString("e9a9533e-47b7-40b4-a277-644b86d2452d");
TextView textview;
IntentFilter intentfilter;
int REQUEST_ENABLE_BLUETOOTH=1;
@SuppressLint("MissingPermission")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewByIds();
bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
if(!bluetoothAdapter.isEnabled())
{
Intent enableIntent=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent,REQUEST_ENABLE_BLUETOOTH);
ImplementListener();
}
}
private void ImplementListener() {
//......Display pair devices.........//
listDevices.setOnClickListener(new View.OnClickListener() {
@SuppressLint("MissingPermission")
@Override
public void onClick(View view) {
System.out.println("hi");
@SuppressLint("MissingPermission")
Set<BluetoothDevice> bt=bluetoothAdapter.getBondedDevices();
String[]strings=new String[bt.size()];
btarray = new BluetoothDevice[bt.size()];
int index=0;
if(bt.size()>0)
{
for(BluetoothDevice device:bt)
{
btarray[index]=device;
strings[index]=device.getName();
index++;
}
ArrayAdapter<String>arrayAdapter=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,strings);
listView.setAdapter(arrayAdapter);
}
}
});
//.........implement lisen button..............//
listen.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// .........object of server class for implement listen button........
ServerClass serverClass=new ServerClass();
serverClass.start();
}
});
//.........implement clickable list view............//
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
ClientClass clientClass=new ClientClass(btarray[i]);
clientClass.start();
status.setText("Connecting");
}
});
//............implement send button.............//
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String string=String.valueOf(write_msg.getText());
sendReceive.write(string.getBytes());
}
});
//................implement battery status button.................................//
battery.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
batterypercentage bp=new batterypercentage();
bp.start();
}
});
}
Handler handler=new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
switch(msg.what)
{
case STATE_LISTENING:
status.setText("Listening");
break;
case STATE_CONNECTING:
status.setText("Connecting");
break;
case STATE_CONNECTED:
status.setText("Connected");
break;
case STATE_CONNECTION_FAILED:
status.setText("Connection failed");
break;
case STATE_MESSAGE_RECEIVE:
byte[]readBuff= (byte[]) msg.obj;
String tempMsg=new String(readBuff,0,msg.arg1);
msg_box.setText(tempMsg);
break;
}
return true;
}
});
private void findViewByIds() {
listen=(Button) findViewById(R.id.button3);
listDevices=(Button) findViewById(R.id.button4);
status=(TextView) findViewById(R.id.textView2);
listView=(ListView) findViewById(R.id.listview);
send=(Button) findViewById(R.id.button);
msg_box=(TextView) findViewById(R.id.textView);
write_msg=(EditText) findViewById(R.id.editTextTextPersonName);
battery = (Button)findViewById(R.id.button2);
textview = (TextView)findViewById(R.id.textView3);
intentfilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
}
private class ServerClass extends Thread
{
private BluetoothServerSocket serverSocket;
@SuppressLint("MissingPermission")
public ServerClass()
{
try {
serverSocket=bluetoothAdapter.listenUsingRfcommWithServiceRecord(APP_NAME,MY_UUID);
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void run()
{
BluetoothSocket socket=null;
while (socket==null)
{
try {
Message message=Message.obtain();
message.what=STATE_CONNECTING;
handler.sendMessage(message);
socket=serverSocket.accept();
} catch (IOException e) {
Message message=Message.obtain();
message.what=STATE_CONNECTION_FAILED;
handler.sendMessage(message);
throw new RuntimeException(e);
}
if(socket!=null)
{
Message message=Message.obtain();
message.what=STATE_CONNECTED;
handler.sendMessage(message);
sendReceive=new SendReceive(socket);
sendReceive.start();
//..........new.............//
//bp=new batterypercentage(socket);
// bp.start();
break;
}
}
}
}
private class ClientClass extends Thread
{
private BluetoothDevice device;
private BluetoothSocket socket;
@SuppressLint("MissingPermission")
public ClientClass(BluetoothDevice device1)
{
device=device1;
try {
socket=device.createRfcommSocketToServiceRecord(MY_UUID);
}
catch (IOException e)
{
e.printStackTrace();
}
}
@SuppressLint("MissingPermission")
public void run()
{
try {
socket.connect();
Message message=Message.obtain();
message.what=STATE_CONNECTED;
handler.sendMessage(message);
sendReceive=new SendReceive(socket);
sendReceive.start();
}
catch (IOException e)
{
e.printStackTrace();
Message message=Message.obtain();
message.what=STATE_CONNECTION_FAILED;
handler.sendMessage(message);
}
}
}
private class SendReceive extends Thread
{
private final BluetoothSocket bluetoothSocket;
private final InputStream inputStream;
private final OutputStream outputStream;
public SendReceive(BluetoothSocket socket)
{
bluetoothSocket=socket;
InputStream tempIn=null;
OutputStream tempOut=null;
try {
tempIn=bluetoothSocket.getInputStream();
tempOut=bluetoothSocket.getOutputStream();
} catch (IOException e) {
throw new RuntimeException(e);
}
inputStream=tempIn;
outputStream=tempOut;
}
public void run()
{
byte[] buffer=new byte[1024];
int bytes;
try {
bytes=inputStream.read(buffer);
handler.obtainMessage(STATE_MESSAGE_RECEIVE,bytes,-1,buffer).sendToTarget();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public void write(byte [] bytes)
{
try {
outputStream.write(bytes);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
//.................................new........................................//
private class batterypercentage extends Thread
{
public void run()
{
//MainActivity.this.registerReceiver(broadcastreceiver,intentfilter);
/*try {
BluetoothDevice device = bluetoothAdapter.getRemoteDevice("Hardware address");
java.lang.reflect.Method method;
method = device.getClass().getMethod("getBatteryLevel");
int value = (int) method.invoke(device);
textview.setText(" Battery percentage: "+value+" %");
} catch (Exception ex) {
//result.error("invalid_argument", "'deviceId' argument is required to be string", null);
textview.setText("Exception occur");
//break;
}
*/
IntentFilter iFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = registerReceiver(null, iFilter);
int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL,
-1);
int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE,
-1);
int batteryLevel=(int)(((float)level / (float)scale) * 100.0f);
textview.setText(" Battery percentage: "+batteryLevel+" %");
}
}
}