Printing a list of available bluetooth devices - java

I'm trying to make my app print a list of available Bluetooth-enabled devices upon opening the activity.
First I enable Bluetooth on the device:
public class Home extends AppCompatActivity {
TextView textView3;
private static final int REQUEST_ENABLE_BT = 1;
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
textView3 = (TextView) findViewById(R.id.textView3);
if (btAdapter == null) {
textView3.append("\nBluetooth not supported. Aborting.");
}
}
then I attempt to add any found devices to the Adapter
private final BroadcastReceiver bReceiver = 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);
//add device to the adapter
btAdapter.add(device.getName(), device.getAddress());
}
}
};
I know there should be a startDiscovery() call somewhere, but I'm having trouble making sense of other answers online. Also, my btAdapter.add() isn't recognized for some reason.
Any help would be appreciated!

my btAdapter.add() isn't recognized for some reason.
Because there is no such method in BluetoothAdapter.
I know there should be a startDiscovery() call somewhere, but I'm having trouble making sense of other answers online.
you can call startDiscovery, once you determine that device supports Bluetooth and Bluetooth is ON from DeviceSettings.

Related

Android play Text To Speech with audio focus (java)

I don't understand how to play text to speech with audio focus (there is spotify running some music when I try my app),
I don't understand the audioFocusChangeListener.
Here is my code:
public class MainActivity extends AppCompatActivity {
AudioManager.OnAudioFocusChangeListener audioFocusChangeListener;
public void playTTSWithAudioFocus(String toSpeak) {
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
audioManager.requestAudioFocus(audioFocusChangeListener,
// Use the music stream.
AudioManager.STREAM_MUSIC,
// Request temporary focus.
AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
textToSpeech.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null,null);
}
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
playTTSWithAudioFocus("hello world");
}
}
Please help me.

Can't use Android BT API methods

I'm developing an android app that needs a BT connection. After reading the Android Developers page, the given method such us isEnabled() doesn't work. The error is cannot resolve symbol isEnabled.
The imported library is android.bluetooth.BluetoothAdapter. In the manifest file, following the instructions of the Android page, I also have inserted the permission to Bluetooth, BT admin and fine location.
The code:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
Log.i("Fallo","Dispositivo sin bluetooth");
}
if (!bluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
You are creating your BluetoothAdapter object outside the onCreate method. Put everything inside the onCreate curly brackets.

Using manager for controlling the volume

I am having problem with using audio manager for controlling volume
I am making a simple app to change ringer mode from the app but the app is crashing. The way to get instance of audio manager as directed by google is showing error. Is it possible to access and control ringer volume and mode from app?
public class MainActivity extends AppCompatActivity {
private boolean isPhoneSilent;
private AudioManager audioManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
Button toggle_Btn = findViewById(R.id.toggle_Btn);
int ringerMode = audioManager.getRingerMode();
if(ringerMode==AudioManager.RINGER_MODE_SILENT)
{
isPhoneSilent=true;
}
else
toggle_Btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(isPhoneSilent)
{
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
isPhoneSilent=false;
}else
{
audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
isPhoneSilent=true;
}
}
});
}

Google Play services activity recognition disconnects without any error

