Android Bluetooth API
Marko Gargenta@MarkoGargenta
Marakana, Inc.
Member since Jan 19, 2007
Location: San Francisco
Forum Posts: 228
Location: San Francisco
Forum Posts: 228
Android was release in version 1.0 without the Bluetooth support. The API was yanked out of the final release at the last minute. The reason was that the development team felt they didn't have the time to complete it properly and didn't want to commit to half-fast API.
Android 2.0 (SDK level 5) finally brings the official support for the Bluetooth. It is offered via
Note that the emulator still doesn't support Bluetooth emulation. And since my Dev2/G2 is still running Android 1.5, I do not have a way to test this code and evolve it.
The main access to Bluetooth is done via the
To get the list of all the devices that have been paired with the local device, use
/src/com.marakana/BluetoothDemo.java
Mainfest File
Don't forget to add appropriate permissions in your manifest file:
Output
As I mentioned before, my emulator and my physical phone do not support Bluetooth at this point, so the output just says so. I'll update this example when the support is there.
Android 2.0 (SDK level 5) finally brings the official support for the Bluetooth. It is offered via
android.bluetooth package.Note that the emulator still doesn't support Bluetooth emulation. And since my Dev2/G2 is still running Android 1.5, I do not have a way to test this code and evolve it.
The main access to Bluetooth is done via the
BluetoothAdapter. The adapter, returned via getDefaultAdapter() static method, offers access to various devices. The startDiscovery() method on the adapter will start the discovery of other discoverable devices. It is a synchronous call that can take some time to complete.To get the list of all the devices that have been paired with the local device, use
adapter.getBondedDevices()./src/com.marakana/BluetoothDemo.java
Code:
package com.marakana;
import java.util.Set;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.os.Bundle;
import android.widget.TextView;
public class BluetoothDemo extends Activity {
TextView out;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
out = (TextView) findViewById(R.id.out);
// Getting the Bluetooth adapter
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
out.append("\nAdapter: " + adapter);
// Check for Bluetooth support in the first place
// Emulator doesn't support Bluetooth and will return null
if(adapter==null) {
out.append("\nBluetooth NOT supported. Aborting.");
return;
}
// Starting the device discovery
out.append("\nStarting discovery...");
adapter.startDiscovery();
out.append("\nDone with discovery...");
// Listing paired devices
out.append("\nDevices Pared:");
Set<BluetoothDevice> devices = adapter.getBondedDevices();
for (BluetoothDevice device : devices) {
out.append("\nFound device: " + device);
}
}
}
Mainfest File
Don't forget to add appropriate permissions in your manifest file:
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.marakana" android:versionCode="1" android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name"
android:theme="@android:style/Theme.Light">
<activity android:name=".BluetoothDemo" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
</application>
<uses-sdk android:minSdkVersion="5" />
</manifest>
Output
As I mentioned before, my emulator and my physical phone do not support Bluetooth at this point, so the output just says so. I'll update this example when the support is there.
Edited 8 times. Last edit by Vishal Rajpal on Apr 17, 2011 at 12:19:02 PM (about 2 years ago).
Syed Agha
None
Member since May 20, 2010
Forum Posts: 6
Forum Posts: 6
when i run this code on emulator it gives me the error "application has stopped unexpectedly". so can u please tell me . what is the problem?
Marko Gargenta@MarkoGargenta
Marakana, Inc.
Member since Jan 19, 2007
Location: San Francisco
Forum Posts: 228
Location: San Francisco
Forum Posts: 228
Look at your logs. It's hard to tell what went wrong without any info. Use your LogCat - it's your friend.
Syed Agha
None
Member since May 20, 2010
Forum Posts: 6
Forum Posts: 6
i am facing problem getDefaultAdapter . when i try to take the name or address of the adapter. it say "Application stopped unexpectedly" i check the logcat it say "unable to start activity component info" . what would u suggest?
Syed Agha
None
Member since May 20, 2010
Forum Posts: 6
Forum Posts: 6
public class BlueToothAdapter extends Activity {
/** Called when the activity is first created. */
//BluetoothAdapter = BluetoothAdapter.getdefault();
private final BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
//BluetoothDevice bluetooth = BluetoothAdapter.getDefaultAdapter().getAddress();
String toast;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
get_Name();
}
public void get_Name(){
if(bluetooth==null){
toast ="Bluetooth is not Enabled";
}
else{
String name=bluetooth.getName();
// String address = bluetooth.getAddress();
toast= name;
Toast.makeText(this, toast, Toast.LENGTH_LONG).show();
}
}
}
this is my code
/** Called when the activity is first created. */
//BluetoothAdapter = BluetoothAdapter.getdefault();
private final BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
//BluetoothDevice bluetooth = BluetoothAdapter.getDefaultAdapter().getAddress();
String toast;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
get_Name();
}
public void get_Name(){
if(bluetooth==null){
toast ="Bluetooth is not Enabled";
}
else{
String name=bluetooth.getName();
// String address = bluetooth.getAddress();
toast= name;
Toast.makeText(this, toast, Toast.LENGTH_LONG).show();
}
}
}
this is my code
Edited one time. Last edit by Syed Agha on May 28, 2010 at 1:16:13 PM (about 2 years ago).
Ulrik Hørlyk Hjort
Bpc
Member since Oct 14, 2010
Forum Posts: 1
Forum Posts: 1
You need to have the uses-permission tags after the Application block else you will get an BLUETOOTH_ADMIN permission exception which leads to the "application has stopped unexpectedly" error.
The correct Manifest file is:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.marakana" android:versionCode="1" android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name"
android:theme="@android:style/Theme.Light">
<activity android:name=".BluetoothDemo" 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>
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-sdk android:minSdkVersion="5" />
</manifest>
The correct Manifest file is:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.marakana" android:versionCode="1" android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name"
android:theme="@android:style/Theme.Light">
<activity android:name=".BluetoothDemo" 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>
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-sdk android:minSdkVersion="5" />
</manifest>
Edited one time. Last edit by Ulrik Hørlyk Hjort on Oct 14, 2010 at 7:36:21 AM (about 2 years ago).
Kevin Timm
None
Member since Nov 18, 2010
Forum Posts: 1
Forum Posts: 1
Is there anyway to get your res directory?
Atul Goswami
Noe
Member since Dec 24, 2010
Forum Posts: 1
Forum Posts: 1
Could we send a file directly from a music player (without searching that file in file explorer).
i have search a lot and din't find any such application could u help me to do that.
it would be great help to all.
i have search a lot and din't find any such application could u help me to do that.
it would be great help to all.
Trevor GuilloryStudent
CSUC
Member since Feb 6, 2011
Forum Posts: 1
Forum Posts: 1
Mr. Gargenta,
As I understand it, the code example is what we put in our app so the app can use bluetooth, correct? If so, how do we get the information from our bluetooth section of our code to actually use it in an app? I am trying to develop an app that will allow me to take in serial data via bluetooth and then display it. Specifically, I am trying to develop an interface to the user that gets data sent over bluetooth to the phone and is then displayed using a PIC and BT module. I am not using an arduino, but I think it is similar to the amarino apk. Any pointers or help you can give would be greatly appreciated.
Trevor
As I understand it, the code example is what we put in our app so the app can use bluetooth, correct? If so, how do we get the information from our bluetooth section of our code to actually use it in an app? I am trying to develop an app that will allow me to take in serial data via bluetooth and then display it. Specifically, I am trying to develop an interface to the user that gets data sent over bluetooth to the phone and is then displayed using a PIC and BT module. I am not using an arduino, but I think it is similar to the amarino apk. Any pointers or help you can give would be greatly appreciated.
Trevor
Vishal Rajpal
APIIT
Member since Apr 17, 2011
Forum Posts: 1
Forum Posts: 1
Hello Sir,
I am using bluetooth to send a string to other device to my application ...below is the code I have written..am nt recieving any errors...but unable to recieve the string...
package com.apiit.Andro_Blue;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
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 Andro_Blue extends Activity {
BluetoothAdapter adapter;
private static final int REQUEST_ENABLE_BT=1;
private static final int DISCOVERY_REQUEST=2;
Button on, scan, send, discover;
private ArrayAdapter<String> mNewDevicesArrayAdapter;
private ArrayAdapter<String> mPairedDevicesArrayAdapter;
private BluetoothSocket mmSocket=null;
private BluetoothDevice device=null;
private static final UUID MY_UUID = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
adapter=BluetoothAdapter.getDefaultAdapter();
on=(Button)findViewById(R.id.on);
scan=(Button)findViewById(R.id.Scan);
send=(Button)findViewById(R.id.Send);
discover=(Button)findViewById(R.id.Discoverable);
mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
//Switching Bluetooth ON From Here
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(mReceiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(mReceiver, filter);
final ListView pairedListView = (ListView) findViewById(R.id.paired_list);
pairedListView.setAdapter(mPairedDevicesArrayAdapter);
final Set<BluetoothDevice> pairedDevices = adapter.getBondedDevices();
//Click Listener For Switching Bluetooth On
on.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(adapter==null)
{
Toast.makeText(getApplicationContext(), "Device Dosen;t Supports Bluetooth", Toast.LENGTH_SHORT).show();
finish();
}else
if(!adapter.isEnabled())
{
Intent enablebt=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enablebt, REQUEST_ENABLE_BT);
}else
Toast.makeText(getApplicationContext(), "Bluetooth Already On", Toast.LENGTH_SHORT).show();
}
});
//Till Here
discover.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE),DISCOVERY_REQUEST);
}
});
//Scan For Device From Here (Click Listener)
scan.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (pairedDevices.size() > 0) {
findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
for (BluetoothDevice device : pairedDevices) {
mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
} else {
String noDevices ="No Devices Paired";
mPairedDevicesArrayAdapter.add(noDevices);
}
pairedListView.setAdapter(mPairedDevicesArrayAdapter);
pairedListView.setOnItemClickListener(mDeviceClickListener);
if (!adapter.isDiscovering())
{
Toast.makeText(getApplicationContext(), "devicename", Toast.LENGTH_LONG).show();
adapter.startDiscovery();
ListView newDevicesListView = (ListView) findViewById(R.id.list);
newDevicesListView.setAdapter(mNewDevicesArrayAdapter);
newDevicesListView.setOnItemClickListener(mDeviceClickListener);
}
}
});
// Till Here
}
//Receiver for found devices From Here
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
findViewById(R.id.title_found_devices).setVisibility(View.VISIBLE);
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// If it's already paired, skip it, because it's been listed already
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
// When discovery is finished, change the Activity title
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
setProgressBarIndeterminateVisibility(false);
setTitle("Select Device");
if (mNewDevicesArrayAdapter.getCount() == 0) {
String noDevices = "No Devices";
mNewDevicesArrayAdapter.add(noDevices);
}
}
}
};
// Till Here
private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View v, int arg2,
long arg3) {
// TODO Auto-generated method stub
String info = ((TextView) v).getText().toString();
String address = info.substring(info.length() - 17);
device = adapter.getRemoteDevice(address);
Toast.makeText(getApplicationContext(), arg3 + "cONNECTING", Toast.LENGTH_SHORT).show();
try {
mmSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
mmSocket.connect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), address, Toast.LENGTH_SHORT).show();
sendMessage("koi");
String MSG=listenForMessage();
Toast.makeText(getApplicationContext(), MSG, Toast.LENGTH_SHORT).show();
}
};
private void sendMessage(String message){
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
OutputStream outStream;
try {
outStream = mmSocket.getOutputStream();
// Add a stop character.
byte[] byteArray = (message + " ").getBytes();
byteArray[byteArray.length - 1] = 0;
outStream.write(byteArray);
} catch (IOException e) { }
}
private String listenForMessage(){
Toast.makeText(getApplicationContext(), "inListen", Toast.LENGTH_SHORT).show();
String result = "";
String message="";
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
try {
InputStream instream = mmSocket.getInputStream();
int bytesRead = -1;
while (true) {
bytesRead = instream.read(buffer);
if (bytesRead != -1) {
while ((bytesRead == bufferSize) && (buffer[bufferSize-1] != 0)){
message = message + new String(buffer, 0, bytesRead);
bytesRead = instream.read(buffer);
}
message = message + new String(buffer, 0, bytesRead - 1);
Toast.makeText(getApplicationContext(), message + "2", Toast.LENGTH_SHORT).show();
return result;
}
}
} catch (IOException e) {}
return result;
}
protected void onActivityResult(int requestCode,int resultCode, Intent data) {
if (requestCode == DISCOVERY_REQUEST) {
Toast.makeText(getApplicationContext(), "In Discovery", Toast.LENGTH_SHORT).show();
boolean isDiscoverable = resultCode > 0;
int discoverableDuration = resultCode;
if (isDiscoverable) {
UUID uuid = UUID.fromString("a60f35f0-b93a-11de-8a39-08002009c666");
String name = "bluetoothserver";
final BluetoothServerSocket btserver;
try {
btserver = adapter.listenUsingRfcommWithServiceRecord(name, uuid);
Thread acceptThread = new Thread(new Runnable() {
public void run() {
try {
BluetoothSocket serverSocket = btserver.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
acceptThread.start();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
}
Your help will be apprecieted,...
I am using bluetooth to send a string to other device to my application ...below is the code I have written..am nt recieving any errors...but unable to recieve the string...
package com.apiit.Andro_Blue;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
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 Andro_Blue extends Activity {
BluetoothAdapter adapter;
private static final int REQUEST_ENABLE_BT=1;
private static final int DISCOVERY_REQUEST=2;
Button on, scan, send, discover;
private ArrayAdapter<String> mNewDevicesArrayAdapter;
private ArrayAdapter<String> mPairedDevicesArrayAdapter;
private BluetoothSocket mmSocket=null;
private BluetoothDevice device=null;
private static final UUID MY_UUID = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
adapter=BluetoothAdapter.getDefaultAdapter();
on=(Button)findViewById(R.id.on);
scan=(Button)findViewById(R.id.Scan);
send=(Button)findViewById(R.id.Send);
discover=(Button)findViewById(R.id.Discoverable);
mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
//Switching Bluetooth ON From Here
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(mReceiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(mReceiver, filter);
final ListView pairedListView = (ListView) findViewById(R.id.paired_list);
pairedListView.setAdapter(mPairedDevicesArrayAdapter);
final Set<BluetoothDevice> pairedDevices = adapter.getBondedDevices();
//Click Listener For Switching Bluetooth On
on.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(adapter==null)
{
Toast.makeText(getApplicationContext(), "Device Dosen;t Supports Bluetooth", Toast.LENGTH_SHORT).show();
finish();
}else
if(!adapter.isEnabled())
{
Intent enablebt=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enablebt, REQUEST_ENABLE_BT);
}else
Toast.makeText(getApplicationContext(), "Bluetooth Already On", Toast.LENGTH_SHORT).show();
}
});
//Till Here
discover.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE),DISCOVERY_REQUEST);
}
});
//Scan For Device From Here (Click Listener)
scan.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (pairedDevices.size() > 0) {
findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
for (BluetoothDevice device : pairedDevices) {
mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
} else {
String noDevices ="No Devices Paired";
mPairedDevicesArrayAdapter.add(noDevices);
}
pairedListView.setAdapter(mPairedDevicesArrayAdapter);
pairedListView.setOnItemClickListener(mDeviceClickListener);
if (!adapter.isDiscovering())
{
Toast.makeText(getApplicationContext(), "devicename", Toast.LENGTH_LONG).show();
adapter.startDiscovery();
ListView newDevicesListView = (ListView) findViewById(R.id.list);
newDevicesListView.setAdapter(mNewDevicesArrayAdapter);
newDevicesListView.setOnItemClickListener(mDeviceClickListener);
}
}
});
// Till Here
}
//Receiver for found devices From Here
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
findViewById(R.id.title_found_devices).setVisibility(View.VISIBLE);
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// If it's already paired, skip it, because it's been listed already
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
// When discovery is finished, change the Activity title
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
setProgressBarIndeterminateVisibility(false);
setTitle("Select Device");
if (mNewDevicesArrayAdapter.getCount() == 0) {
String noDevices = "No Devices";
mNewDevicesArrayAdapter.add(noDevices);
}
}
}
};
// Till Here
private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View v, int arg2,
long arg3) {
// TODO Auto-generated method stub
String info = ((TextView) v).getText().toString();
String address = info.substring(info.length() - 17);
device = adapter.getRemoteDevice(address);
Toast.makeText(getApplicationContext(), arg3 + "cONNECTING", Toast.LENGTH_SHORT).show();
try {
mmSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
mmSocket.connect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), address, Toast.LENGTH_SHORT).show();
sendMessage("koi");
String MSG=listenForMessage();
Toast.makeText(getApplicationContext(), MSG, Toast.LENGTH_SHORT).show();
}
};
private void sendMessage(String message){
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
OutputStream outStream;
try {
outStream = mmSocket.getOutputStream();
// Add a stop character.
byte[] byteArray = (message + " ").getBytes();
byteArray[byteArray.length - 1] = 0;
outStream.write(byteArray);
} catch (IOException e) { }
}
private String listenForMessage(){
Toast.makeText(getApplicationContext(), "inListen", Toast.LENGTH_SHORT).show();
String result = "";
String message="";
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
try {
InputStream instream = mmSocket.getInputStream();
int bytesRead = -1;
while (true) {
bytesRead = instream.read(buffer);
if (bytesRead != -1) {
while ((bytesRead == bufferSize) && (buffer[bufferSize-1] != 0)){
message = message + new String(buffer, 0, bytesRead);
bytesRead = instream.read(buffer);
}
message = message + new String(buffer, 0, bytesRead - 1);
Toast.makeText(getApplicationContext(), message + "2", Toast.LENGTH_SHORT).show();
return result;
}
}
} catch (IOException e) {}
return result;
}
protected void onActivityResult(int requestCode,int resultCode, Intent data) {
if (requestCode == DISCOVERY_REQUEST) {
Toast.makeText(getApplicationContext(), "In Discovery", Toast.LENGTH_SHORT).show();
boolean isDiscoverable = resultCode > 0;
int discoverableDuration = resultCode;
if (isDiscoverable) {
UUID uuid = UUID.fromString("a60f35f0-b93a-11de-8a39-08002009c666");
String name = "bluetoothserver";
final BluetoothServerSocket btserver;
try {
btserver = adapter.listenUsingRfcommWithServiceRecord(name, uuid);
Thread acceptThread = new Thread(new Runnable() {
public void run() {
try {
BluetoothSocket serverSocket = btserver.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
acceptThread.start();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
}
Your help will be apprecieted,...
Shan Ali
CIIT
Member since May 28, 2011
Forum Posts: 1
Forum Posts: 1
Hi Marko
Your tutorial helped me a lot but as you know that the emulator does not supports Bluetooth so i will test the code on real device. on thing i wan't to know that after getting the list of bluetooth devices how can i connect to a device's Bluetooth and transmit my data to that device via bluetooth.
I shall be very thankful to you.
Regards
Shan
Your tutorial helped me a lot but as you know that the emulator does not supports Bluetooth so i will test the code on real device. on thing i wan't to know that after getting the list of bluetooth devices how can i connect to a device's Bluetooth and transmit my data to that device via bluetooth.
I shall be very thankful to you.
Regards
Shan
Edited one time. Last edit by Shan Ali on May 28, 2011 at 12:07:14 PM (about 2 years ago).
Madhuri Rajput
Cognizant
Member since Aug 11, 2011
Forum Posts: 1
Forum Posts: 1
Can you please tell me how to define package here... I dint got how to define it...
Ankit VermaEngineer
Member since Apr 20, 2011
Forum Posts: 1
Forum Posts: 1
Enabling bluetooth support on emulator would help developers a lot
Edited 2 times. Last edit by Ankit Verma on Sep 23, 2011 at 12:04:22 PM (about 2 years ago).
Umang Patel
GMD
Member since Oct 14, 2011
Forum Posts: 1
Forum Posts: 1
Hi Marko,
Is it any method to get the status of connected Bluetooth Headset with Android OS???
or Is there any way to get the status of connected Bluetooth Headset with Android OS?
Is it any method to get the status of connected Bluetooth Headset with Android OS???
or Is there any way to get the status of connected Bluetooth Headset with Android OS?
Hagop "Jack" Bilemjian
TrekOnTrek.com
Member since Jan 26, 2012
Forum Posts: 1
Forum Posts: 1
Hi Marko,
Can you suggest an approach to connect and send a PCL file to a Bluetooth printer? Or, how can I send an image to a printer?
Thanks
Jack
Can you suggest an approach to connect and send a PCL file to a Bluetooth printer? Or, how can I send an image to a printer?
Thanks
Jack
Bert Briones
INDIVIDUAL
Member since Oct 24, 2012
Forum Posts: 1
Forum Posts: 1
I'm a veteran coder for desktop but a newbie for Android Platform. Is there any way to have an Android App connect to another app in the same phone using a virtualized form of BlueTooth. I am trying to write code that will send data to BT and wish to have another App to read that information.
I understand that there are IPC/intents/etc, but the other APP that consumes the BT data is a 3rd party app and nothing that I wrote.
Thx
I understand that there are IPC/intents/etc, but the other APP that consumes the BT data is a 3rd party app and nothing that I wrote.
Thx
Eric Jonathan
Student
Member since Dec 16, 2012
Forum Posts: 1
Forum Posts: 1
Dear , sir
After i pared my Bluetooth adapter, how can i read the input data from my adapter.
I am currently using arduino + bluetooth adapter -> Android. The concept is about arduino measure data send to android. android read data and calculate it
best
Eric
After i pared my Bluetooth adapter, how can i read the input data from my adapter.
I am currently using arduino + bluetooth adapter -> Android. The concept is about arduino measure data send to android. android read data and calculate it
best
Eric
Taher Kawantwala
Ambimat electronics
Member since Dec 31, 2012
Forum Posts: 1
Forum Posts: 1
You need to have the uses-permission tags after the Application block else you will get an BLUETOOTH_ADMIN permission exception which leads to the "application has stopped unexpectedly" error.
The correct Manifest file is:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.marakana" android:versionCode="1" android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name"
android:theme="@android:style/Theme.Light">
<activity android:name=".BluetoothDemo" 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>
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-sdk android:minSdkVersion="5" />
</manifest>
i am having the same problem with my Bluetooth remote app which communicate with ATmega16.
when i connect the Bluetooth modem with controller Android app stop working. but when module is not connected to Controller it works fine. i have checked it LogCat but im not able to understand it
my manifestfile
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.yarin.android.Examples_08_09"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon2" android:label="@string/app_name">
<activity android:name=".Activity01"
android:label="AmbimatElectronics">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".DiscoveryActivity"
android:theme="@style/Theme.Transparent">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity android:name=".ClientSocketActivity"
android:label="ClientToBluetoothBee"
android:windowSoftInputMode="stateVisible|adjustPan">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity android:name=".ServerSocketActivity"
android:theme="@style/Theme.Transparent">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity android:name=".OBEXActivity"
android:theme="@style/Theme.Transparent">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion="5" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.READ_CONTACTS"/>
</manifest>