I'm starting to develop an app to communicate with an arduino device through bluetooth.
I'm initializing the bt adapter with
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
The problem is that btAdapter returns null,
txt_status.append("\nAdapter " + btAdapter);
Its like the device hasn't got a bluetooth adapter, which is not my case.
Any ideas? I'm searching around with no luck.
Thanks, Federico
Complete code of the activity:
package com.voice.benz.instaurentremote;
import android.bluetooth.*;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.Switch;
import android.widget.TextView;
import android.bluetooth.BluetoothAdapter;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.content.Intent;
import android.widget.Toast;
import android.widget.ArrayAdapter;
import java.util.Set;
import android.content.Context;
import android.util.Log;
public class bluetooth extends ActionBarActivity {
private TextView bluetoothPaired;
private TextView txt_status;
private BluetoothAdapter btAdapter;
private ListView listview_devices;
private Set<BluetoothDevice> dispositivi;
private ArrayAdapter<String> adapter = null;
private static final int BLUETOOTH_ON=1000;
private TextView txt_bluetoothStatus;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth);
txt_bluetoothStatus = (TextView) findViewById(R.id.txt_bluetooth_status);
txt_status = (TextView) findViewById(R.id.txt_status);
listview_devices = (ListView) findViewById(R.id.listView_devices);
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1);
listview_devices.setAdapter(adapter);
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
if (btAdapter == null)
{
System.out.println ("Bluetooth non supportato");
}
else
{
System.out.println ("Bluetooth inizializzato");
}
if (btAdapter.isEnabled())
{
// Il bluetooth è già attivato
String mydeviceaddress = btAdapter.getAddress();
String mydevicename = btAdapter.getName();
String status = mydevicename + " : " + mydeviceaddress;
txt_bluetoothStatus.setText(status);
}
else
{
// Attiva bluetooth
}
}
public void attivaBluetooth (View view) {
if (btAdapter != null && !btAdapter.isEnabled())
{
Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, BLUETOOTH_ON);
}
//else
//load();
}
public void disattivaBluetooth (View view)
{
if (btAdapter.isEnabled())
{
btAdapter.disable();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==BLUETOOTH_ON && resultCode==RESULT_OK)
{
load();
}
}
private void load()
{
dispositivi = btAdapter.getBondedDevices();
adapter.clear();
for(BluetoothDevice bt : dispositivi)
adapter.add(bt.getName());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_bluetooth, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Replace your code line,
#Override
protected void onCreate(Bundle savedInstanceState) {
...
...
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
with
btAdapter = BluetoothAdapter.getDefaultAdapter();
its all about local variable and Class level variable.
You are getting Bluetooth adapter in onCreate as local variable and accessing outside of onCreate() the class level variable which is not initialized and always remain null.
Related
I am trying to pass my BluetoothAdapter BA to another activity using putExtra(String str, Bundle bundle) method of Intent, but the compiler of my Android studio shows an error in that. When I hover over a red curved line that appears under the method, it shows me
Can't resolve method 'putExtra(java.lang.String, android.bluetooth.BluetoothAdapter)'
This is what I'm talking about
If I understand it correctly, Bundle is basically any object, hence there shouldn't be any problem passing a BluetoothAdapter to another activity via putExtra.
This is my MainActivity.java
package vertex2016.mvjce.edu.bluealert;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import static java.lang.Thread.sleep;
public class MainActivity extends AppCompatActivity {
public BluetoothAdapter BA = BluetoothAdapter.getDefaultAdapter();
private int REQ_CODE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void connect(View v)
{
if(BA == null)
Toast.makeText(MainActivity.this, "System Doesn't Support Bluetooth", Toast.LENGTH_SHORT).show();
else if(!BA.isEnabled())
{
Intent enableBT = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBT, REQ_CODE);
}
else {
Toast.makeText(MainActivity.this, "ALREADY ON!!", Toast.LENGTH_SHORT).show();
searchBTDevices();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode!=RESULT_CANCELED) {
Toast.makeText(MainActivity.this, "TURNED ON!", Toast.LENGTH_SHORT).show();
searchBTDevices();
}
else
Toast.makeText(MainActivity.this,"FAILED TO ENABLE BLUETOOTH", Toast.LENGTH_LONG).show();
}
public void searchBTDevices()
{
Thread searchThread = new Thread() {
#Override
public void run() {
Intent searchBT = new Intent(getApplicationContext(), SearchBTDevice.class);
searchBT.putExtra("BT_ADAPTER", BA);
startActivity(searchBT);
}
};
searchThread.start();
}
}
And this is my SearchBTDevices.java that is supposed to receive the extra info.
package vertex2016.mvjce.edu.bluealert;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
public class SearchBTDevice extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_btdevice);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
Where am I going wrong?
Thank you for your time!!
Intents can only be used to pass primitives, Parcelable and Serializable objects. BluetoothAdapter does not support either of these and it can't be built from primitives, so you can't create a Parcelable that will help you.
So when faced with a situation like this, you need to pass in parameters that the Activty can use to re-build or retrieve the object necessary for execution.
If you need the ability to use different BluetoothAdapters, then you need to tell SearchBTDevices which BluetoothAdapter you want to check and have SearchBTDevices retrieve the adapter itself. For example,
public class SearchBTDevices extends Activity {
public static final String PARAM_ADAPTER_TYPE = "adapterType";
public static final int ADAPTER_DEFAULT = 1;
public static final int ADAPTER_ALTERNATE = 2;
private BluetoothAdapter mAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int adapterType = getIntent().getIntExtra(PARAM_ADAPTER_TYPE, ADAPTER_DEFAULT);
switch(adapterType) {
case PARAM_ADAPTER_ALTERNATE:
mAdapter = getAlternateAdapter(); // This is whatever method you need to get it.
break;
default:
mAdapter = getDefaultAdapter();
}
}
}
Now, whenever you need to start this Activity, just do this:
Intent intent = new Intent(getContext(), SearchBTDevices.class);
intent.putExtra(SearchBTDevices.PARAM_ADAPTER_TYPE, SearchBTDevices.ADAPTER_ALTERNATE);
startActivity(intent);
So when SearchBTDevices starts, it will pull the parameter from the intent and know that it needs to use the alternate adapter.
I'm doing an app which uses bluetooth communication.
At first, I'm trying to get a list of all bluetooth devices detectable by the device.
I've managed to load in a listview all the paired devices, but i'm unable to list un-paired devices, I've found some tutorials but I'm a bit confused as I'm a bit new to android development & bluetooth communication.
So i need to find every bluetooth device in range, and I don't know how to do it (lazy)
Here is the (edited) code:
package com.voice.benz.instaurentremote;
import android.bluetooth.*;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.widget.ArrayAdapter;
import java.util.Set;
import android.content.Context;
import android.content.BroadcastReceiver;
import android.view.Window;
import android.app.Activity;
import android.content.IntentFilter;
import android.util.Log;
import android.widget.Button;
import android.view.View.OnClickListener;
import android.widget.AdapterView.OnItemClickListener;
import java.util.ArrayList;
public class bluetooth extends ActionBarActivity {
private TextView bluetoothPaired;
private TextView txt_status;
private BluetoothAdapter btAdapter;
private ListView newdevices_listview;
private Set<BluetoothDevice>pairedDevices;
private ArrayAdapter<String> adapter = null;
private static final int BLUETOOTH_ON = 1000;
private static final int REQUEST_ENABLE_BT = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth);
// Initialize the button to perform device discovery
txt_status = (TextView) findViewById(R.id.txt_status);
newdevices_listview = (ListView)findViewById(R.id.newdevices_listview);
adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1);
newdevices_listview.setAdapter(adapter);
// Initialize adapter
btAdapter = BluetoothAdapter.getDefaultAdapter();
// Register for broadcasts when a device is discovered
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(mReceiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(mReceiver, filter);
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
//discovery starts, we can show progress dialog or perform other tasks
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
//discovery finishes, dismis progress dialog
} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
//bluetooth device found
BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
txt_status.setText("Found device " + device.getName());
adapter.add(device.getName() + "\n" + device.getAddress());
}
}
};
public void attivaBluetooth (View view) {
if (!btAdapter.isEnabled()) {
Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 1);
}
}
public void cercaDispositivi (View view)
{
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter);
btAdapter.startDiscovery();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(mReceiver);
}
public void disattivaBluetooth (View view)
{
if (btAdapter.isEnabled())
{
btAdapter.disable();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_bluetooth, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
You don't seem to be registering your BroadcastReceiver myBluetoothReceiver anywhere. If you do that in onResume() or onCreate you'll probably have more luck. :)
I am new to android development. I need a solution for the new app I am developing which takes voice input and gives output in voice by mapping with a mapping database. Current program takes voice input with onlick on button . I need a soultion which can take voice input without clicking of any button simliar to Talking Tom application . Here is my code.My main code is in speakToMe which is method called on onclick & onActivityResult
package com.example.secondprog;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Locale;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Build;
import com.example.secondprog.*;
//import com.example.secondprog.DatabaseHelper;
public class MainActivity extends Activity {
private static final int VOICE_RECOGNITION_REQUEST = 0;
//private static final int VOICE_RECOGNITION_REQUEST = 0x10101;
TextToSpeech ttobj;
String resulttxt ;
TestDBClass db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new TestDBClass(this, null, null, 1);
try {
db.loadWords();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ttobj=new TextToSpeech(getApplicationContext(),
new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR){
ttobj.setLanguage(Locale.UK);
Toast.makeText(getApplicationContext(), "No error",
Toast.LENGTH_LONG).show();
}
}
});
//DatabaseHelper db = DatabaseHelper(this);
//dbdtls dbdtlsresult = new dbdtls();
//String message3 = db.getdtls("how are");
//String output = dbdtlsresult.new_name();
//EditText editText = (EditText) findViewById(R.id.edit_message);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
public void sendMessage(View view) {
EditText editText = (EditText) findViewById(R.id.edit_message);
String txt = editText.getText().toString();
// Toast.makeText(getApplicationContext(), txt.toUpperCase(),
// Toast.LENGTH_LONG).show();
DictonaryDAO dictonaryDAO =
db.findname(txt.toUpperCase());
if (dictonaryDAO != null) {
resulttxt = String.valueOf(dictonaryDAO.getnewname());
Toast.makeText(getApplicationContext(), resulttxt.toUpperCase(),
Toast.LENGTH_LONG).show();
}
ttobj.speak(resulttxt, TextToSpeech.QUEUE_FLUSH, null);
}
/*#Override
public void onPause(){
if(ttobj !=null){
ttobj.stop();
ttobj.shutdown();
}
super.onPause();
}
*/
**public void speakToMe(View view) {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
"Please speak slowly and enunciate clearly.");
startActivityForResult(intent, VOICE_RECOGNITION_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == VOICE_RECOGNITION_REQUEST && resultCode == RESULT_OK) {
ArrayList<String> matches = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
// TextView textView = (TextView) findViewById(R.id.speech_io_text);
String firstMatch = matches.get(0);
// textView.setText(firstMatch);
DictonaryDAO dictonaryDAO =
db.findname(firstMatch.toUpperCase());
if (dictonaryDAO != null) {
resulttxt = String.valueOf(dictonaryDAO.getnewname());
Toast.makeText(getApplicationContext(), resulttxt.toUpperCase(),
Toast.LENGTH_LONG).show();
ttobj.speak(resulttxt, TextToSpeech.QUEUE_FLUSH, null);
}
}
}**
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
Voice Recognition not working for talking tom app so you try to use noise detection with sound meter. below here link for voice/ noise detection with audio recording without click.
http://androidexample.com/Detect_Noise_Or_Blow_Sound_-_Set_Sound_Frequency_Thersold/index.php?view=article_discription&aid=108&aaid=130
Please change SoundMeter.java File
mRecorder.setOutputFile(Environment.getExternalStorageDirectory().
getAbsolutePath() + "/test.3ggp");
I am developing an application where I have to connect to a Bluetooth device.
When I click the btn_discover Button, it will call BroadcastReceiver and scan the new bluetooth device and show on the TextView.
When I use the TextView, I can see the bluetooth device on Textview.
And now I want to change the TextView to ListView.
But it always crashes. When in BroadcastReceiver's onReceive(), I write:
newDevicelistArrayAdapter.add(device.getName());
This is my Java Code:
package com.example.bttest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;
import com.example.bttest.R.menu;
import android.os.Bundle;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class Main extends Activity {
public BluetoothAdapter mBluetoothAdapter;
private static final int REQUEST_SELECT_DEVICE = 1;
public Button btn_scan;
public Button btn_discover;
public TextView pair_list;
public TextView scan_list;
public ListView scan_list_1;
public Set<BluetoothDevice> pairedDevices;
public ArrayAdapter<String> newDevicelistArrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn_scan = (Button)findViewById(R.id.btn_scan);
btn_discover = (Button)findViewById(R.id.btn_discover);
pair_list = (TextView)findViewById(R.id.pair_list);
scan_list = (TextView)findViewById(R.id.scan_list);
newDevicelistArrayAdapter = new ArrayAdapter<String>(this, R.layout.main);
scan_list_1 = (ListView)findViewById(R.id.scan_list_1);
scan_list_1.setAdapter(newDevicelistArrayAdapter);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null)
{
Toast.makeText(this, "No support bluetooth", Toast.LENGTH_SHORT).show();
return;
}else if(mBluetoothAdapter != null) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_SELECT_DEVICE);
}
//******************scan按鈕動作-將已配對過的藍芽裝置列出來
btn_scan.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
pairedDevices = mBluetoothAdapter.getBondedDevices();
if(pairedDevices.size()>0) {
for(BluetoothDevice bDevice : pairedDevices) {
pair_list.append(bDevice.getName() + "\n" + bDevice.getAddress() + "\n" + bDevice.getBondState() + "\n" );
}
}
}
});
//******************scan按鈕動作結束
btn_discover.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter);
mBluetoothAdapter.startDiscovery();
}
});
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
scan_list.append(device.getName() + "\n" + device.getAddress() + "\n");
newDevicelistArrayAdapter.add(device.getName());
}
}
};
protected void onDestroy() {
super.onDestroy();
if (mBluetoothAdapter != null) {
mBluetoothAdapter.cancelDiscovery();
}
unregisterReceiver(mReceiver);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Does it any wrong when I use the ListView and ArrayAdapter?
Replace the onReceive() of your BroadcastReceiver with this:
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
scan_list.append(device.getName() + "\n" + device.getAddress() + "\n");
newDevicelistArrayAdapter.notifyDataSetChanged();
}
}
I am trying to make an android bluetooth printer application, in which I am successful in detecting bluetooth devices in my proximity,but I am not able to set up a connection when one of the device is choose for connection. also as I am trying to get names of devices in a listview,it is showing one name many times. I am posting my code below.please help
package com.example.test;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.UUID;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final int REQUEST_ENABLE_BT = 1;
OutputStream mmOutputStream;
ListView listDevicesFound;
Button btnScanDevice,connect;
TextView stateBluetooth;
BluetoothAdapter mBluetoothAdapter;
BluetoothSocket mmSocket;
BluetoothDevice mmDevice;
List<String> discoverableDevicesList;
InputStream mmInputStream;
Thread workerThread;
byte[] readBuffer;
int readBufferPosition;
int counter;
volatile boolean stopWorker;
ArrayAdapter<String> btArrayAdapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnScanDevice = (Button)findViewById(R.id.scandevice);
stateBluetooth = (TextView)findViewById(R.id.bluetoothstate);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
connect = (Button)findViewById(R.id.button2);
listDevicesFound = (ListView)findViewById(R.id.devicesfound);
btArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
listDevicesFound.setAdapter(btArrayAdapter);
CheckBlueToothState();
btnScanDevice.setOnClickListener(btnScanDeviceOnClickListener);
registerReceiver(ActionFoundReceiver,
new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(ActionFoundReceiver);
}
private void CheckBlueToothState(){
if (mBluetoothAdapter == null){
stateBluetooth.setText("Bluetooth NOT support");
}else{
if (mBluetoothAdapter.isEnabled()){
if(mBluetoothAdapter.isDiscovering()){
stateBluetooth.setText("Bluetooth is currently in device discovery process.");
}else{
stateBluetooth.setText("Bluetooth is Enabled.");
btnScanDevice.setEnabled(true);
}
}else{
stateBluetooth.setText("Bluetooth is NOT Enabled!");
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
}
private Button.OnClickListener btnScanDeviceOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
btArrayAdapter.clear();
mBluetoothAdapter.startDiscovery();
}};
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if(requestCode == REQUEST_ENABLE_BT){
CheckBlueToothState();
}
}
private final BroadcastReceiver ActionFoundReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
btArrayAdapter.add(device.getName() + "\n" + device.getAddress());
btArrayAdapter.notifyDataSetChanged();
}
}
};}
This is Dialog to show all Paired devices in ListView.
public Dialog pushDevicePairDialog(){
_mDeviceListView = ((LayoutInflater) _mCallingActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.bluetooth_devices_list, null, false);
_mDeviceListDialog = new Dialog(_mCallingActivity,R.style.ThemeDialogCustom);
_mDeviceListDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
_mDeviceListDialog.setContentView(_mDeviceListView);
_mDeviceListDialog.setCancelable(true);
_mPairedDevicesArrayAdapter = new ArrayAdapter<String>(_mCallingActivity,R.layout.device_name);
_mNewDevicesArrayAdapter = new ArrayAdapter<String>(_mCallingActivity,R.layout.device_name);
Button scanButton = (Button) _mDeviceListView.findViewById(R.id.button_scan);
scanButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
doDiscovery();
v.setVisibility(View.GONE);
}
});
ListView pairedListView = (ListView) _mDeviceListView.findViewById(R.id.paired_devices);
pairedListView.setAdapter(_mPairedDevicesArrayAdapter);
pairedListView.setOnItemClickListener(_mDeviceClickListener);
ListView newDevicesListView = (ListView) _mDeviceListView.findViewById(R.id.new_devices);
newDevicesListView.setAdapter(_mNewDevicesArrayAdapter);
newDevicesListView.setOnItemClickListener(_mDeviceClickListener);
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
_mCallingActivity.registerReceiver(_mReceiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
_mCallingActivity.registerReceiver(_mReceiver, filter);
_mBtAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = _mBtAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
_mDeviceListView.findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
for (BluetoothDevice device : pairedDevices) {
String devName = device.getName();
if(devName != null && (devName.startsWith("ESYS") || devName.startsWith("ACC")))
_mPairedDevicesArrayAdapter.add(devName + "\n" + device.getAddress());
}
} else {
String noDevices = _mCallingActivity.getResources().getText(R.string.none_paired).toString();
_mPairedDevicesArrayAdapter.add(noDevices);
}
if (_mBluetoothService == null)
_mBluetoothService = new BluetoothConnectorService(_mCallingActivity);
_mBluetoothService.setListener(this);
return _mDeviceListDialog;
}