Here is my problem/question, probably a nooby one....
I have an activity where the app checks if the bluetooth is switched on, if not it displays a pop-up window with a button to activate it.
when activated there is a button which will search for bluetooth devices.
now my question is how can i pair to the selected device which will be protected with an password, if it is already paired just connect to it (witouth entering the password again)
after connecting to the device it should go to the next page.
Here is my Code
package com.example.silcamanager96x32;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
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.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import android.view.View.OnClickListener;
import android.widget.AdapterView.OnItemClickListener;
public class Bluetooth_check extends Activity {
//global variables
private final static int REQUEST_ENABLE_BT = 1;
private ArrayAdapter<String> btArrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth_check);
btn_go();
btn_scan();
}
//tijdelijke button volgende pagina
public void btn_go(){
Button btn_go=(Button)findViewById(R.id.Button01);
btn_go.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("clicks","You Clicked B1");
Intent i=new Intent(
Bluetooth_check.this,
home.class);
startActivity(i);
}
});
}
//button scannen naar bluetooth apparaten en in ene lijst plaatsen
public void btn_scan(){
final Button scanb = (Button)findViewById(R.id.button);
final ListView Deviceslist = (ListView)findViewById(R.id.listView1);
btArrayAdapter = new ArrayAdapter<String>(Bluetooth_check.this, android.R.layout.simple_list_item_1);
Deviceslist.setAdapter(btArrayAdapter);
//vraagt of app bluetooth mag inschakelen
final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
// Device does not support Bluetooth
Toast.makeText(Bluetooth_check.this, "Your device doesnot support Bluetooth", Toast.LENGTH_LONG).show();
}
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
//onclick scan button
scanb.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
btArrayAdapter.clear();
mBluetoothAdapter.startDiscovery();
Toast.makeText(Bluetooth_check.this, "Scanning Devices", Toast.LENGTH_LONG).show();
}
});
Deviceslist.setOnItemClickListener( new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v, int position,
long id) {
// onclick item gevonden apparaten
AlertDialog.Builder adb = new AlertDialog.Builder(
Bluetooth_check.this);
adb.setTitle("ListView OnClick");
adb.setMessage("Selected Item is = "
+ Deviceslist.getItemAtPosition(position));
adb.setPositiveButton("Ok", null);
adb.show();
}
});
registerReceiver(FoundReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(FoundReceiver);
}
private final BroadcastReceiver FoundReceiver = 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();
}
}};
}
try this link here is whole code ...Android + Pair devices via bluetooth programmatically and add permission to manifest
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
Related
i have problem with this code everything works but when i press scan button nothing happens why is that, i'm sure this code is right i follow Bluetooth Android Developer tutorial, Upon debug, I found that the onReceive method of BroadcastReceiver is never called. However, Bluetooth is enabled. What am I missing?
package com.example.bluetoothmaccounter;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
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.media.MediaPlayer;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
Button buttonON , buttonOFF, scanBt;
ListView deviceList;
ArrayList<String> arrayList = new ArrayList<String>();
ArrayAdapter<String> arrayAdapter;
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
int requestCodeForEnable = 1;
Intent btEnablingIntent;
Vibrator vibrator;
MediaPlayer mediaPlayer;
TextView textView2 ;
#Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonOFF = findViewById(R.id.bt_off);
buttonON = findViewById(R.id.bt_on);
scanBt = findViewById(R.id.bt_scan);
deviceList = findViewById(R.id.device_list);
btEnablingIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
mediaPlayer = MediaPlayer.create(this, R.raw.alarm);
textView2 = findViewById(R.id.textView2);
// /////////////////// Enable bluetooth ///////////////////////
buttonON.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (bluetoothAdapter == null) {
Toast.makeText(getApplicationContext(), "this device not support bluetooth", Toast.LENGTH_SHORT).show();
} else {
if (!bluetoothAdapter.isEnabled()) {
startActivityForResult(btEnablingIntent, requestCodeForEnable);
}
}
}
});
// /////////////////// disable bluetooth ///////////////////////
buttonOFF.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (bluetoothAdapter.isEnabled()) {
bluetoothAdapter.disable();
Toast.makeText(getApplicationContext(), "bluetooth disable", Toast.LENGTH_SHORT).show();
}
}
});
// /////////////////// start scan ///////////////////////
scanBt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
arrayList.clear();
if (!bluetoothAdapter.isEnabled()) {
Toast.makeText(getApplicationContext(), " bluetooth not Enabled", Toast.LENGTH_SHORT).show();
} else {
bluetoothAdapter.startDiscovery();
Toast.makeText(getApplicationContext(), "discover started", Toast.LENGTH_SHORT).show();
}
}
});
try {
IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
textView2.setText("befoore receiver");
registerReceiver(receiver, intentFilter);
arrayAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, arrayList);
deviceList.setAdapter(arrayAdapter);
} catch (Exception e) {
textView2.setText("exeption" + e.getMessage());
}
}
// Create a BroadcastReceiver for ACTION_FOUND.
private final BroadcastReceiver receiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
textView2.setText("on receive 1");
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
textView2.setText("found");
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
arrayList.add(device.getName() + device.getAddress());
String size = "size is " + arrayList.size();
textView2.setText(size);
arrayAdapter.notifyDataSetChanged();
if (arrayList.size() >= 1) {
Toast.makeText(getApplicationContext(), "There are :" + arrayList.size() + "person here ", Toast.LENGTH_LONG).show();
vibrator.vibrate(3 * 1000);
mediaPlayer.start();
}
//
}
}
};
#Override
protected void onDestroy () {
super.onDestroy();
// Don't forget to unregister the ACTION_FOUND receiver.
textView2.setText("destrrooooooy");
unregisterReceiver(receiver);
}
}
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"></uses-permission>
<uses-permission android:name="android.permission.BLUETOOTH"></uses-permission>
You need to add these two permissions in AndroidManifest.xml
i'm trying to create a simple app in which I have a button in the MainActivity and a ListView in the PairingList activity. I want the button to enable bluetooth and then list all the paired devices in the listview in the other activity. However, I get a runtime exception as soon as I've enabled BT after I clicked the button. So far this is my code:
MainActivity.java
package com.gmburg.android.bluetoothservice;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Set;
public class MainActivity extends AppCompatActivity {
Button btOn;
BluetoothAdapter btAdapter;
int REQUEST_CODE = 1;
Set<BluetoothDevice> paired_devices;
String plist[];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btOn = (Button) findViewById(R.id.btOn);
btOn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btAdapter = BluetoothAdapter.getDefaultAdapter();
if (btAdapter == null) {
Toast.makeText(getBaseContext(), "Device has no bluetooth antenna", Toast.LENGTH_LONG).show();
} else {
if (!btAdapter.isEnabled()) {
Intent i = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(i, REQUEST_CODE);
}
}
}
});
}
public void onActivityResult(int requestcode, int resultcode, Intent data) {
if (requestcode == REQUEST_CODE) {
if (resultcode == RESULT_OK) {
Toast.makeText(getBaseContext(), "Bluetooth enabled", Toast.LENGTH_LONG).show();
paired_devices = btAdapter.getBondedDevices();
int count = paired_devices.size();
plist = new String[count];
int j = 0;
for(BluetoothDevice device : paired_devices){
plist[j] = device.getName();
j++;
}
}
Bundle btOn = new Bundle();
btOn.putStringArray("paires", plist);
Intent in = new Intent("pair_filter");
in.putExtras(btOn);
startActivity(in);
}
}
}
PairingList.java
package com.gmburg.android.bluetoothservice;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class PairingList extends Activity {
ListView lview;
String[] pairs;
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pairinglist_layout);
lview = (ListView) findViewById(R.id.listviewid);
Bundle btOn = getIntent().getExtras();
pairs = btOn.getStringArray("pairs");
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, pairs);
lview.setAdapter(adapter);
}
}
The logger gives me this:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=null} to activity {com.gmburg.android.bluetoothservice/com.gmburg.android.bluetoothservice.MainActivity}: android.content.ActivityNotFoundException: No Activity found to handle Intent { act=pair_filter (has extras) }
All the help is appreciated!
You are getting below error
android.content.ActivityNotFoundException: No Activity found to handle Intent { act=pair_filter (has extras)
this is because the intent you are trying to start activity for is not handled by any available activity/app in the phone. try resolveActivity method to find if any activity will be able to handle this, then only call startActivity/ForResult from your application.
resolveActivity Method's docs
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
i know it has been asked before for a different program but I am still getting error given below for my program
Thread [Thread-15956] (Suspended (exception ViewRootImpl$CalledFromWrongThreadException))
Please HELP!!
This is my MainActivity class
package a.example.na;
import java.util.Scanner;
import java.util.Set;
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.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class MainActivity extends Activity {
private static TextView inputtext;
private BluetoothAdapter myBluetoothAdapter;
private Set<BluetoothDevice> pairedDevices;
private ListView myListView;
private ArrayAdapter<String> BTArrayAdapter;
private BluetoothDevice mDevice;
private Button findBtn;
private String address;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(myBluetoothAdapter == null) {
findBtn.setEnabled(false);
Toast.makeText(getApplicationContext(),"Your device does not support Bluetooth",
Toast.LENGTH_LONG).show();
} else {
inputtext = (TextView) findViewById(R.id.text);
findBtn = (Button)findViewById(R.id.search);
findBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
find(v);
}
});
myListView = (ListView)findViewById(R.id.listView1);
// create the arrayAdapter that contains the BTDevices, and set it to the ListView
BTArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
myListView.setAdapter(BTArrayAdapter);
myListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapterView, View v, int pos,
long arg3) {
// Add the name and address to an array adapter to show in a ListView
String i = (String) adapterView.getItemAtPosition(pos);
B b=new B(inputtext);
b.start();
Scanner scanner = new Scanner(i);
if(scanner.hasNextLine()) {
address =scanner.nextLine();
}
mDevice = myBluetoothAdapter.getRemoteDevice(address);
scanner.close();
}
});
}
}
final BroadcastReceiver bReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// add the name and the MAC address of the object to the arrayAdapter
BTArrayAdapter.add( device.getAddress()+ "\n" +device.getName() );
BTArrayAdapter.notifyDataSetChanged();
}
}
};
public void find(View view) {
if (myBluetoothAdapter.isDiscovering()) {
// the button is pressed when it discovers, so cancel the discovery
myBluetoothAdapter.cancelDiscovery();
}
else {
BTArrayAdapter.clear();
myBluetoothAdapter.startDiscovery();
registerReceiver(bReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
}
#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);
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(bReceiver);
}
}
This is my separate Thread class
package com.bt;
import android.widget.TextView;
public class B extends Thread {
TextView inputtext;
public B(TextView x){
inputtext=x;
}
public void run(){
inputtext.setText("hero");
}
}
Your are touching the views(widgets) in the Non UI Thread.
public class B extends Thread {
TextView inputtext;
Activity activity;
public B(Activity activity, TextView x) {
inputtext = x;
this.activity = activity;
}
public void run() {
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
inputtext.setText("hero");
}
});
}
}
While starting the Thread
B b=new B(MainActivity.this, inputtext);
b.start();
I am trying to create an application which activates and deactivates Bluetooth, finds the paired Bluetooth devices and scans for discovered Bluetooth devices. I added the permissions to the AndroidManifest.xml. And everything seems to be ok. However when I debug the app on the device(Samsung Galaxy tab 3 Lite) I get NullPointerException and the application crashes. Do you have an idea what might cause the problem? Please find below my code and the exception stack trace.
package dyankov.mylibraryrecommender.MainActivities.GUI;
import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import dyankov.mylibraryrecommender.R;
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 java.util.Set;
import android.content.Intent;
import android.content.IntentFilter;
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 AroundMeActivity extends Activity {
private static final int REQUEST_ENABLE_BT = 1;
private Button turnOn;
private Button offBtn;
private Button listBtn;
private Button findBtn;
private TextView text;
private BluetoothAdapter myBluetoothAdapter;
private Set<BluetoothDevice> pairedDevices;
private ListView myListView;
private ArrayAdapter<String> BTArrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// take an instance of BluetoothAdapter - Bluetooth radio
myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(myBluetoothAdapter == null) {
turnOn.setEnabled(false);
offBtn.setEnabled(false);
listBtn.setEnabled(false);
findBtn.setEnabled(false);
text.setText("Status: not supported");
Toast.makeText(getApplicationContext(),"Your device does not support Bluetooth",
Toast.LENGTH_LONG).show();
} else {
text = (TextView) findViewById(R.id.text);
turnOn = (Button)findViewById(R.id.turnOn);
turnOn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
on(v);
}
});
offBtn = (Button)findViewById(R.id.turnOff);
offBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
off(v);
}
});
listBtn = (Button)findViewById(R.id.paired);
listBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
list(v);
}
});
findBtn = (Button)findViewById(R.id.search);
findBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
find(v);
}
});
myListView = (ListView)findViewById(R.id.listView1);
// create the arrayAdapter that contains the BTDevices, and set it to the ListView
BTArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
myListView.setAdapter(BTArrayAdapter);
}
}
public void on(View view){
if (!myBluetoothAdapter.isEnabled()) {
Intent turnOnIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOnIntent, REQUEST_ENABLE_BT);
Toast.makeText(getApplicationContext(),"Bluetooth turned on" ,
Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(getApplicationContext(),"Bluetooth is already on",
Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if(requestCode == REQUEST_ENABLE_BT){
if(myBluetoothAdapter.isEnabled()) {
text.setText("Status: Enabled");
} else {
text.setText("Status: Disabled");
}
}
}
public void list(View view){
// get paired devices
pairedDevices = myBluetoothAdapter.getBondedDevices();
// put it's one to the adapter
for(BluetoothDevice device : pairedDevices)
BTArrayAdapter.add(device.getName()+ "\n" + device.getAddress());
Toast.makeText(getApplicationContext(),"Show Paired Devices",
Toast.LENGTH_SHORT).show();
}
final BroadcastReceiver bReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// add the name and the MAC address of the object to the arrayAdapter
BTArrayAdapter.add(device.getName() + "\n" + device.getAddress());
BTArrayAdapter.notifyDataSetChanged();
}
}
};
public void find(View view) {
if (myBluetoothAdapter.isDiscovering()) {
// the button is pressed when it discovers, so cancel the discovery
myBluetoothAdapter.cancelDiscovery();
}
else {
BTArrayAdapter.clear();
myBluetoothAdapter.startDiscovery();
registerReceiver(bReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
}
public void off(View view){
myBluetoothAdapter.disable();
text.setText("Status: Disconnected");
Toast.makeText(getApplicationContext(),"Bluetooth turned off",
Toast.LENGTH_LONG).show();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(bReceiver);
}
}
And here is my Logcat file:
Caused by: java.lang.NullPointerException
at dyankov.mylibraryrecommender.MainActivities.GUI.AroundMeActivity.onCreate(AroundMeActivity.java:60)
at android.app.Activity.performCreate(Activity.java:5326)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1097)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2225)
The code on line 60 is:
turnOn.setOnClickListener(new OnClickListener() { ... }
put turnOn = (Button)findViewById(R.id.turnOn) and all your Button object initialization before turnOn.setEnabled(false);
You try to use button before you set value for it.
Try this code:
text = (TextView) findViewById(R.id.text);
turnOn = (Button)findViewById(R.id.turnOn);
if(myBluetoothAdapter == null) {
turnOn.setEnabled(false);
offBtn.setEnabled(false);
listBtn.setEnabled(false);
findBtn.setEnabled(false);
text.setText("Status: not supported");
Toast.makeText(getApplicationContext(),"Your device does not support Bluetooth",
Toast.LENGTH_LONG).show();
} else {
turnOn.setOnClickListener(new OnClickListener() {
I want to create simple application in which i want to show bluetooth devices..but when i press the button, Application crashes..
in ActivityMain.java this method will go to next activity (Activity.java)..in which i am getting problem..Rest of buttons are working
ActivityMain.java
package com.example.bluetoothcheck5;
import java.util.Set;
import com.example.bluetoothcheck5.Activity2;
import android.os.Bundle;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final int REQUEST_ENABLE_BT = 0;
private static final int REQUEST_DISCOVERABLE_BT = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView out=(TextView)findViewById(R.id.out);
final Button button = (Button) findViewById(R.id.button1);
final Button button1 = (Button) findViewById(R.id.button2);
final Button button2 = (Button) findViewById(R.id.button3);
final Button buttonSearch = (Button) findViewById(R.id.buttonSearch);
final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
out.append("device not supported");
}
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
});
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (!mBluetoothAdapter.isDiscovering()) {
Context context = getApplicationContext();
CharSequence text = "MAKING YOUR DEVICE DISCOVERABLE";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(enableBtIntent, REQUEST_DISCOVERABLE_BT);
}
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
mBluetoothAdapter.disable();
Context context = getApplicationContext();
CharSequence text = "TURNING_OFF BLUETOOTH";
Toast toast = Toast.makeText(context, text, Toast.LENGTH_LONG);
toast.show();
Set<BluetoothDevice> mPairedDevices = mBluetoothAdapter.getBondedDevices();
if (mPairedDevices.size() > 0)
{
for (BluetoothDevice mDevice : mPairedDevices)
{
Log.v("Title", "PairedDevices: " + mDevice.getName() + " " + mDevice.getAddress());
}
}
}
});
buttonSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(arg0.getContext(), Activity2.class);
// myIntent.setClass(MainActivity.this, Activity2.class);
// startActivityForResult(myIntent, REQUEST_PAIRED_DEVICE);
startActivity(myIntent);
}
});
}}
Activity2.java
package com.example.bluetoothcheck5;
import java.util.Set;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import com.example.bluetoothcheck5.R;
import com.example.bluetoothcheck5.MainActivity;
public class Activity2 extends MainActivity {
protected static final String TAG = "TAG";
private BluetoothAdapter mBluetoothAdapter;
private ArrayAdapter<String> mPairedDevicesArrayAdapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.activity_2);
ListView mPairedListView = (ListView) findViewById(R.id.listView1);
mPairedListView.setAdapter(mPairedDevicesArrayAdapter);
mPairedListView.setOnItemClickListener(mDeviceClickListener);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> mPairedDevices = mBluetoothAdapter.getBondedDevices();
if (mPairedDevices.size() > 0)
{
findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
for (BluetoothDevice mDevice : mPairedDevices)
{
mPairedDevicesArrayAdapter.add(mDevice.getName() + "\n" + mDevice.getAddress());
}
}
else
{
String mNoDevices = getResources().getText(R.string.none_paired).toString();
mPairedDevicesArrayAdapter.add(mNoDevices);
}
}
private OnItemClickListener mDeviceClickListener = new OnItemClickListener()
{
public void onItemClick(AdapterView<?> mAdapterView, View mView, int mPosition, long mLong)
{
mBluetoothAdapter.cancelDiscovery();
String mDeviceInfo = ((TextView) mView).getText().toString();
String mDeviceAddress = mDeviceInfo.substring(mDeviceInfo.length() - 17);
Log.v(TAG, "Device_Address " + mDeviceAddress);
Bundle mBundle = new Bundle();
mBundle.putString("DeviceAddress", mDeviceAddress);
Intent mBackIntent = new Intent();
mBackIntent.putExtras(mBundle);
setResult(Activity.RESULT_OK, mBackIntent);
finish();
}
};
}
i made sample project to demonstrate bluetooth disovering, pair or unpair device. Find it here,
http://www.londatiga.net/it/programming/android/how-to-programmatically-scan-or-discover-android-bluetooth-device/