Created
May 18, 2024 01:15
-
-
Save Lerie82/6c38f3d10b7bec4eff125f1f25bd993a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.bluetooth.BluetoothDevice; | |
import android.os.Bundle; | |
import android.view.View; | |
import android.widget.ArrayAdapter; | |
import android.widget.Button; | |
import android.widget.ListView; | |
import android.widget.Toast; | |
import java.util.ArrayList; | |
import java.util.List; | |
public class BluetoothActivity extends AppCompatActivity implements BluetoothHelper.BluetoothListener { | |
private ListView listView; | |
private Button btnScan; | |
private List<BluetoothDevice> deviceList; | |
private ArrayAdapter<String> adapter; | |
private BluetoothHelper bluetoothHelper; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_bluetooth); | |
listView = findViewById(R.id.listView); | |
btnScan = findViewById(R.id.btnScan); | |
deviceList = new ArrayList<>(); | |
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1); | |
listView.setAdapter(adapter); | |
bluetoothHelper = new BluetoothHelper(this); | |
bluetoothHelper.setListener(this); | |
btnScan.setOnClickListener(new View.OnClickListener() { | |
@Override | |
public void onClick(View v) { | |
if (btnScan.getText().toString().equals("Scan")) { | |
deviceList.clear(); | |
adapter.clear(); | |
bluetoothHelper.startDiscovery(); | |
btnScan.setText("Stop"); | |
Toast.makeText(BluetoothActivity.this, "Scanning...", Toast.LENGTH_SHORT).show(); | |
} else { | |
bluetoothHelper.stopDiscovery(); | |
btnScan.setText("Scan"); | |
Toast.makeText(BluetoothActivity.this, "Scan Stopped", Toast.LENGTH_SHORT).show(); | |
} | |
} | |
}); | |
} | |
@Override | |
public void onDeviceFound(List<BluetoothDevice> devices) { | |
for (BluetoothDevice device : devices) { | |
adapter.add(device.getName() + " - " + device.getAddress()); | |
} | |
} | |
@Override | |
protected void onDestroy() { | |
super.onDestroy(); | |
bluetoothHelper.stopDiscovery(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment