Hey guys I am working on an app which should connect to bluetooth devices. But at the moment I'm struggling with the problem that it doesn't find any bluetooth devices in my app but in the bluetooth settings it finds some. (my device runs android 6.x)
My code:
public class MainActivity extends AppCompatActivity {
private ProgressDialog progressDialogBluetoothDiscovery;
private ListView bluetoothDevices;
private ArrayList<String> bluetoothNearbyDevices;
private BluetoothAdapter mBluetoothAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
bluetoothDevices = (ListView) findViewById(R.id.bluetoothDevicesList);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(bluetoothBroadcast, filter);
bluetoothNearbyDevices = new ArrayList<>();
final FloatingActionButton searchDevices = (FloatingActionButton) findViewById(R.id.search_devices);
searchDevices.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
searchDevices();
}
});
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(bluetoothBroadcast);
}
private void searchDevices() {
if (mBluetoothAdapter == null) {
Toast.makeText(MainActivity.this, getResources().getString(R.string.bluetooth_not_supported), Toast.LENGTH_LONG).show();
return;
} else {
if (!mBluetoothAdapter.isEnabled()) {
Snackbar.make(findViewById(R.id.coordinatorLayout), getResources().getString(R.string.bluetooth_not_enabled), Snackbar.LENGTH_LONG).setAction(getResources().getString(R.string.activate_bluetooth), new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, MainActivity.CONTEXT_INCLUDE_CODE);
}
}).show();
} else {
scanForDevices();
}
}
}
private void scanForDevices() {
mBluetoothAdapter.startDiscovery();
}
private final BroadcastReceiver bluetoothBroadcast = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
if (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1) == BluetoothAdapter.STATE_ON) {
scanForDevices();
}
} else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
progressDialogBluetoothDiscovery = ProgressDialog.show(MainActivity.this, getResources().getString(R.string.bluetooth_discovery_title), getResources().getString(R.string.bluetooth_discovery_message), true);
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
progressDialogBluetoothDiscovery.dismiss();
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, bluetoothNearbyDevices);
bluetoothDevices.setAdapter(arrayAdapter);
} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String deviceName = device.getName();
String deviceHardwareAddress = device.getAddress(); // MAC address
Toast.makeText(MainActivity.this, deviceName, Toast.LENGTH_LONG).show();
bluetoothNearbyDevices.add(deviceName);
}
}
};
}
And my manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.package">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
</manifest>
So do you have any Idea why it doesn't find any device in my app?
What version of Android are you running this on? If it is Android 6.x, I believe you need to add the ACCESS_COURSE_LOCATION permission to your manifest.
Below is how run time Permissions work Android 6.0 Marshmallow i.e:
> API level 23
For example:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
switch (ContextCompat.checkSelfPermission(getBaseContext(), Manifest.permission.ACCESS_COARSE_LOCATION)) {
case PackageManager.PERMISSION_DENIED:
((TextView) new AlertDialog.Builder(this)
.setTitle("Runtime Permissions up ahead")
.setMessage("To find nearby bluetooth devices please click Allow on the runtime permissions popup." )
.setNeutralButton("Okay", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (ContextCompat.checkSelfPermission(getBaseContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(DeviceListActivity.this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
REQUEST_ACCESS_COARSE_LOCATION);
}
}
})
.show()
.findViewById(android.R.id.message))
.setMovementMethod(LinkMovementMethod.getInstance());
break;
case PackageManager.PERMISSION_GRANTED:
break;
}
}
Related
I made an application to turn on/off bluetooth. To turn on/off i used a switch button. Here is the code:
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private final static int REQUEST_ENABLE_BT = 1;
BluetoothAdapter mBluetoothAdapter = null;
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(mBluetoothAdapter.ACTION_STATE_CHANGED)) {
final int state = intent.getIntExtra(mBluetoothAdapter.EXTRA_STATE, mBluetoothAdapter.ERROR);
switch (state){
case BluetoothAdapter.STATE_OFF:
break;
case BluetoothAdapter.STATE_ON:
break;
}
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Switch bluetoothSwitch = (Switch) findViewById(R.id.bluetoothSwitch);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null){
//Device does not support bluetooth
}
else{
bluetoothSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(bluetoothSwitch.isChecked() && !mBluetoothAdapter.isEnabled()){
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mReceiver, BTIntent);
}
if(!bluetoothSwitch.isChecked() && mBluetoothAdapter.isEnabled()){
mBluetoothAdapter.disable();
IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mReceiver, BTIntent);
}
}
});
}
}
}
The problem is that if i turn on/off bluetooth from settings and not from my app the switch doesn't change.
I have implemented a broadcast receiver but i can't access the switch from it.
I tried:
bluetoothSwich.setChecked(true)
inside the broadcast receiver but it doesn't work.
Ty
EDIT :
I partially solved the problem with the global switch but to catch the on/off action from settings first i have to click the on/off button from my app at least one time. any suggestion?
To detect the state change of bluetooth you need to add following permission to your AndroidManifest.xml.
<uses-permission android:name="android.permission.BLUETOOTH" />
Use a Local broadcast preferably. You do not need to register it in Manifest . register it at runtime where you need it.(If need throughout the app then register it in Manifest)
private final BroadcastReceiver bStateReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
if (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1) == BluetoothAdapter.STATE_OFF) {
// Bluetooth is disconnected, do handling here
}
}
}
};
Runtime register:
LocalBroadcastManager.getInstance(this).registerReceiver(bStateReceiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));
Runtime unregister : Don't forget to unregister the broadcast.
LocalBroadcastManager.getInstance(this).unregisterReceiver(bStateReceiver);
Static Register:
<receiver
android:name=".FullyQualifiedBroadcastReceiverClassName"
android:enabled="true">
<intent-filter>
<action android:name="android.bluetooth.adapter.action.STATE_CHANGED"/>
</intent-filter>
I tried implementing the Activity Fence using the Google Awareness API. But changes in the user's activity are not getting detected. The headphone fence works as expected though.
ActivityFenceActivity
public class ActivityFenceActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks {
private static final String FENCE_RECEIVER_ACTION = "FENCE_RECEIVE";
private static final String FENCE_WALKING_KEY = "walkingKey";
private static final String FENCE_RUNNING_KEY = "runningKey";
private static final String TAG = ActivityFenceActivity.class.getSimpleName();
private GoogleApiClient googleApiClient;
private TextView activityTextView;
private BroadcastReceiver activityFenceReceiver = new BroadcastReceiver() {
#Override
public void onReceive(final Context context, final Intent intent) {
Toast.makeText(context, "Recieved", Toast.LENGTH_SHORT).show();
FenceState fenceState = FenceState.extract(intent);
if (TextUtils.equals(fenceState.getFenceKey(), FENCE_WALKING_KEY)) {
switch (fenceState.getCurrentState()) {
case FenceState.TRUE:
activityTextView.setText("User is walking");
break;
case FenceState.FALSE:
activityTextView.setText("User is not walking");
break;
case FenceState.UNKNOWN:
activityTextView.setText("Activity state unknown");
break;
}
} else if (TextUtils.equals(fenceState.getFenceKey(), FENCE_RUNNING_KEY)) {
switch (fenceState.getCurrentState()) {
case FenceState.TRUE:
activityTextView.setText("User is running");
break;
case FenceState.FALSE:
activityTextView.setText("User is not running");
break;
case FenceState.UNKNOWN:
activityTextView.setText("Activity state unknown");
break;
}
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity_fence);
activityTextView = (TextView) findViewById(R.id.activityTextView);
googleApiClient = new GoogleApiClient.Builder(ActivityFenceActivity.this)
.addApi(Awareness.API)
.addConnectionCallbacks(this)
.build();
googleApiClient.connect();
findViewById(R.id.register_fence).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
registerActivityFence();
}
});
findViewById(R.id.unregister_fence).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
unregisterActivityFence();
}
});
}
#Override
public void onConnected(#Nullable final Bundle bundle) {
Log.d(TAG, "Google API connected");
}
#Override
public void onConnectionSuspended(final int i) {
Log.d(TAG, "Google API connection suspended");
}
#Override
protected void onStart() {
super.onStart();
registerReceiver(activityFenceReceiver, new IntentFilter(FENCE_RECEIVER_ACTION));
}
#Override
protected void onStop() {
super.onStop();
unregisterReceiver(activityFenceReceiver);
unregisterActivityFence();
}
private void registerActivityFence() {
AwarenessFence walkingFence = DetectedActivityFence.during(DetectedActivityFence.WALKING);
AwarenessFence runningFence = DetectedActivityFence.during(DetectedActivityFence.RUNNING);
PendingIntent fencePendingIntent = PendingIntent.getBroadcast(this,
0,
new Intent(FENCE_RECEIVER_ACTION),
0);
Awareness.FenceApi.updateFences(googleApiClient, new FenceUpdateRequest.Builder()
.addFence(FENCE_WALKING_KEY, walkingFence, fencePendingIntent).build())
.setResultCallback(new ResultCallbacks<Status>() {
#Override
public void onSuccess(#NonNull final Status status) {
Toast.makeText(ActivityFenceActivity.this,
"Fence registered successfully",
Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(#NonNull final Status status) {
Toast.makeText(ActivityFenceActivity.this,
"Cannot register activity fence.",
Toast.LENGTH_SHORT).show();
}
});
Awareness.FenceApi.updateFences(googleApiClient, new FenceUpdateRequest.Builder()
.addFence(FENCE_RUNNING_KEY, runningFence, fencePendingIntent).build());
}
private void unregisterActivityFence() {
Awareness.FenceApi.updateFences(
googleApiClient,
new FenceUpdateRequest.Builder()
.removeFence(FENCE_WALKING_KEY)
.removeFence(FENCE_RUNNING_KEY)
.build()).setResultCallback(new ResultCallbacks<Status>() {
#Override
public void onSuccess(#NonNull Status status) {
Toast.makeText(ActivityFenceActivity.this,
"Fence unregistered successfully.",
Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(#NonNull Status status) {
Toast.makeText(ActivityFenceActivity.this,
"Cannot unregister headphone fence.",
Toast.LENGTH_SHORT).show();
}
});
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.subhrajyoti.awareness">
<uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.awareness.API_KEY"
android:value="AIzaSyBEmjlfC87xRUP2FnFynsDdY3QRuI1hIHs" />
</application>
</manifest>
If the headphone fence is working and the activity fence is not, maybe you simply forgot to add the permission in the manifest?
<uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION"/>
I tried to use Awareness API instead of geofencing, I think the problem is how you tested your code.
I'm pretty sure that Awareness uses phone's sensors, so when I use the GPS simulator to simulate a walk, it doesn't trigger anything, but if I use my real phone and walk, BroadcastReceiver is triggered.
However, I don't know how to simulate a "sensor walking" on the emulator!
While making a call from the app, it is not working. I have added the permission in android manifest, but it is still not working. Please see my code and help me soon.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:999999999"));
if (ActivityCompat.checkSelfPermission(menu.this,
Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
return;
}
startActivity(callIntent);
}
});
This code should work:
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + "Your Phone_number"));
startActivity(intent);
Permission in Manifest:
<uses-permission android:name="android.permission.CALL_PHONE" />
but i highly recommend using ACTION_DIAL instead. It opens up the dialer screen with the number entered instead. This gives the user more flexibility. Also you don't need to have the CALL_PHONE permission with this one.
Here is an update:
With CALL_PHONE permission
Main Class
public class MainActivity extends AppCompatActivity {
private final int CALL_PHONE = 1;
private Button dialBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dialBtn = (Button) findViewById(R.id.dial_button);
//In android 6 we need to ask for permissions:
if (ActivityCompat.checkSelfPermission(getApplicationContext(),
Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.CALL_PHONE}, CALL_PHONE);
} else {
Toast.makeText(getApplicationContext(), "We need permissions to dial.", Toast.LENGTH_LONG).show();
}
} else {
setupView();
}
}
private void setupView() {
dialBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:999999999"));
// We have to implement this part because ... yeah permissions in android.....
if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(getApplicationContext(), "We need permissions to dial.", Toast.LENGTH_LONG).show();
return;
}
startActivity(callIntent);
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case CALL_PHONE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
setupView();
} else {
Toast.makeText(getApplicationContext(), "We need permissions to dial.", Toast.LENGTH_LONG).show();
}
break;
}
}
My manifest:
<uses-permission android:name="android.permission.CALL_PHONE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Without the permission check and only using ACTION_DIAL
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button dialBtn = (Button) findViewById(R.id.dial_button);
dialBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent callIntent = new Intent(Intent.ACTION_DIAL);
callIntent.setData(Uri.parse("tel:999999999"));
startActivity(callIntent);
}
});
}
}
The last one is so much easier. Android permission checks are a pain in the ass.
I just made my own class. It's easier for the next time to also provide the error Stack trace. But for what I can see in your code is that your using menu.this I don't know for sure because u didn't provide enough information but I think this causes the error.
I hope I helped u out.
I am trying to use google search to text engine but it is not possible and get error :
android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.speech.action.RECOGNIZE_SPEECH (has extras)
Can you help me?
Here is my MainActivity.java code
public class MainActivity extends Activity {
private static final int REQUEST_CODE = 1234;
Button Start;
TextView Speech;
Dialog match_text_dialog;
ListView textlist;
ArrayList<String> matches_text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Start = (Button)findViewById(R.id.start_reg)
Speech = (TextView)findViewById(R.id.speech);
Start.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(isConnected()){
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
startActivityForResult(intent, REQUEST_CODE);
}
else{
Toast.makeText(getApplicationContext(), "Plese Connect to Internet", Toast.LENGTH_LONG).show();
}}
});
}
public boolean isConnected()
{
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo net = cm.getActiveNetworkInfo();
if (net!=null && net.isAvailable() && net.isConnected()) {
return true;
} else {
return false;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
match_text_dialog = new Dialog(MainActivity.this);
match_text_dialog.setContentView(R.layout.dialog_matches_frag);
match_text_dialog.setTitle("Select Matching Text");
textlist = (ListView)match_text_dialog.findViewById(R.id.list);
matches_text = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, matches_text);
textlist.setAdapter(adapter);
textlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Speech.setText("You have said " +matches_text.get(position));
match_text_dialog.hide();
}
});
match_text_dialog.show();
}
super.onActivityResult(requestCode, resultCode, data);
}
}
and this is AndroidManifest.xml code
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.learn2crack.speech"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="15"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.learn2crack.speech.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
I am developing an app which scans the bluetooth devices and list them all. My requirement is that I have to scan for devices as soon as application starts..Now my problem is when i run the app for the first time it only turns on the bluetooth but does not scan for devices..
I can see the bluetooth icon on screen but in log cat getState() method of the BluetoothAdapter shows state as STATE_OFF.
Please anyone help me about this issue ??
Here is my code snippet
public class MainActivity extends Activity {
private BluetoothAdapter bluetoothAdapter;
Set<String> BTList;
ArrayAdapter<String> BTAdapter;
private ListView listView;
private BroadcastReceiver mReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
listView = (ListView) findViewById(R.id.listView1);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null)
Toast.makeText(this, "Devices does not support Bluetooth",
Toast.LENGTH_SHORT).show();
if (!bluetoothAdapter.isEnabled())
bluetoothAdapter.enable();
if(bluetoothAdapter.isEnabled()) {
if(bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
}
}
bluetoothAdapter.startDiscovery();
mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
BTAdapter.add(device.getName() + "\n" + device.getAddress());
BTAdapter.notifyDataSetChanged();
}
}
};
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
BTAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_expandable_list_item_1);
listView.setAdapter(BTAdapter);
}
#Override
protected void onDestroy() {
super.onDestroy();
//if(bluetoothAdapter != null)
// bluetoothAdapter.cancelDiscovery();
unregisterReceiver(mReceiver);
}
}
Check in your AndroidManifest.xml file, if you have these below entries
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />