I have succeeded in sending characters from a bletooth terminal App to Arduino and it worked.
Now, I am trying to send some characters to my arduino using my own app and I have programmed the HC05 Bluetooth module in slave mode so that it can only receive data. I used this code Reference code for bluetooth chat as a starting point so that later I can modify it according to my needs to only transfer characters from android to arduino.
But As soon as I hit send button after typing a character on my phone I get the following error in my logcat:
05-05 16:06:41.966 8042-8042/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.bluetoothtest, PID: 8042
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.android.bluetoothtest.BluetoothConnectionService.write(byte[])' on a null object reference
at com.example.android.bluetoothtest.MainActivity$7.onClick(MainActivity.java:227)
at android.view.View.performClick(View.java:5640)
at android.view.View$PerformClick.run(View.java:22455)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6165)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778)
Java File:
MainActivity.java
public class MainActivity extends AppCompatActivity implements
AdapterView.OnItemClickListener{
private static final String TAG = "MainActivity";
BluetoothAdapter mBluetoothAdapter;
Button btnEnableDisable_Discoverable;
BluetoothConnectionService mBluetoothConnection;
Button btnStartConnection;
Button btnSend;
EditText etSend;
private static final UUID MY_UUID_INSECURE =
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
BluetoothDevice mBTDevice;
public ArrayList<BluetoothDevice> mBTDevices = new ArrayList<>();
public DeviceListAdapter mDeviceListAdapter;
ListView lvNewDevices;
// Create a BroadcastReceiver for ACTION_FOUND
private final BroadcastReceiver mBroadcastReceiver1 = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (action.equals(mBluetoothAdapter.ACTION_STATE_CHANGED)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, mBluetoothAdapter.ERROR);
switch(state){
case BluetoothAdapter.STATE_OFF:
Log.d(TAG, "onReceive: STATE OFF");
break;
case BluetoothAdapter.STATE_TURNING_OFF:
Log.d(TAG, "mBroadcastReceiver1: STATE TURNING OFF");
break;
case BluetoothAdapter.STATE_ON:
Log.d(TAG, "mBroadcastReceiver1: STATE ON");
break;
case BluetoothAdapter.STATE_TURNING_ON:
Log.d(TAG, "mBroadcastReceiver1: STATE TURNING ON");
break;
}
}
}
};
/**
* Broadcast Receiver for changes made to bluetooth states such as:
* 1) Discoverability mode on/off or expire.
*/
private final BroadcastReceiver mBroadcastReceiver2 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED)) {
int mode = intent.getIntExtra(BluetoothAdapter.EXTRA_SCAN_MODE, BluetoothAdapter.ERROR);
switch (mode) {
//Device is in Discoverable Mode
case BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE:
Log.d(TAG, "mBroadcastReceiver2: Discoverability Enabled.");
break;
//Device not in discoverable mode
case BluetoothAdapter.SCAN_MODE_CONNECTABLE:
Log.d(TAG, "mBroadcastReceiver2: Discoverability Disabled. Able to receive connections.");
break;
case BluetoothAdapter.SCAN_MODE_NONE:
Log.d(TAG, "mBroadcastReceiver2: Discoverability Disabled. Not able to receive connections.");
break;
case BluetoothAdapter.STATE_CONNECTING:
Log.d(TAG, "mBroadcastReceiver2: Connecting....");
break;
case BluetoothAdapter.STATE_CONNECTED:
Log.d(TAG, "mBroadcastReceiver2: Connected.");
break;
}
}
}
};
/**
* Broadcast Receiver for listing devices that are not yet paired
* -Executed by btnDiscover() method.
*/
private BroadcastReceiver mBroadcastReceiver3 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
Log.d(TAG, "onReceive: ACTION FOUND.");
if (action.equals(BluetoothDevice.ACTION_FOUND)){
BluetoothDevice device = intent.getParcelableExtra (BluetoothDevice.EXTRA_DEVICE);
mBTDevices.add(device);
Log.d(TAG, "onReceive: " + device.getName() + ": " + device.getAddress());
mDeviceListAdapter = new DeviceListAdapter(context, R.layout.device_adapter_view, mBTDevices);
lvNewDevices.setAdapter(mDeviceListAdapter);
}
}
};
/**
* Broadcast Receiver that detects bond state changes (Pairing status changes)
*/
private final BroadcastReceiver mBroadcastReceiver4 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if(action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)){
BluetoothDevice mDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//3 cases:
//case1: bonded already
if (mDevice.getBondState() == BluetoothDevice.BOND_BONDED){
Log.d(TAG, "BroadcastReceiver: BOND_BONDED.");
//inside BroadcastReceiver4
mBTDevice = mDevice;
}
//case2: creating a bone
if (mDevice.getBondState() == BluetoothDevice.BOND_BONDING) {
Log.d(TAG, "BroadcastReceiver: BOND_BONDING.");
}
//case3: breaking a bond
if (mDevice.getBondState() == BluetoothDevice.BOND_NONE) {
Log.d(TAG, "BroadcastReceiver: BOND_NONE.");
}
}
}
};
#Override
protected void onDestroy() {
Log.d(TAG, "onDestroy: called.");
super.onDestroy();
unregisterReceiver(mBroadcastReceiver1);
unregisterReceiver(mBroadcastReceiver2);
unregisterReceiver(mBroadcastReceiver3);
unregisterReceiver(mBroadcastReceiver4);
//mBluetoothAdapter.cancelDiscovery();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnONOFF = (Button) findViewById(R.id.btnONOFF);
btnEnableDisable_Discoverable = (Button) findViewById(R.id.btnDiscoverable_on_off);
lvNewDevices = (ListView) findViewById(R.id.lvNewDevices);
mBTDevices = new ArrayList<>();
btnStartConnection = (Button) findViewById(R.id.btnStartConnection);
btnSend = (Button) findViewById(R.id.btnSend);
etSend = (EditText) findViewById(R.id.editText);
//Broadcasts when bond state changes (ie:pairing)
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
registerReceiver(mBroadcastReceiver4, filter);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
lvNewDevices.setOnItemClickListener(MainActivity.this);
btnONOFF.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "onClick: enabling/disabling bluetooth.");
enableDisableBT();
}
});
btnStartConnection.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startConnection();
}
});
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
byte[] bytes = etSend.getText().toString().getBytes(Charset.defaultCharset());
mBluetoothConnection.write(bytes);
}
});
}
//create method for starting connection
//***remember the conncction will fail and app will crash if you haven't
paired first
public void startConnection(){
startBTConnection(mBTDevice,MY_UUID_INSECURE);
}
/**
* starting chat service method
*/
public void startBTConnection(BluetoothDevice device, UUID uuid){
Log.d(TAG, "startBTConnection: Initializing RFCOM Bluetooth Connection.");
mBluetoothConnection.startClient(device,uuid);
}
public void enableDisableBT(){
if(mBluetoothAdapter == null){
Log.d(TAG, "enableDisableBT: Does not have BT capabilities.");
}
if(!mBluetoothAdapter.isEnabled()){
Log.d(TAG, "enableDisableBT: enabling BT.");
Intent enableBTIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivity(enableBTIntent);
IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mBroadcastReceiver1, BTIntent);
}
if(mBluetoothAdapter.isEnabled()){
Log.d(TAG, "enableDisableBT: disabling BT.");
mBluetoothAdapter.disable();
IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mBroadcastReceiver1, BTIntent);
}
}
public void btnEnableDisable_Discoverable(View view) {
Log.d(TAG, "btnEnableDisable_Discoverable: Making device discoverable for 300 seconds.");
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
IntentFilter intentFilter = new IntentFilter(mBluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
registerReceiver(mBroadcastReceiver2,intentFilter);
}
public void btnDiscover(View view) {
Log.d(TAG, "btnDiscover: Looking for unpaired devices.");
if(mBluetoothAdapter.isDiscovering()){
mBluetoothAdapter.cancelDiscovery();
Log.d(TAG, "btnDiscover: Canceling discovery.");
//check BT permissions in manifest
checkBTPermissions();
mBluetoothAdapter.startDiscovery();
IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
}
if(!mBluetoothAdapter.isDiscovering()){
//check BT permissions in manifest
checkBTPermissions();
mBluetoothAdapter.startDiscovery();
IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
}
}
/**
* This method is required for all devices running API23+
* Android must programmatically check the permissions for bluetooth. Putting the proper permissions
* in the manifest is not enough.
*
* NOTE: This will only execute on versions > LOLLIPOP because it is not needed otherwise.
*/
private void checkBTPermissions() {
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
int permissionCheck = this.checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATION");
permissionCheck += this.checkSelfPermission("Manifest.permission.ACCESS_COARSE_LOCATION");
if (permissionCheck != 0) {
this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1001); //Any number
}
}else{
Log.d(TAG, "checkBTPermissions: No need to check permissions. SDK version < LOLLIPOP.");
}
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//first cancel discovery because its very memory intensive.
mBluetoothAdapter.cancelDiscovery();
Log.d(TAG, "onItemClick: You Clicked on a device.");
String deviceName = mBTDevices.get(i).getName();
String deviceAddress = mBTDevices.get(i).getAddress();
Log.d(TAG, "onItemClick: deviceName = " + deviceName);
Log.d(TAG, "onItemClick: deviceAddress = " + deviceAddress);
//create the bond.
//NOTE: Requires API 17+? I think this is JellyBean
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2){
Log.d(TAG, "Trying to pair with " + deviceName);
mBTDevices.get(i).createBond();
mBTDevice = mBTDevices.get(i);
mBluetoothConnection = new BluetoothConnectionService(MainActivity.this);
}
}
}
Please help me, I can't seem to find a solution at all, I am a novice.
Thank You, Any help is greatly appreciated.
You MUST initialize BluetoothConnectionService before send anything to the Bluetooth
call this line before sending any data
....
mBluetoothConnection = new BluetoothConnectionService(MainActivity.this);
startConnection();
mBluetoothConnection.write(bytes);
and make sure that bytes are not null, try to print it in LOG
Related
I'm trying to disconnect from WiFi network inside the function disconnectWiFi() using removeNetworkSuggestions but the device still stays connected to the network. I tried passing a null ArrayList as well as a list that contains the NetworkSuggestion to the RemoveNetworkSuggestions function and neither of it fixed the problem.
public class SingleWifi extends AppCompatActivity {
private WifiManager wifiManager;
private Button disconnectButton;
List<WifiNetworkSuggestion> suggestionsList = new ArrayList<WifiNetworkSuggestion>();
#RequiresApi(api = Build.VERSION_CODES.Q)
#Override
protected void onCreate(Bundle savedInstanceState) {
wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_wifi);
String wifiSSID = getIntent().getStringExtra("wifiList");
connectToNetwork(wifiSSID);
disconnectButton = findViewById(R.id.disconnectBtn);
disconnectButton.setEnabled(false);
disconnectButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
disconnectWifi();
startActivity(new Intent(SingleWifi.this, MainActivity.class));
}
});
}
#RequiresApi(api = Build.VERSION_CODES.Q)
private void disconnectWifi() {
if(wifiManager != null) {
wifiManager.removeNetworkSuggestions(suggestionsList);
Toast.makeText(this,"Disconnect successful", Toast.LENGTH_SHORT).show();
}
}
#RequiresApi(api = Build.VERSION_CODES.Q)
private void connectToNetwork(String ssid) {
final WifiNetworkSuggestion suggestion = new WifiNetworkSuggestion.Builder()
.setSsid(ssid)
.setWpa2Passphrase("password")
.setIsAppInteractionRequired(true)
.build();
int statusCode = wifiManager.removeNetworkSuggestions(suggestionsList);
suggestionsList.add(suggestion);
final WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
int status = wifiManager.addNetworkSuggestions(suggestionsList);
if (status == WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS) {
Toast.makeText(this, "Connection success", Toast.LENGTH_LONG).show();
}
else if(status == WifiManager.STATUS_NETWORK_SUGGESTIONS_ERROR_ADD_DUPLICATE) {
Toast.makeText(this, "Already connected, update needed", Toast.LENGTH_LONG).show();
status = wifiManager.removeNetworkSuggestions(suggestionsList);
status = wifiManager.addNetworkSuggestions(suggestionsList);
}
final IntentFilter intentFilter = new IntentFilter(WifiManager.ACTION_WIFI_NETWORK_SUGGESTION_POST_CONNECTION);
final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override public void onReceive(Context context, Intent intent) {
if (!intent.getAction().equals(WifiManager.ACTION_WIFI_NETWORK_SUGGESTION_POST_CONNECTION)) {
return;
}
// Post connection
disconnectButton.setEnabled(true);
}
};
getApplicationContext().registerReceiver(broadcastReceiver, intentFilter);
}
}
removeNetworkSuggestions returns 0 so it does seem to produce the right output but does not seem to actually disconnect from the Internet.
I ended up going for a completely different implementation getting rid of the Wifinetworksuggestions API since this issue seem to be an unresolved bug as seen here: https://issuetracker.google.com/issues/140398818 So sadly, there is no fix for this issue as of now.
So im creating an app that scans for nearby bluetooth devices. Now this part works perfectly fine. the thing is, i want it to stop the discovery process after a time-period of 30 seconds. How do i achieve this?
Here is my code:
Broadcast Receiver:
private BroadcastReceiver mBroadcastReceiver3 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
Log.d(TAG,"onReceive: Action Found");
if(action.equals(BluetoothDevice.ACTION_FOUND))
{
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.d(TAG, "onReceive: " + device.getName() + ": " + device.getAddress());
if(device.getName() != null)
{
//System.out.println("JUNGE ER FINDET DOCH SOGAR DAS DEVICE WIESO ZEIGT ER DIE SCHEIßE NICHT AN");
//Jetzt wo keine nullpointer Exception mehr ent
if(device.getName().contains("HC")) {
mBTDevices.add(device);
mDeviceListAdapter = new DeviceListAdapter(context, R.layout.device_adapter_view, mBTDevices);
lvNewDevices.setAdapter((mDeviceListAdapter));
}
}
}
/*else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
Log.v(TAG, "Entered the Finished ");
System.out.println("Entered the Finished");
}
*/
}
} ;
Discover method (onclick when i press the discover button)
public void btnDiscover(View view)
{
Log.d(TAG,"btnDiscover: Looking for unpaired Devices");
if(mBluetoothAdapter.isDiscovering())
{
mBluetoothAdapter.cancelDiscovery();
Log.d(TAG,"btnDiscover:Cancelling discovery.");
//Checkt ob die Berechtigungen im Manifest für BT vorliegen
checkBTPermissions();
//start discovery again
mBluetoothAdapter.startDiscovery();
IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadcastReceiver3,discoverDevicesIntent);
}
if(!(mBluetoothAdapter.isDiscovering()))
{
//another check
checkBTPermissions();
mBluetoothAdapter.startDiscovery();
IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadcastReceiver3,discoverDevicesIntent);
}
}
Replace mBluetoothAdapter.startDiscovery(); with scann(mBluetoothAdapter,30);
void scann(final BluetoothAdapter mBluetoothAdapter, int seconds)
{
final long desired_miliseconds=seconds*1000;
final long start_mils=System.currentTimeMillis();
final Timer tm=new Timer();
tm.schedule(new TimerTask() {
#Override
public void run() {
if((System.currentTimeMillis()-start_mils)>=desired_miliseconds&&mBtAdapter.isDiscovering())
{
mBluetoothAdapter.cancelDiscovery();
tm.cancel();
}else if((System.currentTimeMillis()-start_mils)<desired_miliseconds&&!mBtAdapter.isDiscovering())
{
mBluetoothAdapter.startDiscovery();
}
}
},1000,1000);
}
My co-captain is annoying and broke my scouting app when he tried to add in Bluetooth.
Whenever I run this, I get an error that listview is null. The listview pops up a dialog and lists the discover-able devices that it can connect to. I have tried changing the id per instructions on another post and made sure there were discover-able devices available before running but nothing has worked. Please help! This is my
auto.java:
private final BroadcastReceiver mBroadcastReceiver1 = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (action.equals(mBluetoothAdapter.ACTION_STATE_CHANGED)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, mBluetoothAdapter.ERROR);
switch (state) {
case BluetoothAdapter.STATE_OFF:
Log.d(TAG, "onReceive: STATE OFF");
break;
case BluetoothAdapter.STATE_TURNING_OFF:
Log.d(TAG, "mBroadcastReceiver1: STATE TURNING OFF");
break;
case BluetoothAdapter.STATE_ON:
Log.d(TAG, "mBroadcastReceiver1: STATE ON");
break;
case BluetoothAdapter.STATE_TURNING_ON:
Log.d(TAG, "mBroadcastReceiver1: STATE TURNING ON");
break;
}
}
}
};
private final BroadcastReceiver mBroadcastReceiver2 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED)) {
int mode = intent.getIntExtra(BluetoothAdapter.EXTRA_SCAN_MODE, BluetoothAdapter.ERROR);
switch (mode) {
//Device is in Discoverable Mode
case BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE:
Log.d(TAG, "mBroadcastReceiver2: Discoverability Enabled.");
break;
//Device not in discoverable mode
case BluetoothAdapter.SCAN_MODE_CONNECTABLE:
Log.d(TAG, "mBroadcastReceiver2: Discoverability Disabled. Able to receive connections.");
break;
case BluetoothAdapter.SCAN_MODE_NONE:
Log.d(TAG, "mBroadcastReceiver2: Discoverability Disabled. Not able to receive connections.");
break;
case BluetoothAdapter.STATE_CONNECTING:
Log.d(TAG, "mBroadcastReceiver2: Connecting....");
break;
case BluetoothAdapter.STATE_CONNECTED:
Log.d(TAG, "mBroadcastReceiver2: Connected.");
break;
}
}
}
};
/**
* Broadcast Receiver that detects bond state changes (Pairing status changes)
*/
private BroadcastReceiver mBroadcastReceiver3 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
Log.d(TAG, "onReceive: ACTION FOUND.");
if (action.equals(BluetoothDevice.ACTION_FOUND)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
mBTDevices.add(device);
Log.d(TAG, "onReceive: " + device.getName() + ": " + device.getAddress());
mDeviceListAdapter = new DeviceListAdapter(context, R.layout.device_adapter_view, mBTDevices);
if(lvNewDevices == null)
{
Toast.makeText(getBaseContext(), " its null you fool and kaitlyn is the best", Toast.LENGTH_LONG).show();
}
else{
lvNewDevices.setAdapter(mDeviceListAdapter);
}
}
}
};
private final BroadcastReceiver mBroadcastReceiver4 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)) {
BluetoothDevice mDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//3 cases:
//case1: bonded already
if (mDevice.getBondState() == BluetoothDevice.BOND_BONDED) {
Log.d(TAG, "BroadcastReceiver: BND_BONDED.");
mBTDevice = mDevice;
}
//case2: creating a bone
if (mDevice.getBondState() == BluetoothDevice.BOND_BONDING) {
Log.d(TAG, "BroadcastReceiver: BOND_BONDING.");
}
//case3: breaking a bond
if (mDevice.getBondState() == BluetoothDevice.BOND_NONE) {
Log.d(TAG, "BroadcastReceiver: BOND_NONE.");
}
}
}
};
#Override
protected void onDestroy() {
Log.d(TAG, "onDestroy: called.");
super.onDestroy();
/*unregisterReceiver(mBroadcastReceiver1);
unregisterReceiver(mBroadcastReceiver2);
unregisterReceiver(mBroadcastReceiver3);
unregisterReceiver(mBroadcastReceiver4);
mBluetoothAdapter.cancelDiscovery();*/
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button next = (Button) findViewById(R.id.auto);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), MainActivity.class);
startActivityForResult(myIntent, 0);
}
});
Button btnONOFF = (Button) findViewById(R.id.btnONOFF);
btnEnableDisable_Discoverable = (Button) findViewById(R.id.btnDiscoverable_on_off);
mBTDevices = new ArrayList<>();
// btnSend = (Button) findViewById(R.id.btnSend);
// etSend = (EditText) findViewById(R.id.editText);
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
registerReceiver(mBroadcastReceiver4, filter);
connectbtn = (Button) findViewById(R.id.connctbtn);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
lvNewDevices.setOnItemClickListener(Auto.this);
autoGearVal = (EditText) ((findViewById(R.id.autoGears)));
autoBallVal = (EditText) ((findViewById(R.id.autoBalls)));
match = (EditText) ((findViewById(R.id.matches)));
teamVal = (EditText) ((findViewById(R.id.team)));
textView = (TextView) findViewById(R.id.textView);
saveVal = (Button) findViewById(R.id.save);
btnStartConnection = (Button) findViewById(R.id.btnStartConnection);
File dir = new File(path);
dir.mkdirs();
spinner = (Spinner) findViewById(R.id.spinner);
final CheckBox checkBox = (CheckBox) findViewById(R.id.checkbox);
connectbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final ConnectDialog connectDialog = new ConnectDialog();
View view = getLayoutInflater().inflate(R.layout.layout_dialog,null);
connectDialog.show(getSupportFragmentManager(), "Connect Dialog");
}
});
adapter = ArrayAdapter.createFromResource(this, R.array.Gear_Location, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
sideValue = String.valueOf(parent.getItemAtPosition(position));
Toast.makeText(getBaseContext(), parent.getItemAtPosition(position) + " selected", Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
lvNewDevices = (ListView) findViewById(R.id.lvNewDevices);
}
public void send(String etSend) {
byte[] bytes = etSend.getBytes(Charset.defaultCharset());
mBluetoothConnection.write(bytes);
}
public void enableBT(View view) {
Log.d(TAG, "onClick: enabling/disabling bluetooth.");
enableDisableBT();
}
public void startConnection(View view) {
startBTConnection(mBTDevice, MY_UUID_INSECURE);
}
public void startBTConnection(BluetoothDevice device, UUID uuid) {
Log.d(TAG, "startBTConnection:Initializing RFCOM Bluetooth Connection.");
mBluetoothConnection.startClient(device, uuid);
}
public void enableDisableBT() {
if (mBluetoothAdapter == null) {
Log.d(TAG, "enableDisableBT: Does not have BT capabilities.");
}
if (!mBluetoothAdapter.isEnabled()) {
Log.d(TAG, "enableDisableBT: enabling BT.");
Intent enableBTIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivity(enableBTIntent);
IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mBroadcastReceiver1, BTIntent);
}
if (mBluetoothAdapter.isEnabled()) {
Log.d(TAG, "enableDisableBT: disabling BT.");
mBluetoothAdapter.disable();
IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mBroadcastReceiver1, BTIntent);
}
}
public void btnEnableDisable_Discoverable(View view) {
Log.d(TAG, "btnEnableDisable_Discoverable: Making device discoverable for 300 seconds.");
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
IntentFilter intentFilter = new IntentFilter(mBluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
registerReceiver(mBroadcastReceiver2, intentFilter);
}
#RequiresApi(api = Build.VERSION_CODES.M)
public void btnDiscover(View view) {
Log.d(TAG, "btnDiscover: Looking for unpaired devices.");
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
Log.d(TAG, "btnDiscover: Canceling discovery.");
//check BT permissions in manifest
checkBTPermissions();
mBluetoothAdapter.startDiscovery();
IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
}
if (!mBluetoothAdapter.isDiscovering()) {
//check BT permissions in manifest
checkBTPermissions();
mBluetoothAdapter.startDiscovery();
IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
}
}
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//first cancel discovery because its very memory intensive.
mBluetoothAdapter.cancelDiscovery();
Log.d(TAG, "onItemClick: You Clicked on a device.");
String deviceName = mBTDevices.get(i).getName();
String deviceAddress = mBTDevices.get(i).getAddress();
Log.d(TAG, "onItemClick: deviceName = " + deviceName);
Log.d(TAG, "onItemClick: deviceAddress = " + deviceAddress);
//create the bond.
//NOTE: Requires API 17+? I think this is JellyBean
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2) {
Log.d(TAG, "Trying to pair with " + deviceName);
mBTDevices.get(i).createBond();
mBTDevice = mBTDevices.get(i);
mBluetoothConnection = new BluetoothConnectionService((Auto.this));
}
}
XML file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/lvNewDevices"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignTop="#+id/btnStartConnection"
android:layout_marginTop="11dp" />
"more nonsense about buttons"
</RelativeLayout>
error:
12-17 21:40:00.405 13246-13246/com.example.owen.scoutingapp2 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.owen.scoutingapp2, PID: 13246
java.lang.RuntimeException: Error receiving broadcast Intent { act=android.bluetooth.device.action.FOUND flg=0x10 bqHint=4 (has extras) } in com.example.owen.scoutingapp2.Auto$3#8132b08
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:1003)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at com.example.owen.scoutingapp2.Auto$3.onReceive(Auto.java:151)
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:993)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
auto.java.151:
lvNewDevices.setAdapter(mDeviceListAdapter);
I guess I found it. In this line you are trying to set the OnItemClickListener. But the ListView is not initialised yet:
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
registerReceiver(mBroadcastReceiver4, filter);
connectbtn = (Button) findViewById(R.id.connctbtn);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
lvNewDevices.setOnItemClickListener(Auto.this);
autoGearVal = (EditText) ((findViewById(R.id.autoGears)));
autoBallVal = (EditText) ((findViewById(R.id.autoBalls)));
You need to set the field 'lvNewDevices' before you do
lvNewDevices.setOnItemClickListener(Auto.this);
so move this line
lvNewDevices = (ListView) findViewById(R.id.lvNewDevices);
over this
lvNewDevices.setOnItemClickListener(Auto.this);
and try again.
Jojii
I wanted my Android to communicate with an Arduino using an USB host. I've tried many references but can't seem to send any char to my Arduino. I can detect my Arduino but sending char or string to it is frustrating. Here are my codes:
MainActivity.java
public class MainActivity extends AppCompatActivity {
UsbDevice device=null;
UsbManager manager=null;
PendingIntent mPermissionIntent;
UsbInterface intf;
UsbEndpoint endpoint;
UsbDeviceConnection connection;
Button find;
Button send;
TextView hello;
UsbManager mUsbManager;
private static final String ACTION_USB_PERMISSION =
"com.android.example.USB_PERMISSION";
private byte[] bytes;
private static int TIMEOUT = 0;
private boolean forceClaim = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
find = (Button) findViewById(R.id.Find);
send = (Button) findViewById(R.id.Send);
hello = (TextView) findViewById(R.id.hello);
find.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
hello.setText("");
checkInfo();
}
});
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(device!=null) {
intf = device.getInterface(0);
endpoint = intf.getEndpoint(0);
connection = mUsbManager.openDevice(device);
hello.setText("Kirim");
String kirim = "a";
bytes = kirim.getBytes();
connection.claimInterface(intf, forceClaim);
connection.bulkTransfer(endpoint, bytes, bytes.length, 0);
}
else{
Toast.makeText(MainActivity.this,"Device ==
null",Toast.LENGTH_SHORT);
}
}
});
private void checkInfo(){
manager=(UsbManager) getSystemService(Context.USB_SERVICE);
mPermissionIntent = PendingIntent.getBroadcast(this,0,new
Intent(ACTION_USB_PERMISSION),0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
registerReceiver(mUsbReceiver,filter);
HashMap<String,UsbDevice> deviceList = manager.getDeviceList();
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
String i="";
int j=0;
while(deviceIterator.hasNext()){
device = deviceIterator.next();
manager.requestPermission(device,mPermissionIntent);
i += "\n" + "DeviceID: " + device.getDeviceId() + "\n"
+ "DeviceName: " + device.getDeviceName() + "\n"
+ "DeviceClass: " + device.getDeviceClass() + " - "
+ "DeviceSubClass: " + device.getDeviceSubclass() + "\n"
+ "VendorID: " + device.getVendorId() + "\n"
+ "ProductID: " + device.getProductId() + "\n";
j++;
}
hello.setText(i);
}
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
UsbDevice device = (UsbDevice) intent
.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(
UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if (device != null) {
// call method to set up device communication
}
} else {
Log.d("ERROR", "permission denied for device " +
device);
}
}
}
}
};
}
I iterate using a find button and send using a send button. The iteration went just fine, but the sending didn't work. I needed to send just a character to the Arduino. My phone supports OTG and had been tested using other serial communication application to send char to Arduino and it works just fine.
Thanks in advance
using the usb serial lib in releases section at: https://github.com/felHR85/UsbSerial then import the lib and install dependencies as shown in the url. For solving the problem you can create a service class that handles usb related stuff (look at usb host android documentation for details: https://developer.android.com/guide/topics/connectivity/usb/host.html
as follows:
public class UsbService extends Service {
public static final String TAG = "UsbService";
public static final String ACTION_USB_READY = "com.felhr.connectivityservices.USB_READY";
public static final String ACTION_USB_ATTACHED = "android.hardware.usb.action.USB_DEVICE_ATTACHED";
public static final String ACTION_USB_DETACHED = "android.hardware.usb.action.USB_DEVICE_DETACHED";
public static final String ACTION_USB_NOT_SUPPORTED = "com.felhr.usbservice.USB_NOT_SUPPORTED";
public static final String ACTION_NO_USB = "com.felhr.usbservice.NO_USB";
public static final String ACTION_USB_PERMISSION_GRANTED = "com.felhr.usbservice.USB_PERMISSION_GRANTED";
public static final String ACTION_USB_PERMISSION_NOT_GRANTED = "com.felhr.usbservice.USB_PERMISSION_NOT_GRANTED";
public static final String ACTION_USB_DISCONNECTED = "com.felhr.usbservice.USB_DISCONNECTED";
public static final String ACTION_CDC_DRIVER_NOT_WORKING = "com.felhr.connectivityservices.ACTION_CDC_DRIVER_NOT_WORKING";
public static final String ACTION_USB_DEVICE_NOT_WORKING = "com.felhr.connectivityservices.ACTION_USB_DEVICE_NOT_WORKING";
public static final int MESSAGE_FROM_SERIAL_PORT = 0;
public static final int CTS_CHANGE = 1;
public static final int DSR_CHANGE = 2;
private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
private static final int BAUD_RATE = 9600; // BaudRate. Change this value if you need
public static boolean SERVICE_CONNECTED = false;
private IBinder binder = new UsbBinder();
private UsbService context;
private Handler mHandler;
private UsbManager usbManager;
private UsbDevice device;
private UsbDeviceConnection connection;
private UsbSerialDevice serialPort;
private boolean serialPortConnected;
/*
* Data received from serial port will be received here. Just populate onReceivedData with your code
* In this particular example. byte stream is converted to String and send to UI thread to
* be treated there.
*/
private UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() {
#Override
public void onReceivedData(byte[] arg0) {
try {
String data = new String(arg0, "UTF-8");
if (mHandler != null)
mHandler.obtainMessage(MESSAGE_FROM_SERIAL_PORT, data).sendToTarget();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
};
/*
* State changes in the CTS line will be received here
*/
private UsbSerialInterface.UsbCTSCallback ctsCallback = new UsbSerialInterface.UsbCTSCallback() {
#Override
public void onCTSChanged(boolean state) {
if(mHandler != null)
mHandler.obtainMessage(CTS_CHANGE).sendToTarget();
}
};
/*
* State changes in the DSR line will be received here
*/
private UsbSerialInterface.UsbDSRCallback dsrCallback = new UsbSerialInterface.UsbDSRCallback() {
#Override
public void onDSRChanged(boolean state) {
if(mHandler != null)
mHandler.obtainMessage(DSR_CHANGE).sendToTarget();
}
};
/*
* Different notifications from OS will be received here (USB attached, detached, permission responses...)
* About BroadcastReceiver: http://developer.android.com/reference/android/content/BroadcastReceiver.html
*/
private final BroadcastReceiver usbReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
if (arg1.getAction().equals(ACTION_USB_PERMISSION)) {
boolean granted = arg1.getExtras().getBoolean(UsbManager.EXTRA_PERMISSION_GRANTED);
if (granted) // User accepted our USB connection. Try to open the device as a serial port
{
Intent intent = new Intent(ACTION_USB_PERMISSION_GRANTED);
arg0.sendBroadcast(intent);
connection = usbManager.openDevice(device);
new ConnectionThread().start();
} else // User not accepted our USB connection. Send an Intent to the Main Activity
{
Intent intent = new Intent(ACTION_USB_PERMISSION_NOT_GRANTED);
arg0.sendBroadcast(intent);
}
} else if (arg1.getAction().equals(ACTION_USB_ATTACHED)) {
if (!serialPortConnected)
findSerialPortDevice(); // A USB device has been attached. Try to open it as a Serial port
} else if (arg1.getAction().equals(ACTION_USB_DETACHED)) {
// Usb device was disconnected. send an intent to the Main Activity
Intent intent = new Intent(ACTION_USB_DISCONNECTED);
arg0.sendBroadcast(intent);
if (serialPortConnected) {
serialPort.close();
}
serialPortConnected = false;
}
}
};
/*
* onCreate will be executed when service is started. It configures an IntentFilter to listen for
* incoming Intents (USB ATTACHED, USB DETACHED...) and it tries to open a serial port.
*/
#Override
public void onCreate() {
this.context=this;
serialPortConnected = false;
UsbService.SERVICE_CONNECTED = true;
setFilter();
usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
findSerialPortDevice();
}
/* MUST READ about services
* http://developer.android.com/guide/components/services.html
* http://developer.android.com/guide/components/bound-services.html
*/
#Override
public IBinder onBind(Intent intent) {
return binder;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
serialPort.close();
unregisterReceiver(usbReceiver);
UsbService.SERVICE_CONNECTED = false;
}
/*
* This function will be called from MainActivity to write data through Serial Port
*/
public void write(byte[] data) {
if (serialPort != null)
serialPort.write(data);
}
public void setHandler(Handler mHandler) {
this.mHandler = mHandler;
}
private void findSerialPortDevice() {
// This snippet will try to open the first encountered usb device connected, excluding usb root hubs
HashMap<String, UsbDevice> usbDevices = usbManager.getDeviceList();
if (!usbDevices.isEmpty()) {
// first, dump the hashmap for diagnostic purposes
for (Map.Entry<String, UsbDevice> entry : usbDevices.entrySet()) {
device = entry.getValue();
Log.d(TAG, String.format("USBDevice.HashMap (vid:pid) (%X:%X)-%b class:%X:%X name:%s",
device.getVendorId(), device.getProductId(),
UsbSerialDevice.isSupported(device),
device.getDeviceClass(), device.getDeviceSubclass(),
device.getDeviceName()));
}
for (Map.Entry<String, UsbDevice> entry : usbDevices.entrySet()) {
device = entry.getValue();
int deviceVID = device.getVendorId();
int devicePID = device.getProductId();
// if (deviceVID != 0x1d6b && (devicePID != 0x0001 && devicePID != 0x0002 && devicePID != 0x0003) && deviceVID != 0x5c6 && devicePID != 0x904c) {
if (UsbSerialDevice.isSupported(device)) {
// There is a supported device connected - request permission to access it.
requestUserPermission();
break;
} else {
connection = null;
device = null;
}
}
if (device==null) {
// There are no USB devices connected (but usb host were listed). Send an intent to MainActivity.
Intent intent = new Intent(ACTION_NO_USB);
sendBroadcast(intent);
}
} else {
Log.d(TAG, "findSerialPortDevice() usbManager returned empty device list." );
// There is no USB devices connected. Send an intent to MainActivity
Intent intent = new Intent(ACTION_NO_USB);
sendBroadcast(intent);
}
}
private void setFilter() {
IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_USB_PERMISSION);
filter.addAction(ACTION_USB_DETACHED);
filter.addAction(ACTION_USB_ATTACHED);
registerReceiver(usbReceiver, filter);
}
/*
* Request user permission. The response will be received in the BroadcastReceiver
*/
private void requestUserPermission() {
Log.d(TAG, String.format("requestUserPermission(%X:%X)", device.getVendorId(), device.getProductId() ) );
PendingIntent mPendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
usbManager.requestPermission(device, mPendingIntent);
}
public class UsbBinder extends Binder {
public UsbService getService() {
return UsbService.this;
}
}
/*
* A simple thread to open a serial port.
* Although it should be a fast operation. moving usb operations away from UI thread is a good thing.
*/
private class ConnectionThread extends Thread {
#Override
public void run() {
serialPort = UsbSerialDevice.createUsbSerialDevice(device, connection);
if (serialPort != null) {
if (serialPort.open()) {
serialPortConnected = true;
serialPort.setBaudRate(BAUD_RATE);
serialPort.setDataBits(UsbSerialInterface.DATA_BITS_8);
serialPort.setStopBits(UsbSerialInterface.STOP_BITS_1);
serialPort.setParity(UsbSerialInterface.PARITY_NONE);
/**
* Current flow control Options:
* UsbSerialInterface.FLOW_CONTROL_OFF
* UsbSerialInterface.FLOW_CONTROL_RTS_CTS only for CP2102 and FT232
* UsbSerialInterface.FLOW_CONTROL_DSR_DTR only for CP2102 and FT232
*/
serialPort.setFlowControl(UsbSerialInterface.FLOW_CONTROL_OFF);
serialPort.read(mCallback);
serialPort.getCTS(ctsCallback);
serialPort.getDSR(dsrCallback);
//
// Some Arduinos would need some sleep because firmware wait some time to know whether a new sketch is going
// to be uploaded or not
//Thread.sleep(2000); // sleep some. YMMV with different chips.
// Everything went as expected. Send an intent to MainActivity
Intent intent = new Intent(ACTION_USB_READY);
context.sendBroadcast(intent);
} else {
// Serial port could not be opened, maybe an I/O error or if CDC driver was chosen, it does not really fit
// Send an Intent to Main Activity
if (serialPort instanceof CDCSerialDevice) {
Intent intent = new Intent(ACTION_CDC_DRIVER_NOT_WORKING);
context.sendBroadcast(intent);
} else {
Intent intent = new Intent(ACTION_USB_DEVICE_NOT_WORKING);
context.sendBroadcast(intent);
}
}
} else {
// No driver for given device, even generic CDC driver could not be loaded
Intent intent = new Intent(ACTION_USB_NOT_SUPPORTED);
context.sendBroadcast(intent);
}
}
}
}
then in your main activity put this snippets:
java
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
switch (intent.getAction()) {
case UsbService.ACTION_USB_PERMISSION_GRANTED: // USB PERMISSION GRANTED
Toast.makeText(context, "USB Ready", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_PERMISSION_NOT_GRANTED: // USB PERMISSION NOT GRANTED
Toast.makeText(context, "USB Permission not granted", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_NO_USB: // NO USB CONNECTED
Toast.makeText(context, "No USB connected", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_DISCONNECTED: // USB DISCONNECTED
Toast.makeText(context, "USB disconnected", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_NOT_SUPPORTED: // USB NOT SUPPORTED
Toast.makeText(context, "USB device not supported", Toast.LENGTH_SHORT).show();
break;
}
}
};
private UsbService usbService;
public TextView display;
private EditText editText;
private MyHandler mHandler;
private final ServiceConnection usbConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
usbService = ((UsbService.UsbBinder) arg1).getService();
usbService.setHandler(mHandler);
// Toast.makeText(getApplicationContext(),"dentro on service connected " + usbService, Toast.LENGTH_SHORT).show();
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
usbService = null;
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.operacion);
mHandler = new MyHandler(this);
// your stuff here
#Override
public void onResume() {
super.onResume();
// Toast.makeText(getApplicationContext(),"on resume ", Toast.LENGTH_SHORT).show();
setFilters(); // Start listening notifications from UsbService
startService(UsbService.class, usbConnection, null); // Start UsbService(if it was not started before) and Bind it
// Toast.makeText(getApplicationContext(),"despues de start y weas ", Toast.LENGTH_SHORT).show();
}
#Override
public void onPause() {
super.onPause();
unregisterReceiver(mUsbReceiver);
unbindService(usbConnection);
}
private void startService(Class<?> service, ServiceConnection serviceConnection, Bundle extras) {
// Toast.makeText(getApplicationContext(),"start1", Toast.LENGTH_SHORT).show();
if (!UsbService.SERVICE_CONNECTED) {
Intent startService = new Intent(this, service);
if (extras != null && !extras.isEmpty()) {
Set<String> keys = extras.keySet();
for (String key : keys) {
String extra = extras.getString(key);
startService.putExtra(key, extra);
}
}
startService(startService);
// Toast.makeText(getApplicationContext(),"dp metodo start", Toast.LENGTH_SHORT).show();
}
Intent bindingIntent = new Intent(this, service);
bindService(bindingIntent, serviceConnection, Context.BIND_AUTO_CREATE);
}
private void setFilters() {
IntentFilter filter = new IntentFilter();
filter.addAction(UsbService.ACTION_USB_PERMISSION_GRANTED);
filter.addAction(UsbService.ACTION_NO_USB);
filter.addAction(UsbService.ACTION_USB_DISCONNECTED);
filter.addAction(UsbService.ACTION_USB_NOT_SUPPORTED);
filter.addAction(UsbService.ACTION_USB_PERMISSION_NOT_GRANTED);
registerReceiver(mUsbReceiver, filter);
}
public void getCurrentTimeUsingDate(){
String currentDateTimeString2 = DateFormat.getDateInstance().format(new Date());
TextView txtView3 = (TextView) findViewById(R.id.textView4);
txtView3.setText(""+currentDateTimeString2);
}
private static class MyHandler extends Handler {
private final WeakReference<Pag4> mActivity;
public MyHandler(Pag4 activity) {
mActivity = new WeakReference<>(activity);
}
Integer conta = 0;
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case UsbService.MESSAGE_FROM_SERIAL_PORT:
String data = (String) msg.obj;
conta++;
break;
case UsbService.CTS_CHANGE:
Toast.makeText(mActivity.get(), "CTS_CHANGE",Toast.LENGTH_LONG).show();
break;
case UsbService.DSR_CHANGE:
Toast.makeText(mActivity.get(), "DSR_CHANGE",Toast.LENGTH_LONG).show();
break;
}
}
}
}
you make a button (btn3 in the example) and then add the listener as follows:
java
bt3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
String auxi2="1"; // put whatever you need to send here
if (!auxi2.equals("")) {
String data = auxi2;
if (usbService != null) { // if UsbService was correctly binded, Send data
usbService.write(data.getBytes());
// Toast.makeText(getApplicationContext(),"auxi2 escrito"+ auxi2, Toast.LENGTH_SHORT).show();
}
}
}
});
Hope is clear, I assume you know how to import libs, and make a button, put the permission in manifiest, dependencies. Details about this in android doc link already posted upper in my answer.
I'm trying to make a java android application with bluetooth and I have some troubles to show the result after search all the devices paired or not in a listview and to connect to a device, in my code I'm trying to connect with a device using the mac addres of it, but it doesn't work and I show the result in a textview, any idea????
Thank you.
public class Conexion_bluetooth extends Activity {
TextView out;
// Debugging
private static final UUID MY_UUID = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
private BluetoothAdapter mBluetoothAdapter = null;
private BluetoothSocket mmSocket=null;
private static final String TAG = "BluetoothChat";
private static final boolean D = true;
private static final int REQUEST_ENABLE_BT = 3;
private BluetoothAdapter mBluetoothAdapter = null;
ListView lstDispositivos;
ListView lstDispositivos2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(D) Log.e(TAG, "+++ ON CREATE +++");
// Set up the window layout
setContentView(R.layout.activity_conexion_bluetooth);
// Get local Bluetooth adapter
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// If the adapter is null, then Bluetooth is not supported
if (mBluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
return;
}
}
#Override
//Comprueba que el bluetooth esta conectado
public void onStart() {
super.onStart();
if(D) Log.e(TAG, "++ ON START ++");
// Si el bluetooth no está activado muestra un mensaje solicitando permiso para activarle
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
Toast.makeText(this, "conectando...", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(this, "conectado", Toast.LENGTH_LONG).show();
}
}
public void buscar(View view){
//TextView dispositivos = (TextView) findViewById(R.id.dispositivos);
if (mBluetoothAdapter.isDiscovering()) {
Toast.makeText(this, "\nCancel discovery...", Toast.LENGTH_LONG).show();
mBluetoothAdapter.cancelDiscovery();
}else{
Toast.makeText(this, "\nStarting discovery...", Toast.LENGTH_LONG).show();
//mBluetoothAdapter.
mBluetoothAdapter.startDiscovery();
Toast.makeText(this, "\nDone with discovery...", Toast.LENGTH_LONG).show();
}
final TextView dispositivos = (TextView) findViewById(R.id.dispositivos);
String dispositivo[] = new String[]{};
final Vector<String> dispositivosBT = new Vector<String>();
//final int dispEncontrados=0;
// Create a BroadcastReceiver for ACTION_FOUND
final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
//String dispositivosBT[] = new String[]{};
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
//setContentView(R.layout.dispositivos_bluetooth);//determinamos que al iniciar la aplicacion aparezca esta pantalla
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the name and address to an array adapter to show in a ListView
dispositivos.append("\n" + device.getName() + "\n" + device.getAddress());
}
}
};
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
//dispositivosBT = new String[dispositivos.length()];
//final ArrayAdapter<String> adaptador = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, dispositivosBT);
final TextView dispositivosSincronizados = (TextView) findViewById(R.id.dispositivosSincronizados);
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
// If there are paired devices
if (pairedDevices.size() > 0) {
// Loop through paired devices
for (BluetoothDevice device : pairedDevices) {
// Add the name and address to an array adapter to show in a ListView
dispositivosSincronizados.append("\n" + device.getName() + "\n" + device.getAddress());
}
}
}
public void paraBusqueda(View view){
if (mBluetoothAdapter.isDiscovering()) {
Toast.makeText(this, "\nCancel discovery...", Toast.LENGTH_LONG).show();
mBluetoothAdapter.cancelDiscovery();
}else{
Toast.makeText(this, "\nis not discovering...", Toast.LENGTH_LONG).show();
}
}
public void pararBluetooth(){
if (mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_conexion_bluetooth, menu);
return true;
}
public void conectar(View view){
String address = "00:15:83:07:d1:14";
device = mBluetoothAdapter.getRemoteDevice(address);
Toast.makeText(getApplicationContext(), "cONNECTING", Toast.LENGTH_SHORT).show();
try {
mmSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
mmSocket.connect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Using AsyncTask we can make Bluetooth Connection.
public class BluetoothConnectionActivity extends Activity {
private Button connectButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
connectButton = (Button) findViewById(R.id.connectButton);
connectButton.setOnclickListener(View.onClickListener() {
#Override
public void onClick(View v) {
String address = "00:15:83:07:d1:14";
new ConnectAsyncTask(address).execute();
}
});
}
private class ConnectAsyncTask extends AsyncTask<String, Void, Boolean> {
#Override
protected void onPostExecute(Boolean isConnected) {
Toast.makeText(getApplicationContext(), "Connecting...",
Toast.LENGTH_SHORT).show();
}
#Override
protected Boolean doInBackground(String... param) {
BluetoothDevice device = BluetoothAdapter
.getDefaultBluetoothAdapter().getRemoteDevice(param[0]);
try {
BluetoothSocket mmSocket = device
.createRfcommSocketToServiceRecord(MY_UUID);
mmSocket.connect();
} catch (Exception e) {
e.printStackTrace();
Log.d("BluetoothConnectivity", "ERROR:" + e.getMessage());
return false;
}
return true;
}
#Override
protected void onPostExecute(Boolean isConnected) {
if (isConnected) {
Toast.makeText(getApplicationContext(), "Connected",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Failed to connected",
Toast.LENGTH_SHORT).show();
}
}
}
}
Regards
Srini
Recently we played with bluetooth for some application. i am not an expert in android. You can try the following things.
1. check your bluetooth device's UUID
2. Connecting to Bluetooth need to be in a separate thread
3. Run app in debug mode and check the Exception or error.
Refer the android bluetooth documentation
If you still have the same problem look at Bluetooth sample application, otherwise i will send the code which i had written for making connection.
regards
srini