I am trying to connect another android device by Bluetooth, So first I paired the devices and then I tried sending the request for another device.
When I called the system bluetooth settings screen, I am able to pair the another device
Intent btSettingsIntent = new Intent(Settings.ACTION_BLUETOOTH_SETTINGS);
startActivityForResult(btSettingsIntent, Pair_Request);
When I tried to pair by programmaticaly, I'm getting this dialogue and entered pair digit in my device but no response in another device
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(strAddress);
Intent intent = new Intent("android.bluetooth.device.action.PAIRING_REQUEST");
intent.putExtra("android.bluetooth.device.extra.DEVICE", device);
intent.putExtra("android.bluetooth.device.extra.PAIRING_VARIANT", 0);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
I got this image in device, when I type pair number, I'm not getting anything in another deivce
if the device is already paired , then you can use
if(device.getBondState()==device.BOND_BONDED){
Log.d(TAG,device.getName());
//BluetoothSocket mSocket=null;
try {
mSocket = device.createInsecureRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e1) {
// TODO Auto-generated catch block
Log.d(TAG,"socket not created");
e1.printStackTrace();
}
try{
mSocket.connect();
}
catch(IOException e){
try {
mSocket.close();
Log.d(TAG,"Cannot connect");
} catch (IOException e1) {
Log.d(TAG,"Socket not closed");
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
for the MY_UUID use
private static final UUID MY_UUID = UUID.fromString("0000110E-0000-1000-8000-00805F9B34FB");
the above code snippet is just to connect your device to an A2DP supported device.
I hope it will work. tell me if not.
Related
I'm trying to set up a system where an android app connects to Arduino via Bluetooth and tells it to either turn on or off its LED. I've looked through a lot of pages and source code and saw many people did it as I did but somehow my code isn't working and I cannot determine why.
Here's the entirety of my Arduino code, really simple and short.
#include <SoftwareSerial.h>
SoftwareSerial Blue(0,1); // rx tx
int LED = 13; // Led connected
char data;
char state = 0;
void setup()
{
pinMode(LED, OUTPUT);
digitalWrite(LED, LOW);
Serial.begin(9600);
Blue.begin(9600);
}
void loop()
{
while(Blue.available()==0);
if(Blue.available()>0){ // read from android via bluetooth
data = Blue.read();
Serial.println(data);
}
if (data == '1') // If data is 1, turn ON the LED
{
digitalWrite(LED,HIGH);
Serial.println("LED ON ");
}
if( data == '2') // if data is 2, turn OFF the LED
{
digitalWrite(LED,LOW);
Serial.println("LED OFF");
}
}
And here's a snippet of my android code that sends data to Arduino to control LED
switchLight.setOnClickListener(new View.OnClickListener() { // button that will switch LED on and off
#Override
public void onClick(View v) {
Log.i("[BLUETOOTH]", "Attempting to send data");
if (mmSocket.isConnected() && btt != null) { //if we have connection to the bluetoothmodule
if (!lightflag) {
try{
mmSocket.getOutputStream().write("1".toString().getBytes());
showToast("on");
}catch (IOException e) {
showToast("Error");
// TODO Auto-generated catch block
e.printStackTrace();
}
//btt.write(sendtxt.getBytes());
lightflag = true;
} else {
try{
mmSocket.getOutputStream().write("2".toString().getBytes());
showToast("off");
}catch (IOException e) {
showToast("Error");
// TODO Auto-generated catch block
e.printStackTrace();
}
//btt.write(sendtxt.getBytes());
lightflag = false;
}
}
else {
Toast.makeText(MainActivity.this, "Something went wrong", Toast.LENGTH_LONG).show();
}
}
});
This is the part of the code that connects to Arduino Bluetooth module. Again, fairly simple stuff and its only purpose are to connect to the module.
BluetoothAdapter bta; //bluetooth stuff
BluetoothSocket mmSocket; //bluetooth stuff
BluetoothDevice mmDevice; //bluetooth stuff
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i("[BLUETOOTH]", "Creating listeners");
final TextView response = findViewById(R.id.response);
Button switchLight = findViewById(R.id.switchlight);
Button connectBT = findViewById(R.id.connectBT);
connectBT.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BluetoothSocket tmp = null;
mmDevice = bta.getRemoteDevice(MODULE_MAC);
Log.i("[BLUETOOTH]", "Attempting to send data");
try {
tmp = mmDevice.createRfcommSocketToServiceRecord(MY_UUID);
mmSocket = tmp;
mmSocket.connect();
Log.i("[BLUETOOTH]","Connected to: "+mmDevice.getName());
showToast("Connected to: " + mmDevice.getName());
}catch(IOException e){
try {mmSocket.close();
}catch(IOException c){return;}
}
}
});
When I connect my android to the Arduino and track the serial monitor on Arduino IDE, instead of reading either 1 or 2, it reads something that looks like this:
This is produced using the Serial. println function in my Arduino code and I'm pretty sure it should display 1 or 2 but as you can see it does not. I've tried multiple workarounds like declaring it as int or char etc. If you can pinpoint any issue I'd much appreciate it.
I have barcode scanner who should work with my app. It is supposed to run in the background and my app is responding to input coming from the scanner in its own way. However it should not be used as a hardware keyboard and its input not directed to the firstresponder (no text entries i.e.). Currently i'm stuck with it although i know i have done a solution like described before (couple years ago for a company).
The first part of the question is now how to prevent the bluetooth device from being attached as a hardware keyboard? Can i control this behaviour or is it maybe some mode or setting that the bluetooth device must support (if yes is there name for it to check in the specifications)?
I guess if the device is not attached as a bluetooth keyboard i could establish a connection and listen to the bluetooth socket input stream for available bytes and collect them. Currently i cannot establish a connection because
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
socket = device.createRfcommSocketToServiceRecord(uuid);
socket.connect();
throws an java.io.IOException with message read failed, socket might closed or timeout, read ret: -1. Any ideas why i cannot connect to the socket, although the device is currently paired to my device?
EDIT:
Because it was asked, the complete connection source code
private void initBluetooth() {
BTAdapter = BluetoothAdapter.getDefaultAdapter();
if (BTAdapter == null) {
Log.e(getClass().getName(), "no BT Adapter");
return;
}
if (!BTAdapter.isEnabled()) {
Intent enableBT = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBT, REQUEST_BLUETOOTH);
return;
}
listDevices();
}
private void listDevices() {
Set<BluetoothDevice> pairedDevices = BTAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
Log.d(getClass().getName(), String.format("Device found %s", device.getName()));
if(device.getName().indexOf("Barcode") > 0) {
mmDevice = device;
try {
openBT();
} catch(IOException e) {
Log.e(getClass().getName(), "Failed", e);
}
break;
}
}
}
}
void openBT() throws IOException
{
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
//now make the socket connection in separate thread
Thread connectionThread = new Thread(new Runnable() {
#Override
public void run() {
// Always cancel discovery because it will slow down a connection
BTAdapter.cancelDiscovery();
// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
mmSocket.connect();
} catch (IOException e) {
//connection to device failed so close the socket
e.printStackTrace();
try {
mmSocket.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}
}
});
connectionThread.start();
mmInputStream = mmSocket.getInputStream();
}
I am new to android programming and therefore this might seem like an easy question for many but its been 2 days and i have searched almost everywhere on the internet but cant find a solution to my problem
i am trying to stream a link(which works when i post on chrome) using MediaPlayer class. Although i get audio on chrome, i never get anything when i run the app on my Samsung galaxy s4.i have already used internet permission for the app. here is the code i am using:
public class LiveKirtan extends Activity {
MediaPlayer mp;
String url;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_live_kirtan);
url = "http://radio2.sikhnet.com:8020/live";
Uri myUri = Uri.parse(url);
mp = new MediaPlayer();
try {
mp.setDataSource(this, myUri);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.prepareAsync();
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer player) {
player.start();
}
});
}
}
Make sure to add the following permission to your manifest:
<uses-permission android:name="android.permission.INTERNET"/>
Also, Android does not support just any kind of streaming audio (especially pre kitkat), so make sure to check the compatibility of your stream here.
im making a music app just for fun. I can read all my music files from sd card but MediaPlayer wont play the sound. I have the path to the file which i pass to the media player with setDataSource but nothing happens and i get no exceptions. Here is the code im using.
Uri songUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
setUpViews();
MediaPlayer mp = new MediaPlayer();
try {
mp.setDataSource(songUri.toString());
mp.prepare();
} catch (IllegalArgumentException e) {
Toast.makeText(this, "ILLEGAL ARGUMENT EXCEPTION", Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (SecurityException e) {
Toast.makeText(this, "SECURITY EXCEPTION", Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (IllegalStateException e) {
Toast.makeText(this, "ILLEGAL STATE EXCEPTION", Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (IOException e) {
Toast.makeText(this, "IO EXCEPTION", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
mp.start();
Log.d("URI AFTER SET UP", songUri.toString());
}
As i said before nothing happens when i open this activity but i still get all the Log.d in the console. Is there any more configurations for the media player to play the music? Thanks in advance.
setDataSource() requires a path argument . You are passing the entire uri as string. Try this :
mp.setDataSource(songUri.getPath());
mp.prepare();
mp.start();
Moreover, if you are trying to access a file with content:// uri, it won't work. You'll have to find the real path to the file, i.e file:// uri.
I think you have to add setAudioStreamType to your MediaPlayer Object. You can add this before mp.setDataSource(your_URI); like below
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
There other types, you can choose AudioManager.STREAM_MUSIC for Music Player
I just solved the problem, and i just dont know why it works. What i did was to put a button to stop the music being played. I dont understand why it works so if someone could explain why it does i'd be thanksfull.
get the path of song by querying MEDIASTORE-EXTERNAL_URI.And this field MEDIASTORE.AUDIO.MEDIA.DATA will give u the path of the song(which is string). U can set it directly to mediaplayer.setDataSource(Your_path_from_mediastore) .It will work fine than.
I'm currently trying to fix a problem I encountered with my Android app which require a Bluetooth connection. For a moment everything seem to work right, But i noticed something strange when the slave Bluetooth device, I want to connect with, is not powered on. Here is my code :
private void connectDevice() {
mBluetoothAdapter.cancelDiscovery();
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
try {
btSocket = createBluetoothSocket(device);
} catch (IOException e) {
errorExit("Fatal Error", "Socket create failed: " + e.getMessage() + ".");
}
//Try to establish the connection. This will block until it connects.
Log.d(TAG, "...Connecting...");
try {
btSocket.connect();
Log.d(TAG, "....Connection ok...");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "Unable to close socket during connection failure" + e2.getMessage() + ".");
}
}
//Create a data stream so we can talk to server.
Log.d(TAG, "...Create Socket...");
mConnectedThread = new ConnectedThread(btSocket);
mConnectedThread.start();
mActionBar.setSubtitle("Connected");
return;
}
And here is where I call this method :
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode){
case REQUEST_ENABLE_BT:
if (resultCode == RESULT_OK) {
Toast.makeText(this, R.string.bt_enabled, Toast.LENGTH_SHORT).show();
setupCom();
break;
}
else {
// User did not enable Bluetooth or an error occurred
if(D) Log.d(TAG, "BT not enabled");
Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
finish();
break;
}
case REQUEST_CONNECT_DEVICE:
if (resultCode == RESULT_OK){
retrieveAddresse(data);
connectDevice();
}
break;
}
return;
}
My problem is that, when I'm not in range or the device I want to connect to is not powered on, the connectDevice() method seem to execute all the code even if it's not possible to connect because Android OS don't want to be blocked by the connection process. I noticed this problem because mActionBar.setSubtitle("Connected"); get executed and because when I try to reconnect when I'm in range or the slave bluetooth module is ON. I can't connect to it unless I relaunch my application.
Put these lines :
mConnectedThread = new ConnectedThread(btSocket);
mConnectedThread.start();
mActionBar.setSubtitle("Connecté");
inside the first try. In this way they will be executed only if the devices establish a connection. As actually they are outside try/catch, they will always executed, even without connection.