i am coding an android app. The app begins at the main screen then click the button to go the activity. My code does not have any error and build fine. However launching the app and click the button result in a crash.
My Manifest.XML
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.androidbtcontrol">
<uses-permission android:name="android.permission.BLUETOOTH" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<activity
android:name=".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>
<activity android:name=".bluetoothconnect">
<intent-filter>
<action android:name="com.example.androidbtcontrol.bluetoothconnect" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
MainActivity.java
public void OnclickButtonListener(){
button_1 = (Button)findViewById(R.id.button);
button_1.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent("com.example.androidbtcontrol.bluetoothconnect");
startActivity(intent);
}
}
);
}
}
bluetoothconnect.java
public class bluetoothconnect extends AppCompatActivity {
protected void onCreate3(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetoothconnect);
}
private static final int REQUEST_ENABLE_BT = 1;
BluetoothAdapter bluetoothAdapter;
ArrayList<BluetoothDevice> pairedDeviceArrayList;
TextView textInfo, textStatus;
ListView listViewPairedDevice;
RelativeLayout inputPane;
SeekBar barAnalogOut;
ArrayAdapter<BluetoothDevice> pairedDeviceAdapter;
private UUID myUUID;
private final String UUID_STRING_WELL_KNOWN_SPP =
"00001101-0000-1000-8000-00805F9B34FB";
ThreadConnectBTdevice myThreadConnectBTdevice;
ThreadConnected myThreadConnected;
protected void onCreate2(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textInfo = (TextView)findViewById(R.id.info);
textStatus = (TextView)findViewById(R.id.status);
listViewPairedDevice = (ListView)findViewById(R.id.pairedlist);
inputPane = (RelativeLayout) findViewById(R.id.inputpane);
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH)){
Toast.makeText(this,
"FEATURE_BLUETOOTH NOT support",
Toast.LENGTH_LONG).show();
finish();
return;
}
//using the well-known SPP UUID
myUUID = UUID.fromString(UUID_STRING_WELL_KNOWN_SPP);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
Toast.makeText(this,
"Bluetooth is not supported on this hardware platform",
Toast.LENGTH_LONG).show();
finish();
return;
}
String stInfo = bluetoothAdapter.getName() + "\n" +
bluetoothAdapter.getAddress();
textInfo.setText(stInfo);
barAnalogOut = (SeekBar)findViewById(R.id.analogOut);
barAnalogOut.setOnSeekBarChangeListener(OnAnalogOutChangeListener);
}
SeekBar.OnSeekBarChangeListener OnAnalogOutChangeListener =
new SeekBar.OnSeekBarChangeListener(){
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
//will generate too much data sent!
//SendAnalogOut(progress);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
SendAnalogOut(seekBar.getProgress());
}
};
private final byte SYNC_BYTE = (byte) 0xAA;
private final byte LENGTH_ANALOG = (byte) 3;
private final byte CMD_ANALOG = (byte) 1;
private void SendAnalogOut(int val){
byte[] bytesToSend = {SYNC_BYTE, LENGTH_ANALOG, CMD_ANALOG, (byte) val};
myThreadConnected.write(bytesToSend);
}
#Override
protected void onStart() {
super.onStart();
//Turn ON BlueTooth if it is OFF
if (!bluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
}
setup();
}
private void setup() {
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
pairedDeviceArrayList = new ArrayList<BluetoothDevice>();
for (BluetoothDevice device : pairedDevices) {
pairedDeviceArrayList.add(device);
}
pairedDeviceAdapter = new ArrayAdapter<BluetoothDevice>(this,
android.R.layout.simple_list_item_1, pairedDeviceArrayList);
listViewPairedDevice.setAdapter(pairedDeviceAdapter);
listViewPairedDevice.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
BluetoothDevice device =
(BluetoothDevice) parent.getItemAtPosition(position);
Toast.makeText(bluetoothconnect.this,
"Name: " + device.getName() + "\n"
+ "Address: " + device.getAddress() + "\n"
+ "BondState: " + device.getBondState() + "\n"
+ "BluetoothClass: " + device.getBluetoothClass() + "\n"
+ "Class: " + device.getClass(),
Toast.LENGTH_LONG).show();
textStatus.setText("start ThreadConnectBTdevice");
myThreadConnectBTdevice = new ThreadConnectBTdevice(device);
myThreadConnectBTdevice.start();
}
});
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if(myThreadConnectBTdevice!=null){
myThreadConnectBTdevice.cancel();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode==REQUEST_ENABLE_BT){
if(resultCode == Activity.RESULT_OK){
setup();
}else{
Toast.makeText(this,
"BlueTooth NOT enabled",
Toast.LENGTH_SHORT).show();
finish();
}
}
}
//Called in ThreadConnectBTdevice once connect successed
//to start ThreadConnected
private void startThreadConnected(BluetoothSocket socket){
myThreadConnected = new ThreadConnected(socket);
myThreadConnected.start();
}
/*
ThreadConnectBTdevice:
Background Thread to handle BlueTooth connecting
*/
private class ThreadConnectBTdevice extends Thread {
private BluetoothSocket bluetoothSocket = null;
private final BluetoothDevice bluetoothDevice;
private ThreadConnectBTdevice(BluetoothDevice device) {
bluetoothDevice = device;
try {
bluetoothSocket = device.createRfcommSocketToServiceRecord(myUUID);
textStatus.setText("bluetoothSocket: \n" + bluetoothSocket);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void run() {
ToggleButton toggle = (ToggleButton) findViewById(R.id.toggleButton);
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
SendAnalogOut( 0);
// The toggle is enabled
} else {
SendAnalogOut( 255);
// The toggle is disabled
}
}
});
boolean success = false;
try {
bluetoothSocket.connect();
success = true;
} catch (IOException e) {
e.printStackTrace();
final String eMessage = e.getMessage();
runOnUiThread(new Runnable() {
#Override
public void run() {
textStatus.setText("Something wrong BluetoothSocket.connect(): \n" + eMessage);
}
});
try {
bluetoothSocket.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
if(success){
//connect successful
final String msgconnected = "Connect Successful:\n"
+ "BluetoothSocket: " + bluetoothSocket + "\n"
+ "BluetoothDevice: " + bluetoothDevice;
runOnUiThread(new Runnable(){
#Override
public void run() {
textStatus.setText(msgconnected);
listViewPairedDevice.setVisibility(View.GONE);
inputPane.setVisibility(View.VISIBLE);
}});
startThreadConnected(bluetoothSocket);
}else{
//fail
}
}
public void cancel() {
Toast.makeText(getApplicationContext(),
"close bluetoothSocket",
Toast.LENGTH_LONG).show();
try {
bluetoothSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/*
ThreadConnected:
Background Thread to handle Bluetooth data communication
after connected
*/
private class ThreadConnected extends Thread {
private final BluetoothSocket connectedBluetoothSocket;
private final InputStream connectedInputStream;
private final OutputStream connectedOutputStream;
public ThreadConnected(BluetoothSocket socket) {
connectedBluetoothSocket = socket;
InputStream in = null;
OutputStream out = null;
try {
in = socket.getInputStream();
out = socket.getOutputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
connectedInputStream = in;
connectedOutputStream = out;
}
#Override
public void run() {
byte[] buffer = new byte[1024];
int bytes;
while (true) {
try {
bytes = connectedInputStream.read(buffer);
String strReceived = new String(buffer, 0, bytes);
final String msgReceived = String.valueOf(bytes) +
" bytes received:\n"
+ strReceived;
runOnUiThread(new Runnable() {
#Override
public void run() {
textStatus.setText(msgReceived);
}});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
final String msgConnectionLost = "Connection lost:\n"
+ e.getMessage();
runOnUiThread(new Runnable(){
#Override
public void run() {
textStatus.setText(msgConnectionLost);
}});
}
}
}
public void write(byte[] buffer) {
try {
connectedOutputStream.write(buffer);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void cancel() {
try {
connectedBluetoothSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Main Layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:autoLink="web"
android:text="Please Choose "
android:textStyle="bold" />
<Button
android:text="Button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/button" />
</LinearLayout>
Activity Layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_bluetoothconnect"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.androidbtcontrol.bluetoothconnect">
<TextView
android:id="#+id/info"
android:textStyle="bold|italic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/status"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ListView
android:id="#+id/pairedlist"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<RelativeLayout
android:id="#+id/inputpane"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:visibility="gone">
</RelativeLayout>
<SeekBar
android:id="#+id/analogOut"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="99"
android:progress="0"/>
<ToggleButton
android:text="ToggleButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/toggleButton" />
</RelativeLayout>
These are some of the mistakes I can spot from the information you have given. Post the logcat exception details so that I can refine on this solution.
1) Don't use your own version of onCreate (in bluetoothactivity). An activity should have only one onCreate method. You also need to add the #Override prefix to the onCreate method. The code you have contains onCreate2 and onCreate3 methods which are erroneous. That may be the reason for the crash, since when the bluetooth activity is called, it can't find the onCreate method.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Keep your bluetooth related functionality here.
}
2) When launching your intent, you need to specify the source and the destination too.
Intent intent = new Intent(CallingActivity.this,CalledActivity.class);
startActivity(intent);
Your crash maybe caused due to your intent,in activity
Intent intent = new Intent("com.example.androidbtcontrol.bluetoothconnect");
startActivity(intent);
the right way
Intent intent=new Intent(firstactivity.this,secondactivity.class);
startactivity(intent);
you need to specify the destination
Related
public class BluetoothActivity extends Activity {
// Create a BroadcastReceiver for ACTION_FOUND
private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// Whenever a remote Bluetooth device is found
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the name and address to an array adapter to show in a ListView
adapter.add(bluetoothDevice.getName() + "\n"
+ bluetoothDevice.getAddress());
}
}
};
//declaration
TextView myLabel;
Thread workerThread;
byte[] readBuffer;
int readBufferPosition;
volatile boolean stopWorker;
private BluetoothAdapter mBluetoothAdapter;
private ListView listview;
private ArrayAdapter adapter;
private ToggleButton toggleButton;
private static final int REQUEST_ENABLE_BT =0;
private static final int DISCOVERABLE_DURATION = 0;
private static final int DISCOVERABLE_BT_REQUEST_CODE = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bluetooth_main);
toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
listview = (ListView) findViewById(R.id.listView);
// ListView Item Click Listener
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// ListView Clicked item value
String itemValue = (String) listview.getItemAtPosition(position);
Toast.makeText(getApplicationContext(), "clicked", Toast.LENGTH_LONG).show();
String MAC = itemValue.substring(itemValue.length() - 17);
BluetoothDevice bluetoothDevice = mBluetoothAdapter.getRemoteDevice(MAC);
// Initiate a connection request in a separate thread
ConnectingThread t = new ConnectingThread(bluetoothDevice);
t.start();
}
});
adapter = new ArrayAdapter
(this,android.R.layout.simple_list_item_1);
listview.setAdapter(adapter);
//verify bluetooth is supported on the device
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// Device does not support Bluetooth
if (mBluetoothAdapter == null) {
}
}//end oncreate
public void onToggle(View view) {
adapter.clear();
if (toggleButton.isChecked()){
//enable bluetooth
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
Toast.makeText(getApplicationContext(), "Turned on", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(),"Already on", Toast.LENGTH_LONG).show();
//To discover remote Bluetooth devices
discoverDevices();
// Make local device discoverable by other devices
makeDiscoverable();
}
}//end of 1st if
else{
//turn off bluetooth
mBluetoothAdapter.disable();
adapter.clear();
Toast.makeText(getApplicationContext(),"Turned off" ,Toast.LENGTH_LONG).show();
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_ENABLE_BT) {
// Bluetooth successfully enabled!
if (resultCode == Activity.RESULT_OK) {
Toast.makeText(getApplicationContext(), "Bluetooth is now enabled.",Toast.LENGTH_SHORT).show();
// Make local device discoverable by other devices
makeDiscoverable();
// To discover remote Bluetooth devices
Log.e("calldiscover", "func");
discoverDevices();
Log.e("Discover", "device");
// Start a thread to create a server socket to listen
// for connection request
Log.e("listenthread", "listenthread");
ListeningThread t = new ListeningThread();
Log.e("call", "t.start");
t.start();
Log.e("t.start", "over");
}
else {
// RESULT_CANCELED as user refused
Toast.makeText(getApplicationContext(), "Bluetooth is not enabled.",
Toast.LENGTH_SHORT).show();
// Turn off togglebutton
toggleButton.setChecked(false);
}
}//end of 1st if
}
protected void discoverDevices(){
// To scan for remote Bluetooth devices
if (mBluetoothAdapter.startDiscovery()) {Log.e("disc", "print");
Toast.makeText(getApplicationContext(), "Discovering other bluetooth devices...", Toast.LENGTH_SHORT).show();
}
else {
Log.e("print", "print");
Toast.makeText(getApplicationContext(), "Discovery failed to start.", Toast.LENGTH_SHORT).show();
}
}
protected void makeDiscoverable(){
// Make local device discoverable
Intent discoverableIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, DISCOVERABLE_DURATION);
startActivityForResult(discoverableIntent, DISCOVERABLE_BT_REQUEST_CODE);
}
#Override
protected void onResume() {
super.onResume();
// Register the BroadcastReceiver for ACTION_FOUND
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(broadcastReceiver, filter);
}
#Override
protected void onPause() {
super.onPause();
this.unregisterReceiver(broadcastReceiver);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class ListeningThread extends Thread {
private final BluetoothServerSocket bluetoothServerSocket;
public ListeningThread() {
BluetoothServerSocket temp = null;
try {
temp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(getString(R.string.app_name), uuid);
} catch (IOException e) {
e.printStackTrace();
}
bluetoothServerSocket = temp;
}
public void run() {
BluetoothSocket bluetoothSocket;
// This will block while listening until a BluetoothSocket is returned
// or an exception occurs
while (true) {
try {
Log.e("while", "over");
bluetoothSocket = bluetoothServerSocket.accept();
Log.e("bt", "accept");
} catch (IOException e) {Log.e("error", "catch");
break;
}
// If a connection is accepted
if (bluetoothSocket != null) {
Log.e("connection is accepted", "over");
BluetoothActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(BluetoothActivity.this, "Connected!", Toast.LENGTH_SHORT).show();
}
});
// Manage the connection in a separate thread
try {Log.e("callserver", "close");
bluetoothServerSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}//end of while
}
// Cancel the listening socket and terminate the thread
public void cancel() {
try {Log.e("cancel", "socket");
bluetoothServerSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//Setting Up a Connecting Client
private class ConnectingThread extends Thread {
OutputStream mmOutputStream;
InputStream mmInputStream;
private final BluetoothSocket bluetoothSocket;
private final BluetoothDevice bluetoothDevice;
public ConnectingThread(BluetoothDevice device) {
BluetoothSocket temp = null;
bluetoothDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try { Log.e("click6", "click6");
temp = bluetoothDevice.createRfcommSocketToServiceRecord(uuid);
} catch (IOException e) {
e.printStackTrace();
}
bluetoothSocket = temp;
}
public void run() {
// Cancel any discovery as it will slow down the connection
Log.e("click7", "click7");
mBluetoothAdapter.cancelDiscovery();
Log.e("click8", "click8");
try {
// This will block until it succeeds in connecting to the device
// through the bluetoothSocket or throws an exception
bluetoothSocket.connect();
mmOutputStream = bluetoothSocket.getOutputStream();
mmInputStream = bluetoothSocket.getInputStream();
beginListenForData();
Log.e("listendata", "lsitendata");
BluetoothActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(BluetoothActivity.this, "Connected with Device!", Toast.LENGTH_SHORT).show();
}
});
Log.e("click9", "click9");
} catch (IOException connectException) {
connectException.printStackTrace();
try {
bluetoothSocket.close();
Log.e("click6", "blueclose");
} catch (IOException closeException) {
closeException.printStackTrace();
}
}
}
void beginListenForData()
{
final Handler handler = new Handler();
final byte delimiter = 10; //This is the ASCII code for a newline character
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];//It uses a 1024 bytes long buffer because it doesn't have any way of knowing the length of the input stream.
workerThread = new Thread(new Runnable()
{
public void run()
{
while(!Thread.currentThread().isInterrupted() && !stopWorker)
{
try
{
int bytesAvailable = mmInputStream.available();
if(bytesAvailable > 0)
{
byte[] packetBytes = new byte[bytesAvailable];
mmInputStream.read(packetBytes);
for(int i=0;i<bytesAvailable;i++)
{
byte b = packetBytes[i];
if(b == delimiter)
{
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
final String data = new String(encodedBytes, "US-ASCII");
readBufferPosition = 0;
handler.post(new Runnable()
{
public void run()
{
myLabel.setText(data);
}
});
}
else
{
readBuffer[readBufferPosition++] = b;
}
}
}
}
catch (IOException ex)
{
stopWorker = true;
}
}
}
});
workerThread.start();
}
Hi the app crashed when I try to call beginListenForData(); The error state that Can't create handler inside thread that has not called Looper.prepare()
Does anyone know what wrong? I am new to android. Please help.
Bluetooth.xml below
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".BluetoothActivity">
<ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="Turn off Bluetooth"
android:textOff="Turn on Bluetooth"
android:id="#+id/toggleButton"
android:onClick="onToggle"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:layout_alignParentStart="true"
android:layout_marginStart="76dp"
android:layout_below="#+id/toggleButton" />
<TextView
android:id="#+id/label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Type here:"
android:layout_below="#+id/toggleButton"
android:layout_centerHorizontal="true"
android:layout_marginTop="66dp" />
</RelativeLayout>
Try this inside beginListenForData()
Replace
final Handler handler = new Handler();
With this
final Handler handler = new Handler(Looper.getMainLooper());
I am creating a basic android application with a client - server chat, a link to a website and on option to open a database (that I am yet to create). I have created a button to open the activity for the database but nothing happens when I press the button.
Here is my application main activity;
public class AndroidChatApplicationActivity extends Activity {
private Handler handler = new Handler();
public ListView msgView;
public ArrayAdapter<String> msgList;
// public ArrayAdapter<String> msgList=new ArrayAdapter<String>(this,
// android.R.layout.simple_list_item_1);;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
msgView = (ListView) findViewById(R.id.listView);
msgList = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1);
msgView.setAdapter(msgList);
// msgView.smoothScrollToPosition(msgList.getCount() - 1);
Button btnSend = (Button) findViewById(R.id.btn_Send);
receiveMsg();
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final EditText txtEdit = (EditText) findViewById(R.id.txt_inputText);
// msgList.add(txtEdit.getText().toString());
sendMessageToServer(txtEdit.getText().toString());
msgView.smoothScrollToPosition(msgList.getCount() - 1);
}
});
Button websiteButton = (Button) findViewById(R.id.website_Button);
websiteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendToWebsite();
}
});
}
protected void sendToWebsite() {
String url = "https://www.ljmu.ac.uk/";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
Button databaseButton = (Button) findViewById(R.id.database);
databaseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(AndroidChatApplicationActivity.this,
Database.class));
}
});
}
// receiveMsg();
// ----------------------------
// server msg receieve
// -----------------------
// End Receive msg from server//
public void sendMessageToServer(String str) {
final String str1 = str;
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
// String host = "opuntia.cs.utep.edu";
String host = "10.0.2.2";
String host2 = "127.0.0.1";
PrintWriter out;
try {
Socket socket = new Socket(host, 8008);
out = new PrintWriter(socket.getOutputStream());
// out.println("hello");
out.println(str1);
Log.d("", "test");
out.flush();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("", "test2");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("", "test3");
}
}
}).start();
}
public void receiveMsg() {
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
// final String host="opuntia.cs.utep.edu";
final String host = "10.0.2.2";
// final String host="localhost";
Socket socket = null;
BufferedReader in = null;
try {
socket = new Socket(host, 8008);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (true) {
String msg = null;
try {
msg = in.readLine();
Log.d("", "MSGGG: " + msg);
// msgList.add(msg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (msg == null) {
break;
} else {
displayMsg(msg);
}
}
}
}).start();
}
public void displayMsg(String msg) {
final String mssg = msg;
handler.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
msgList.add(mssg);
msgView.setAdapter(msgList);
msgView.smoothScrollToPosition(msgList.getCount() - 1);
Log.d("", "Hi Test");
}
});
}
}
Here is my manifest;
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="edu.UTEP.android"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<application
android:allowTaskReparenting="false"
android:icon="#drawable/icon"
android:label="#string/app_name" >
<activity
android:name="androidChat.AndroidChatApplicationActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="androidChat.Database" >
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
And here is database as it stands;
import android.app.Activity;
import android.os.Bundle;
import edu.UTEP.android.R;
public class Database extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.database);
}
}
As you said that "nothing happens", I'm assuming your button clickListener isn't even get called. Try moving this to your OnCreate method:
Button databaseButton = (Button) findViewById(R.id.database);
databaseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(AndroidChatApplicationActivity.this,
Database.class));
}
});
I was searching Google and found a code in stackoverflow. I started using it but the line list.setAdapter(aa); is generating NullPointerException. How can I resolve it? Here is my MainActivity.java:
public class MainActivity extends Activity {
private static int DISCOVERY_REQUEST = 1;
private Handler handler = new Handler();
private ArrayList<BluetoothDevice> foundDevices;
private ArrayAdapter<BluetoothDevice> aa;
private ListView list;
private BluetoothAdapter bluetooth;
private BluetoothSocket socket;
private UUID uuid = UUID.fromString("a60f35f0-b93a-11de-8a39-08002009c666");
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
configureBluetooth();
setupListView();
setupSearchButton();
setupListenButton();
}
private void configureBluetooth() {
bluetooth = BluetoothAdapter.getDefaultAdapter();
}
private void setupListenButton() {
Button listenButton = (Button) findViewById(R.id.button_listen);
listenButton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
Intent disc = new Intent(
BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(disc, DISCOVERY_REQUEST);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == DISCOVERY_REQUEST) {
boolean isDiscoverable = resultCode > 0;
if (isDiscoverable) {
String name = "bluetoothserver";
try {
final BluetoothServerSocket btserver = bluetooth
.listenUsingRfcommWithServiceRecord(name, uuid);
AsyncTask<Integer, Void, BluetoothSocket> acceptThread = new AsyncTask<Integer, Void, BluetoothSocket>() {
#Override
protected BluetoothSocket doInBackground(
Integer... params) {
try {
socket = btserver.accept(params[0] * 1000);
return socket;
} catch (IOException e) {
Log.d("BLUETOOTH", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(BluetoothSocket result) {
if (result != null)
switchUI();
}
};
acceptThread.execute(resultCode);
} catch (IOException e) {
Log.d("BLUETOOTH", e.getMessage());
}
}
}
}
private void setupListView() {
aa = new ArrayAdapter<BluetoothDevice>(this,
android.R.layout.simple_list_item_1, foundDevices);
list = (ListView) findViewById(R.id.list_discovered);
list.setAdapter(aa); //the error comes from this line
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View view, int index,
long arg3) {
AsyncTask<Integer, Void, Void> connectTask = new AsyncTask<Integer, Void, Void>() {
#Override
protected Void doInBackground(Integer... params) {
try {
BluetoothDevice device = foundDevices
.get(params[0]);
socket = device
.createRfcommSocketToServiceRecord(uuid);
socket.connect();
} catch (IOException e) {
Log.d("BLUETOOTH_CLIENT", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(Void result) {
switchUI();
}
};
connectTask.execute(index);
}
});
}
private void setupSearchButton() {
Button searchButton = (Button) findViewById(R.id.button_search);
searchButton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
registerReceiver(discoveryResult, new IntentFilter(
BluetoothDevice.ACTION_FOUND));
if (!bluetooth.isDiscovering()) {
foundDevices.clear();
bluetooth.startDiscovery();
}
}
});
}
private void switchUI() {
final TextView messageText = (TextView) findViewById(R.id.text_messages);
final EditText textEntry = (EditText) findViewById(R.id.text_message);
messageText.setVisibility(View.VISIBLE);
list.setVisibility(View.GONE);
textEntry.setEnabled(true);
textEntry.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
if ((keyEvent.getAction() == KeyEvent.ACTION_DOWN)
&& (keyCode == KeyEvent.KEYCODE_DPAD_CENTER)) {
sendMessage(socket, textEntry.getText().toString());
textEntry.setText("");
return true;
}
return false;
}
});
BluetoothSocketListener bsl = new BluetoothSocketListener(socket,
handler, messageText);
Thread messageListener = new Thread(bsl);
messageListener.start();
}
private void sendMessage(BluetoothSocket socket, String msg) {
OutputStream outStream;
try {
outStream = socket.getOutputStream();
byte[] byteString = (msg + " ").getBytes();
byteString[byteString.length - 1] = 0;
outStream.write(byteString);
} catch (IOException e) {
Log.d("BLUETOOTH_COMMS", e.getMessage());
}
}
BroadcastReceiver discoveryResult = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
BluetoothDevice remoteDevice;
remoteDevice = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (bluetooth.getBondedDevices().contains(remoteDevice)) {
foundDevices.add(remoteDevice);
aa.notifyDataSetChanged();
}
}
};
private class MessagePoster implements Runnable {
private TextView textView;
private String message;
public MessagePoster(TextView textView, String message) {
this.textView = textView;
this.message = message;
}
public void run() {
textView.setText(message);
}
}
private class BluetoothSocketListener implements Runnable {
private BluetoothSocket socket;
private TextView textView;
private Handler handler;
public BluetoothSocketListener(BluetoothSocket socket, Handler handler,
TextView textView) {
this.socket = socket;
this.textView = textView;
this.handler = handler;
}
public void run() {
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
try {
InputStream instream = socket.getInputStream();
int bytesRead = -1;
String message = "";
while (true) {
message = "";
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);
handler.post(new MessagePoster(textView, message));
socket.getInputStream();
}
}
} catch (IOException e) {
Log.d("BLUETOOTH_COMMS", e.getMessage());
}
}
}
}
And the error is:
Caused by: java.lang.NullPointerException
at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:330)
at android.widget.ListView.setAdapter(ListView.java:464)
at com.example.testbluetooth.MainActivity.setupListView(MainActivity.java:113)
Here is my activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<EditText
android:id="#+id/text_message"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:enabled="false" />
<Button
android:id="#+id/button_search"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#id/text_message"
android:text="Search for listener" />
<Button
android:id="#+id/button_listen"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#id/button_search"
android:text="Listen for connection" />
<ListView
android:id="#+id/list_discovered"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#id/button_listen"
android:layout_alignParentTop="true" />
<TextView
android:id="#+id/text_messages"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#id/button_listen"
android:layout_alignParentTop="true"
android:visibility="gone" />
</RelativeLayout>
You have empty list, you are setting up array list before have list with devices.
Try to remove
setupListView() from onCreate()
and put it into place after list with devices is created.
You can try to do it in this way:
Initialize collection in your case just write private ArrayList<BluetoothDevice> foundDevices = new ArrayList<BluetoothDevice>();
When you get broadcast foundDevices.add(remoteDevice);
aa.addAll(foundDevices) and then call aa.notifyDataSetChanged();
References:
ArrayAdapter.AddAll()
I'm trying to send and receive voice mail via bluetooth.
But fail to do that, i searched alot but didnt found a gud tutorial for that.
can any body help me?
Please let me know where I'm doing wrong
Thanks alot
Here is my Updated Class BluetoothChat:
public class BluetoothChat extends Activity {
// Debugging
private static final String TAG = "BluetoothChat";
private static final boolean D = true;
boolean isRoute = true;
// Message types sent from the BluetoothChatService Handler
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_NAME = 4;
public static final int MESSAGE_TOAST = 5;
// Key names received from the BluetoothChatService Handler
public static final String DEVICE_NAME = "device_name";
public static final String TOAST = "toast";
// Intent request codes
private static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
private static final int REQUEST_CONNECT_DEVICE_INSECURE = 2;
private static final int REQUEST_ENABLE_BT = 3;
// Layout Views
private ListView mConversationView;
private EditText mOutEditText;
private Button mSendButton;
ToggleButton mspeakButton, mplayButton;
// Name of the connected device
private String mConnectedDeviceName = null;
// Array adapter for the conversation thread
private ArrayAdapter<String> mConversationArrayAdapter;
// String buffer for outgoing messages
private StringBuffer mOutStringBuffer;
// Local Bluetooth adapter
private BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// Member object for the chat services
private BluetoothChatService mChatService = null;
static AudioManager mAudioManager;
MediaRecorder myAudioRecorder;
private MediaRecorder myRecorder;
private MediaPlayer myPlayer;
File file;
private String outputFile = null;
boolean toggle = true;
String items = "";
String address = "";
String sdcard_path = "";
private TextView text1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (D)
Log.e(TAG, "+++ ON CREATE +++");
// Set up the window layout
setContentView(R.layout.main);
//outputFile = getIntent().getExtras().getString("output");
// Get local Bluetooth adapter
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// store it to sd card
outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/myRecording.mp3";
myRecorder = new MediaRecorder();
myRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myRecorder.setOutputFile(outputFile);
// If the adapter is null, then Bluetooth is not supported
if (mBluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
return;
}
else {
if (mBluetoothAdapter.isEnabled()) {
registerReceiver(ActionFoundReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
mBluetoothAdapter.startDiscovery();
}
}
}
#Override
public void onStart() {
super.onStart();
if (D)
Log.e(TAG, "++ ON START ++");
// If BT is not on, request that it be enabled.
// setupChat() will then be called during onActivityResult
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
// Otherwise, setup the chat session
}
else {
if (mChatService == null)
setupChat();
}
}
#Override
public synchronized void onResume() {
super.onResume();
if (D)
Log.e(TAG, "+ ON RESUME +");
// Performing this check in onResume() covers the case in which BT was
// not enabled during onStart(), so we were paused to enable it...
// onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
if (mChatService != null) {
// Only if the state is STATE_NONE, do we know that we haven't started already
if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
// Start the Bluetooth chat services
mChatService.start();
}
}
}
private void setupChat() {
Log.d(TAG, "setupChat()");
// Initialize the array adapter for the conversation thread
mConversationArrayAdapter = new ArrayAdapter<String>(this, R.layout.message);
mConversationView = (ListView) findViewById(R.id.in);
mConversationView.setAdapter(mConversationArrayAdapter);
// Initialize the compose field with a listener for the return key
mOutEditText = (EditText) findViewById(R.id.edit_text_out);
mOutEditText.setOnEditorActionListener(mWriteListener);
// Initialize the send button with a listener that for click events
mSendButton = (Button) findViewById(R.id.button_send);
mSendButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Send a message using content of the edit text widget
TextView view = (TextView) findViewById(R.id.edit_text_out);
String message = view.getText().toString();
sendMessage(message);
//SetRouteSco(BluetoothChat.this, isRoute);
}
});
text1 = (TextView) findViewById(R.id.text1);
// Initialize the speak button with a listener that for click events
mspeakButton = (ToggleButton) findViewById(R.id.button_speak);
mspeakButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (toggle) {
toggle = false;
sendvoice(v);
}
else {
toggle = true;
record(v);
}
}
});
// Initialize the play button with a listener that for click events
mplayButton = (ToggleButton) findViewById(R.id.button_play);
mplayButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (toggle) {
toggle = false;
stopPlay(v);
}
else {
toggle = true;
play(v);
}
}
});
// Initialize the BluetoothChatService to perform bluetooth connections
mChatService = new BluetoothChatService(this, mHandler);
// Initialize the buffer for outgoing messages
mOutStringBuffer = new StringBuffer("");
}
public void sendvoice(View view) {
try {
myRecorder.stop();
myRecorder.release();
myRecorder = null;
text1.setText("Recording Point: Stop recording");
Toast.makeText(getApplicationContext(), "Stop recording...", Toast.LENGTH_SHORT).show();
if (mBluetoothAdapter.isEnabled()) {
Log.d("btAdapter", "btAdapter" + mBluetoothAdapter);
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("/myRecording.mp3");
sharingIntent.setComponent(new ComponentName("com.android.bluetooth", "com.android.bluetooth.opp.BluetoothOppLauncherActivity"));
file = new File(outputFile);
sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
startActivity(sharingIntent);
Log.d("/myRecording.mp3", "SharingIntent");
}
else {
text1.setText("Bluetooth not activated");
}
}
catch (IllegalStateException e) {
// it is called before start()
e.printStackTrace();
}
catch (RuntimeException e) {
// no valid audio/video data has been received
e.printStackTrace();
}
}
public void record(View view) {
try {
myRecorder.prepare();
myRecorder.start();
}
catch (IllegalStateException e) {
// start:it is called before prepare()
// prepare: it is called after start() or before setOutputFormat()
e.printStackTrace();
}
catch (IOException e) {
// prepare() fails
e.printStackTrace();
}
text1.setText("Recording Point: Recording");
Toast.makeText(getApplicationContext(), "Start recording...", Toast.LENGTH_SHORT).show();
}
public void stopPlay(View view) {
try {
if (myPlayer != null) {
myPlayer.stop();
myPlayer.release();
myPlayer = null;
text1.setText("Recording Point: Stop playing");
Toast.makeText(getApplicationContext(), "Stop playing the recording...", Toast.LENGTH_SHORT).show();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
public void play(View view) {
try {
myPlayer = new MediaPlayer();
myPlayer.setDataSource(outputFile);
myPlayer.prepare();
myPlayer.start();
text1.setText("Recording Point: Playing");
Toast.makeText(getApplicationContext(), "Start play the recording...", Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
e.printStackTrace();
}
}
#Override
public synchronized void onPause() {
super.onPause();
if (D)
Log.e(TAG, "- ON PAUSE -");
}
#Override
public void onStop() {
super.onStop();
if (D)
Log.e(TAG, "-- ON STOP --");
}
#Override
public void onDestroy() {
super.onDestroy();
// Stop the Bluetooth chat services
if (mChatService != null)
mChatService.stop();
if (D)
Log.e(TAG, "--- ON DESTROY ---");
}
private void ensureDiscoverable() {
if (D)
Log.d(TAG, "ensure discoverable");
if (mBluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
}
}
private final BroadcastReceiver ActionFoundReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("BroadcastReceiver", "onReceive");
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
items += device.getName() + ",";
address += device.getAddress() + ",";
}
}
};
/**
* Sends a message.
*
* #param message
* A string of text to send.
*/
private void sendMessage(String message) {
// Check that we're actually connected before trying anything
if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
return;
}
// Check that there's actually something to send
if (message.length() > 0) {
// Get the message bytes and tell the BluetoothChatService to write
byte[] send = message.getBytes();
mChatService.write(send);
// Reset out string buffer to zero and clear the edit text field
mOutStringBuffer.setLength(0);
mOutEditText.setText(mOutStringBuffer);
}
}
// The action listener for the EditText widget, to listen for the return key
private TextView.OnEditorActionListener mWriteListener = new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
// If the action is a key-up event on the return key, send the message
if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP) {
String message = view.getText().toString();
sendMessage(message);
//SetRouteSco(BluetoothChat.this, isRoute);
}
if (D)
Log.i(TAG, "END onEditorAction");
return true;
}
};
private final void setStatus(int resId) {
final ActionBar actionBar = getActionBar();
actionBar.setSubtitle(resId);
}
private final void setStatus(CharSequence subTitle) {
final ActionBar actionBar = getActionBar();
actionBar.setSubtitle(subTitle);
}
// The Handler that gets information back from the BluetoothChatService
#SuppressLint("HandlerLeak")
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_STATE_CHANGE:
if (D)
Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
switch (msg.arg1) {
case BluetoothChatService.STATE_CONNECTED:
setStatus(getString(R.string.title_connected_to, mConnectedDeviceName));
mConversationArrayAdapter.clear();
break;
case BluetoothChatService.STATE_CONNECTING:
setStatus(R.string.title_connecting);
break;
case BluetoothChatService.STATE_LISTEN:
case BluetoothChatService.STATE_NONE:
try {
setStatus(R.string.title_not_connected);
}
catch (Exception e) {
e.printStackTrace();
}
break;
}
break;
case MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
// construct a string from the buffer
String writeMessage = new String(writeBuf);
mConversationArrayAdapter.add("Me: " + writeMessage);
break;
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
mConversationArrayAdapter.add(mConnectedDeviceName + ": " + readMessage);
/*String readMessage = new String(readBuf, 0, msg.arg1);
try {
re(readMessage);
}
catch (IllegalArgumentException e) {
e.printStackTrace();
}
catch (SecurityException e) {
e.printStackTrace();
}
catch (IllegalStateException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Playing audio", Toast.LENGTH_LONG).show();
mConversationArrayAdapter.add(mConnectedDeviceName + ": " + readMessage);*/
break;
case MESSAGE_DEVICE_NAME:
// save the connected device's name
mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
Toast.makeText(getApplicationContext(), "Connected to " + mConnectedDeviceName, Toast.LENGTH_SHORT).show();
break;
case MESSAGE_TOAST:
Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST), Toast.LENGTH_SHORT).show();
break;
}
}
};
/* public void play(String outputFile) throws IllegalArgumentException, SecurityException, IllegalStateException, IOException {
MediaPlayer m = new MediaPlayer();
m.setDataSource(outputFile);
m.prepare();
m.start();
Toast.makeText(getApplicationContext(), "Playing audio", Toast.LENGTH_LONG).show();
}
*/
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (D)
Log.d(TAG, "onActivityResult " + resultCode);
switch (requestCode) {
case REQUEST_CONNECT_DEVICE_SECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
connectDevice(data, true);
}
break;
case REQUEST_CONNECT_DEVICE_INSECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
connectDevice(data, false);
}
break;
case REQUEST_ENABLE_BT:
// When the request to enable Bluetooth returns
if (resultCode == Activity.RESULT_OK) {
// Bluetooth is now enabled, so set up a chat session
setupChat();
}
else {
// User did not enable Bluetooth or an error occurred
Log.d(TAG, "BT not enabled");
Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
finish();
}
}
}
private void connectDevice(Intent data, boolean secure) {
// Get the device MAC address
String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
// Get the BluetoothDevice object
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
// Attempt to connect to the device
mChatService.connect(device, secure);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.option_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent serverIntent = null;
switch (item.getItemId()) {
case R.id.secure_connect_scan:
// Launch the DeviceListActivity to see devices and do scan
serverIntent = new Intent(this, DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_SECURE);
return true;
case R.id.insecure_connect_scan:
// Launch the DeviceListActivity to see devices and do scan
serverIntent = new Intent(this, DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_INSECURE);
return true;
case R.id.discoverable:
// Ensure this device is discoverable by others
ensureDiscoverable();
return true;
}
return false;
}
/* *//**
* Sends a voice message.
*/
/*
public static void SetRouteSco(Context context, boolean isRoute) {
Log.d("SetRouteSco", "isRoute : " + isRoute);
mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
mAudioManager.setBluetoothScoOn(isRoute);
if (isRoute)
mAudioManager.startBluetoothSco();
else
mAudioManager.stopBluetoothSco();
}*/
}
XML:
<ListView
android:id="#+id/in"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:stackFromBottom="true"
android:transcriptMode="alwaysScroll" />
<TextView
android:id="#+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Recording Point: -"
android:textAppearance="?android:attr/textAppearanceMedium" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<ToggleButton
android:id="#+id/button_speak"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="false"
android:textOff="send"
android:textOn="speak" />
<EditText
android:id="#+id/edit_text_out"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_weight="1" />
<Button
android:id="#+id/button_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send Msg" />
<ToggleButton
android:id="#+id/button_play"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="false"
android:textOff="stop"
android:textOn="play" />
</LinearLayout>
Manifest Class:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.BluetoothChat"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="11" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.BROADCAST_STICKY" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<application
android:icon="#drawable/app_icon"
android:label="#string/app_name" >
<activity
android:name=".MAinActivity"
android:configChanges="orientation|keyboardHidden"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".BluetoothChat"
android:configChanges="orientation|keyboardHidden"
android:label="#string/select_device"
android:theme="#android:style/Theme.Holo.Dialog" />
<activity
android:name=".DeviceListActivity"
android:configChanges="orientation|keyboardHidden"
android:label="#string/app_name" />
</application>
</manifest>
NOTE: Firstly I paired my device with another and voice is recorded successfully but while sending that voice to another device, "You are not connected to the device" toast is displayed
IMPORTANT : By this demo my audio file is send, but it only save directly to the sd card,
I want that audio file first should send to that specific application and also save to the sd card
Anyone can help me??
How can I do this?
Thanks In Advanced
You need to establish paring between two device for transfer voice message
1) Record voice message using your application
2) send it using share via Bluetooth.
I am developing an application in which first we have to search and connect available paired Bluetooth devices. I have done till connection. But after that I have put one screen which asks to choose between Text and file transfer. When I select text then one more screen will open in which there are edittext and button. Whatever user types in edittext and clicks on button that should be transferd to connected BT device like BT chat application. I have gone through BT chat app but it is complex to understand. I want a seperate function which does transferring task. Below is my connection code.
Main.java
public class Main extends Activity implements Runnable
{
protected static final String TAG = "TAG";
private static final int REQUEST_CONNECT_DEVICE = 1;
private static final int REQUEST_ENABLE_BT = 2;
Button mScan;
BluetoothAdapter mBluetoothAdapter;
private UUID applicationUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private ProgressDialog mBluetoothConnectProgressDialog;
private BluetoothSocket mBluetoothSocket;
BluetoothDevice mBluetoothDevice;
#Override
public void onCreate(Bundle mSavedInstanceState)
{
super.onCreate(mSavedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
mScan = (Button) findViewById(R.id.Scan);
mScan.setOnClickListener(new View.OnClickListener()
{
public void onClick(View mView)
{
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null)
{
Toast.makeText(Main.this, "Message1", 2000).show();
}
else
{
if (!mBluetoothAdapter.isEnabled())
{
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
else
{
ListPairedDevices();
Intent connectIntent = new Intent(Main.this, DeviceListActivity.class);
startActivityForResult(connectIntent, REQUEST_CONNECT_DEVICE);
}
}
}
});
}
public void onActivityResult(int mRequestCode, int mResultCode, Intent mDataIntent)
{
super.onActivityResult(mRequestCode, mResultCode, mDataIntent);
switch (mRequestCode)
{
case REQUEST_CONNECT_DEVICE:
if (mResultCode == Activity.RESULT_OK)
{
Bundle mExtra = mDataIntent.getExtras();
String mDeviceAddress = mExtra.getString("DeviceAddress");
Log.v(TAG, "Coming incoming address " + mDeviceAddress);
mBluetoothDevice = mBluetoothAdapter.getRemoteDevice(mDeviceAddress);
mBluetoothConnectProgressDialog = ProgressDialog.show(this, "Connecting...", mBluetoothDevice.getName() + " : " + mBluetoothDevice.getAddress(), true, false);
Thread mBlutoothConnectThread = new Thread(this);
mBlutoothConnectThread.start();
//pairToDevice(mBluetoothDevice); This method is replaced by progress dialog with thread
}
break;
case REQUEST_ENABLE_BT:
if (mResultCode == Activity.RESULT_OK)
{
ListPairedDevices();
Intent connectIntent = new Intent(Main.this, DeviceListActivity.class);
startActivityForResult(connectIntent, REQUEST_CONNECT_DEVICE);
}
else
{
Toast.makeText(Main.this, "Message", 2000).show();
}
break;
}
}
private void ListPairedDevices()
{
Set<BluetoothDevice> mPairedDevices = mBluetoothAdapter.getBondedDevices();
if (mPairedDevices.size() > 0)
{
for (BluetoothDevice mDevice : mPairedDevices)
{
Log.v(TAG, "PairedDevices: " + mDevice.getName() + " " + mDevice.getAddress());
}
}
}
public void run()
{
try
{
mBluetoothSocket = mBluetoothDevice.createRfcommSocketToServiceRecord(applicationUUID);
mBluetoothAdapter.cancelDiscovery();
mBluetoothSocket.connect();
mHandler.sendEmptyMessage(0);
}
catch (IOException eConnectException)
{
Log.d(TAG, "CouldNotConnectToSocket", eConnectException);
closeSocket(mBluetoothSocket);
return;
}
}
private void closeSocket(BluetoothSocket nOpenSocket)
{
try
{
nOpenSocket.close();
Log.d(TAG, "SocketClosed");
}
catch (IOException ex)
{
Log.d(TAG, "CouldNotCloseSocket");
}
}
private Handler mHandler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
mBluetoothConnectProgressDialog.dismiss();
Toast.makeText(Main.this, "Device Connected", 5000).show();
Intent in = new Intent(getBaseContext(), Option.class);
startActivity(in);
}
};
}
DeviceListActivity.java
public class DeviceListActivity extends Activity
{
protected static final String TAG = "TAG";
private BluetoothAdapter mBluetoothAdapter;
private ArrayAdapter<String> mPairedDevicesArrayAdapter;
#Override
protected void onCreate(Bundle mSavedInstanceState)
{
super.onCreate(mSavedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.device_list);
setResult(Activity.RESULT_CANCELED);
mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
ListView mPairedListView = (ListView) findViewById(R.id.paired_devices);
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);
}
}
#Override
protected void onDestroy()
{
super.onDestroy();
if (mBluetoothAdapter != null)
{
mBluetoothAdapter.cancelDiscovery();
}
}
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();
}
};
}
option.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/file" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/txt" />
</LinearLayout>
message.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/hint">
<requestFocus />
</EditText>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/send" />
</LinearLayout>
Call to following method:
private void sendDataToPairedDevice(String message ,BluetoothDevice device){
byte[] toSend = message.getBytes();
try {
BluetoothSocket socket = device.createInsecureRfcommSocketToServiceRecord(applicationUUID);
OutputStream mmOutStream = socket.getOutputStream();
mmOutStream.write(toSend);
// Your Data is sent to BT connected paired device ENJOY.
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
}
}
Now Put following in Your Oncreate of the Activity with EditText.
EditText editText1 = (EditText) findViewById(R.id.editText1);
And Call above method like
sendDataToPairedDevice(editText1.getText() ,mBluetoothDevice);
in The Onclick of your desired button.
thats it.
just upvote if you use it, thanks, enjoy buddy.
public void onClick(View v) {
// TODO Auto-generated method stub
mBluetoothAdapter1 = BluetoothAdapter.getDefaultAdapter();
byte[] toSend=message1.getBytes();
try
{
final UUID applicationUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
BluetoothDevice device=mBluetoothAdapter1.getRemoteDevice(MacAddress);
BluetoothSocket socket=device.createInsecureRfcommSocketToServiceRecord(applicationUUID);
OutputStream mmout=socket.getOutputStream();
mmout.write(toSend);
mmout.flush();
mmout.close();
socket.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Finally got the Answer...
BluetoothAdapter mBluetoothAdapter = null;
BluetoothDevice m1BluetoothDevice;
public static BluetoothSocket socket;//Get this value from Main Activity
Button btn;
EditText et;
public static String MacAddressesss;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.message);
btn=(Button)findViewById(R.id.btn);
et=(EditText)findViewById(R.id.et);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try
{
String msg=et.getText().toString();
byte tosend= msg.getBytes();
OutputStream out= socket.getOutputStream();
out.write(tosend);
}
catch(IOException e)
{
e.printStackTrace();
}
}
});
}
}