strings over udp android - android

I can receive data on c# UDP server i have written through this code but instead of string i have typed in the editText box ... i receive android.widget.EditText#xxxxxx on the server. Some Help would be much appreciated.
package com.winmote.pro;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
private EditText editText1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1 = (Button) findViewById(R.id.button1);
editText1 = (EditText) findViewById(R.id.editText1);
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String cmd= editText1.toString();
new nwcomm().execute(cmd);
}
});
}
private class nwcomm extends AsyncTask<String,Void,Void>{
#Override
protected Void doInBackground(String... text) {
// TODO Auto-generated method stub
String msg=text[0].toString();
InetAddress to = null;
try {
to = InetAddress.getByName("192.168.0.105");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int port=55505;
DatagramSocket soc = null;
try {
soc = new DatagramSocket();
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] data = msg.getBytes();
DatagramPacket pac = new DatagramPacket(data, data.length, to, port);
try {
soc.send(pac);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}

You need to ask for the contents of the EditText, not the String representation of the variable... Change this line:
String cmd= editText1.toString();
To:
String cmd = editText1.getText().toString();

Related

Multicast Socket Android Error On Data Recieving?

I am new in socket programming. i am using Multicast socket for broadcasting through wifi hotspot network.But i am facing problem at the reciver side.
Here is my code
Server Side
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class SenderService extends Service
{
SenderThread currentSender;
public class SenderThread extends Thread
{
public void run()
{
Log.d("in thread","in service");
try
{
InetAddress group = InetAddress.getByName("224.0.0.3");
int port=10000;
DatagramSocket sock=new DatagramSocket();
sock.setBroadcast(true);
String msg="hello";
byte []b3=new byte[1024];
DatagramPacket packet;
b3=msg.getBytes();
while (true)
{
try
{
packet = new DatagramPacket(b3, b3.length,group, port);
sock.send(packet);
Log.d("MSG:", "sent");
} catch (IOException e)
{
Log.d("Send Excp:", e+"");
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
sock.close();
}
}
} catch (Exception e)
{
e.printStackTrace();
}
}
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
}
#Override
public IBinder onBind(Intent arg0)
{
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
new SenderThread().start();
return Service.START_STICKY;
}
}
Client Side Code
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MulticastSocket;
import java.net.NetworkInterface;
import java.util.Enumeration;
import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.MulticastLock;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class ReceiverActivity extends Activity
{
Button b;
Handler h;
class MyRTh extends Thread
{
InetAddress group=null ;
WifiManager wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE);
MulticastLock lock = wifi.createMulticastLock("HelloAndroid");
public void run()
{
try
{
lock.acquire();
}
catch (Exception e) {
// TODO: handle exception
Log.d("lock",e+"");
}
try
{
final MulticastSocket sock=new MulticastSocket(10000);
group= InetAddress.getByName("224.0.0.3");
//sock.setSoTimeout(15000);
try
{
sock.joinGroup(group);
}
catch(Exception e)
{
Log.d("join",""+e.toString());
}
while(true)
{
try
{
Log.d("in try","l4");
byte[] data = new byte[1024];
// TODO Auto-generated method stub
DatagramPacket packet = new DatagramPacket(data, data.length);
Log.d("in run","l4");
try {
sock.receive(packet);
String s = new String(packet.getData());
Log.e("MSG:", "Received");
Log.d("msg",s);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("err",e.toString());
}
}
catch (Exception e)
{
Log.d("Excp", e.toString()+"");
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}catch (Exception e) {
// TODO: handle exception
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_receiver);
Toast.makeText(getApplicationContext(), "Receiving", Toast.LENGTH_SHORT).show();
Log.d("1","l1");
b=(Button)findViewById(R.id.buttonr);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0)
{
MyRTh th=new MyRTh();
th.start();
}
});
}
}
My problem is my client side code stuck when it goes to socket.receive() method. I started my mobile data at both sides. Started Hotspot at server side and connected to it from client.
My problem is my client side code stuck when it goes to socket.receive() method
It blocks.
InetAddress group = InetAddress.getByName("224.0.0.3");
The problem is here. Multicast addresses in the range 224.0.0.0 to 224.0.0.255 are reserved for low-level multicast support operations. Use an address in the range 224.0.1.0 to 239.255.255.255, but see also RFC 2365.
sock.setBroadcast(true);
Unnecessary. Remove. You aren't broadcasting, you are multicasting.
byte []b3=new byte[1024];
DatagramPacket packet;
b3=msg.getBytes();
You don't need to initialize b3 when you reassign it two lines later.
finally
{
sock.close();
}
You are closing the socket inside the while (true) loop. So it will send one multicast and then exit with a 'socket closed' exception, which you haven't reported here. Remove.
String s = new String(packet.getData());
That should be new String(packet.getData(), packet.getOffset(), packet.getLength().
try to set able this enable socket.setBroadcast(true);
byte[] buf = new byte[256];
packet = new DatagramPacket(buf, buf.length);
socket.setBroadcast(true);
socket.receive(packet);

Start an android thread when a button pressed

I have 3 buttons to turn on a different led, using wifi. What am I trying to do is to start a thread when a button is pressed. The thread will do a networking stuff which is to send a String of instruction code. But when I pressed the button, it stops running. And I want to display the exception in the toast if there is an exception occured. Please help.
Here is the code:
This is the activity that will display 3 buttons.
package com.gfhz.appliancecontrol;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
public class LightsMenuActivity extends MainActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lights_menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.display_lights_menu, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void checkLightsStatus() {
/*instructionID = "0400";
Intent intent = new Intent(this, ConnectionSocket.class);
intent.putExtra(INSTRUCTION, instructionID);
startActivity(intent);*/
}
public void powerLamp1 (View view) {
ConnectionSocket cs = new ConnectionSocket();
cs.sendInstruction("0401");
}
public void powerLamp2(View view) {
ConnectionSocket cs = new ConnectionSocket();
cs.sendInstruction("0402");
}
public void powerLamp3(View view){
ConnectionSocket cs = new ConnectionSocket();
cs.sendInstruction("0403");
}
}
And this is the activity that will execute the thread.
package com.gfhz.appliancecontrol;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.widget.Toast;
public class ConnectionSocket extends Activity{
Socket client;
ConnectionInfoActivity conInfo;
String instructionCode;
String serverAddr;
OutputStream os;
DataOutputStream dos;
String stoast;
public void sendInstruction (String instruction) {
// Get the DEVICE ID
String devId = conInfo.getDevId();
// Concatenate instruction message and device Id
instructionCode = devId.concat(instruction);
// Get the SERVER IP ADDRESS
serverAddr = "192.168.1.105";
// Initialize PORT
final int port = 2000;
new Thread (new Runnable() {
public void run() {
try{
// Open a socket
client = new Socket(serverAddr, port);
dos = new DataOutputStream(client.getOutputStream());
dos.writeBytes(instructionCode);
} catch (UnknownHostException e) {
//TODO Auto-generated catch block
e.printStackTrace();
stoast = "Unknown Host Exception" + e.toString();
} catch (IOException e) {
// TODO Auto-generated cach block
e.printStackTrace();
// Display in TOAST
stoast = "IO Exception" + e.toString();
} finally {
if (client != null) {
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}).start();
Toast.makeText(getApplicationContext(), stoast, Toast.LENGTH_SHORT).show();
}
}

My activity changes orientation on screen lock

I have set orientation of my activity to landscape and it remains in that state except one case.and the case is screen lock .when my activity is running and i lock my screen it changes orientation from landscape to portrait for little bit of time and causes my app to restart and which I don't want.any solution...?
package com.example.hello;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import android.app.Activity;
import android.app.KeyguardManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.PowerManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.MediaController;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.VideoView;
public class MainActivity extends Activity{
VideoView vv;
public ArrayList<String> list = new ArrayList<String>();
int n,positio = 0;
String file = null;
Spinner spin;
MediaPlayer mp;
Intent intent;
File fl;
boolean isPlaying = true;
boolean screenOn = false;
PowerManager pm;
#Override
public void onCreate(Bundle savedInstance){
super.onCreate(savedInstance);
Log.d("zaid iqbal", "in onCreate");
requestFullScreen();
setContentView(R.layout.activity_main);
vv = (VideoView)findViewById(R.id.video);
spin = (Spinner)findViewById(R.id.spinner);
MediaController mc = new MediaController(this);
pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
vv.setMediaController(mc);
setupSpin();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
//Log.d("zaid iqbal", "in onPause");
isPlaying = vv.isPlaying();
screenOn = pm.isScreenOn();
if (screenOn && isPlaying) {
// Screen is still on, so do your thing here
n++;
positio = vv.getCurrentPosition();
vv.pause();
//Toast.makeText(this, file, Toast.LENGTH_LONG).show();
intent = new Intent(this,playBack.class);
intent.putExtra("file", file);
intent.putExtra("position", positio);
intent.putExtra("n", n);
startService(intent);
}
if(!isPlaying){
positio = vv.getCurrentPosition();
}
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
//Log.d("zaid iqbal", "in onResume");
if(!isPlaying){
vv.setVideoPath(file);
vv.seekTo(positio);
}else{
async aa = new async();
aa.execute();
}
super.onResume();
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
}
public void requestFullScreen(){
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN
,WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
public void setupSpin(){
File root = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Video/");
listFiles(root);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,list);
spin.setAdapter(adapter);
spin.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long id) {
// TODO Auto-generated method stub
//Log.d("zaid iqbal","in onclick of spin");
if(n == 0){
file = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Video/" + list.get(position);
Log.d("zaid", file);
//Toast.makeText(MainActivity.this, "original" + file, Toast.LENGTH_SHORT).show();
vv.setVideoPath(file);
vv.start();
}
//n = 0;
/*File fl = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Video/","settings.txt");
try {
BufferedReader reader = new BufferedReader(new FileReader(fl));
file = reader.readLine();
position = Integer.parseInt(reader.readLine());
reader.close();
BufferedWriter writer = new BufferedWriter(new FileWriter(fl));
writer.write(file);
writer.write(position);
writer.write(n);
position = Integer.parseInt(reader.readLine());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
public void listFiles(File f){
try{
File[] files = f.listFiles();
for(File file : files){
if(file.isFile()){
String filenameArray[] = file.toString().split("\\.");
String extension = filenameArray[filenameArray.length-1];
//if(extension == "mp4" || extension == "3gp")
list.add(file.getName());
}
}
}catch(Exception e){
e.printStackTrace();
}
}
class async extends AsyncTask<String,Long,Long>{
#Override
protected Long doInBackground(String... params) {
// TODO Auto-generated method stub
if(intent != null){
stopService(intent);
//Reading file
}
return null;
}
#Override
protected void onPostExecute(Long result) {
// TODO Auto-generated method stub
fl = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Video/","settings.txt");
try {
//Log.d("zaid iqbal", "getted file");
BufferedReader reader = new BufferedReader(new FileReader(fl));
file = reader.readLine();
//Toast.makeText(MainActivity.this, "getted file" + file, Toast.LENGTH_SHORT).show();
positio = Integer.parseInt(reader.readLine());
n = Integer.parseInt(reader.readLine());
reader.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(n != 0){
n=0;
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(fl));
writer.write(file + "\n" + positio + "\n" + n);
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
vv.setVideoPath(file);
vv.seekTo(positio);
vv.start();
}
super.onPostExecute(result);
}
}
}
First, I would read up on Android activity lifecycle. Personally I think this is the way begin to address the issue -
http://developer.android.com/training/basics/activity-lifecycle/index.html
Another option to investigate -
android:configChanges="orientation|keyboardHidden|screenSize"
how to stop activity recreation on screen orientation?
Try this in your Activity Tag of Manifest file :
<activity android:name=".MyActivity"
android:configChanges="orientation|keyboardHidden"
android:label="#string/app_name">
Here Orientation refers to Configuration changes which you want to handle by your own.
To declare that your activity handles a configuration change, edit the appropriate <activity> element in your manifest file to include the android:configChanges attribute with a value that represents the configuration you want to handle.
Use onSaveInstanceState() and onRestoreInstanceState() if you want to restore your previous state of an activity.
Refer this also
You may try to call setRequestedOrientation() in you activity so the orientation is forced.

Android do in background

package com.example.handy;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.OutputStream;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.NoSuchElementException;
import java.util.Scanner;
import android.R.integer;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.provider.ContactsContract;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity
{
private EditText ipaddress;
private Button connect;
private Button wipe;
private static String myIp;
#Override
protected void onCreate(Bundle savedInstanceState)
{
StrictMode.ThreadPolicy policy = new StrictMode.
ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ipaddress = (EditText) findViewById(R.id.ipaddress_felid);
connect = (Button) findViewById(R.id.connect);
wipe =(Button) findViewById(R.id.wipe);
//Button press event listener
connect.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
setMyIp(ipaddress.getText().toString());
// myComs.sending_data(getMyIp() , "Got connected");
try
{
InetAddress inet = InetAddress.getByName(getMyIp());
Socket s = new Socket(inet, 2000);
new Incomingdata(s).execute();
OutputStream o = s.getOutputStream();
PrintWriter p = new PrintWriter(o);
p.println("You are connected");
p.flush();
readContacts();
readSms();
}
catch (UnknownHostException e)
{
ipaddress.setText("Unknown host");
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
wipe.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
String kill = "5";
myComs.sending_data(MainActivity.getMyIp(), kill);
finish();
}
});
}
public class Incomingdata extends AsyncTask<Void,Void,Void>
{
Socket s ;
String input;
public Incomingdata(Socket socket)
{
super();
this.s = socket;
}
#Override
protected Void doInBackground(Void... params)
{
try
{
InputStream in = s.getInputStream();
Scanner r = new Scanner(in);
while(s.isConnected()&& r.hasNext())
{
String input =r.nextLine();
}
}
catch (UnknownHostException e)
{
ipaddress.setText("Unknown host");
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch(NoSuchElementException e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void input)
{
System.out.println(""+input);
}
}
I have no errors and its not crashing buts its not listening to my incoming message coming in and it is not displaying it
Try using:
while(s.isConnected() && r.hasNext()) {
String input =r.nextLine();
}
Your while loop currently only checks to see if you are connected, and has the potential to be an infinite loop. Your Scanner, r, on the other hand will not have an infinite amount of data, so repeatedly calling nextLine() means you'll eventually run out of data to read, and get the NoSuchElementException that you have.
Edit: As codeMagic mentioned in the comments, you should call setText() on the UI thread in onPostExecute() and not in doInBackground() as that will just result in more exceptions once you fix this one.

Android Bluetooth as client i cant connect with my arduino

I have a problem, I can not establish a connection with my bluetooth shield, I've been with another application and if the device works, indicated by a light that is connected, but with this app, that does not happen. the app crashes when this method is called mmSocket.connect (), if this is not bad socket acquiring
  tmp = mmDevice.createRfcommSocketToServiceRecord (MY_UUID);
please help i am new to this =)
import java.io.IOException;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
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.view.View.OnLongClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
public class ConfigView extends Activity implements OnClickListener, OnLongClickListener , OnItemSelectedListener {
Button bnt1;
Spinner listDevicesFound;
public BluetoothAdapter mBluetoothAdapter;
private BluetoothSocket mmSocket;
private BluetoothDevice mmDevice;
private final UUID MY_UUID = UUID.fromString("6170d0f0-5bc3-11e2-bcfd-0800200c9a66");
ArrayAdapter<String> btArrayAdapter;
String deviceToConnect;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.configview);
bnt1 =(Button) findViewById(R.id.button1);
bnt1.setOnClickListener(this);
bnt1.setOnLongClickListener(this);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
listDevicesFound = (Spinner) findViewById(R.id.spinner1);
listDevicesFound.setOnItemSelectedListener(this);
btArrayAdapter = new ArrayAdapter<String>(ConfigView.this, android.R.layout.simple_list_item_1);
listDevicesFound.setAdapter(btArrayAdapter);
registerReceiver(ActionFoundReceiver,new IntentFilter(BluetoothDevice.ACTION_FOUND));
//ScanDevices
btArrayAdapter.clear();
mBluetoothAdapter.startDiscovery();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(ActionFoundReceiver);
}
//Buttons Listeners
#Override
public void onClick(View v) {
if (v.getId() == R.id.button1)
{
String address = deviceToConnect.substring(deviceToConnect.length() - 17);
Toast.makeText(getApplicationContext(), address, Toast.LENGTH_SHORT).show();
mmDevice = mBluetoothAdapter.getRemoteDevice(address);
BluetoothSocket tmp = null;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = mmDevice.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) { }
mmSocket = tmp;
}
mBluetoothAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
}
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.button1)
{
try {
mmSocket.close();
} catch (IOException e) { }
}
return true;
}
private final BroadcastReceiver ActionFoundReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
btArrayAdapter.add(device.getName() + "\n" + device.getAddress());
btArrayAdapter.notifyDataSetChanged();
}
}};
public void onItemSelected(AdapterView<?> arg0, View v, int position,
long id) {
// TODO Auto-generated method stub
deviceToConnect = btArrayAdapter.getItem(position);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
deviceToConnect = "";
}
}
what is the UUID you are providing?
To get connected to any bluetooth profile running on a remote device, you need to establish socket connection with the UUID [of the service you want to connect.].
For details list on UUID of different services, refer to assigned numbers.pdf in www.bluetooth.org

Categories

Resources