I am writing a background service (started by an activity) that records Screen on/off events and user's activity.
For activity, I am using google api client. The app works correctly on Moto G phones i.e. records both activity and screen but activity recognition stops on HTC one phone.
I have done few updates to code but still there is an issue that activity recognition stops after few minutes. As suggested by another member, I also exported both the android-support-v4.jar and android-support-v7-appcompat.jar files but still the issue is there.
The phone's location is on and it is not on power saving mode. Also, I updated my SDK as well as google play services on phone to the latest one, but still my api client disconnects after few minutes. Below are the code files that I used.
Please help me to correct this. I am using eclipse.
MyActiviy:
public class MyActivity extends Activity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private PendingIntent pIntent;
GoogleApiClient mGoogleApiClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(ActivityRecognition.API).addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();
mGoogleApiClient.connect();
IntentFilter filter = new IntentFilter();
filter.addAction("ACTIVITY_RECOGNITION");//For filtering
}
#Override
public void onConnected(Bundle arg0) {
Intent intent = new Intent(this, ActivityRecognitionService.class);
pIntent = PendingIntent.getService(this, 0, intent,PendingIntent.FLAG_UPDATE_CURRENT);
ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(mGoogleApiClient, 0, pIntent);//0
}
//#Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
mGoogleApiClient.connect(); //I found this recently, but still app doesn't works
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// TODO Auto-generated method stub
}
}
ActivityRecognitionService
public class ActivityRecognitionService extends IntentService {
private String TAG = "appLogs...";
private long fName;
public ActivityRecognitionService() {
super("My Activity Recognition Service");
}
#Override
protected void onHandleIntent(Intent intent) {
if(ActivityRecognitionResult.hasResult(intent)){
ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);
Log.i(TAG, getType(result.getMostProbableActivity().getType()) + "t" + result.getMostProbableActivity().getConfidence());
}
}
private String getType(int type){
if(type == DetectedActivity.UNKNOWN)
return "Unknown";
else if(type == DetectedActivity.IN_VEHICLE)
return "In Vehicle";
else if(type == DetectedActivity.ON_BICYCLE)
return "On Bicycle";
else if(type == DetectedActivity.ON_FOOT)
return "On Foot";
else if(type == DetectedActivity.STILL)
return "Still";
else if(type == DetectedActivity.TILTING)
return "Tilting";
else if(type == DetectedActivity.RUNNING)
return "Running";
else if(type == DetectedActivity.WALKING)
return "Walking";
else
return "";
}
As I have just answered here, it seems that there is no way around. Activity reporting will stop after phone is "still" for some time.
If you want to record even if the phone is "still", I see two ways:
1) rely entirely on the ActivityRecognition API and record "still" until a SIGNIFICANT_MOTION will be detected by Google Services and ActivityRecognition start send you new updates;
2) to write your own simple StillActivityRecognitionService, which starts when there is no updates from "official" API. This Service should listen to the accelerometer sensors, interpret sensor events (deviation from the mean, peak values etc.) and send it's decision "still"/"not still".

Detecting state changes made to the BluetoothAdapter?

I have an app with a button on it that I use to turn BT on and off. I have the following code in there;
public void buttonFlip(View view) {
flipBT();
buttonText(view);
}
public void buttonText(View view) {
Button buttonText = (Button) findViewById(R.id.button1);
if (mBluetoothAdapter.isEnabled() || (mBluetoothAdapter.a)) {
buttonText.setText(R.string.bluetooth_on);
} else {
buttonText.setText(R.string.bluetooth_off);
}
}
private void flipBT() {
if (mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.disable();
} else {
mBluetoothAdapter.enable();
}
}
I'm calling button Flip, which flips the BT state, and then calls ButtonText, which should update the UI. However, the issue I'm having is, it takes a few seconds for BT to turn on - and during these seconds, the BT status is not enabled, making my button say Bluetooth off, even if it will be on in 2 seconds.
I found the STATE_CONNECTING constant in the BluetoothAdapter android documentation, but... I simply don't know how to use it, being a newbie and all.
So, I've got two questions:
Is there a way to dynamically tie a UI element (such as a button or image) to a BT state, so that when the BT state changes, the button will change as well?
Otherwise, I would want to press the button and get the correct state (I would like for it to say BT on, even if it's only connecting, since it will be on in 2 seconds). How do I do this?
You will want to register a BroadcastReceiver to listen for any changes in the state of the BluetoothAdapter:
As a private instance variable in your Activity (or in a separate class file... whichever one you prefer):
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
BluetoothAdapter.ERROR);
switch (state) {
case BluetoothAdapter.STATE_OFF:
setButtonText("Bluetooth off");
break;
case BluetoothAdapter.STATE_TURNING_OFF:
setButtonText("Turning Bluetooth off...");
break;
case BluetoothAdapter.STATE_ON:
setButtonText("Bluetooth on");
break;
case BluetoothAdapter.STATE_TURNING_ON:
setButtonText("Turning Bluetooth on...");
break;
}
}
}
};
Note that this assumes that your Activity implements a method setButtonText(String text) that will change the Button's text accordingly.
And then in your Activity, register and unregister the BroadcastReceiver as follows,
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/* ... */
// Register for broadcasts on BluetoothAdapter state change
IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mReceiver, filter);
}
#Override
public void onDestroy() {
super.onDestroy();
/* ... */
// Unregister broadcast listeners
unregisterReceiver(mReceiver);
}
public void discoverBluetoothDevices(View view)
{
if (bluetoothAdapter!=null)
bluetoothAdapter.startDiscovery();
Toast.makeText(this,"Start Discovery"+bluetoothAdapter.startDiscovery(),Toast.LENGTH_SHORT).show();
}

Categories