this is my server code

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.bluetooth.*;
import javax.microedition.io.*;

public class ServerSide {

        //private static LocalDevice localDevice;
        static LocalDevice localDevice;
        DiscoveryAgent agent;

        private void startServer() throws IOException{

                   UUID uuid = new UUID("112f8dbf1e46442292b6796539467bc9", 
false);
                   String connectionString = "btspp://localhost:" + uuid
+";name=SampleSPPServer";
                 //open server url
                 StreamConnectionNotifier streamConnNotifier =
(StreamConnectionNotifier)Connector.open( connectionString );
                 System.out.println("\nServer Started. Waiting for clients to
connect...");
                 StreamConnection connection=streamConnNotifier.acceptAndOpen();
                 RemoteDevice dev = RemoteDevice.getRemoteDevice(connection);
                 System.out.println("Remote device address:
"+dev.getBluetoothAddress());
                 System.out.println("Remote device name:
"+dev.getFriendlyName(true));

        }
        public static void main(String[] args) {
                //display local device address and name
                try{
                localDevice = LocalDevice.getLocalDevice();
                System.out.println("Address: 
"+localDevice.getBluetoothAddress());
                System.out.println("Name: "+localDevice.getFriendlyName());
                }catch(Exception e){
                System.err.println(e.toString());
                System.err.println(e.getStackTrace());
                e.printStackTrace();}
                try{
                ServerSide sampleSPPServer=new ServerSide();
                sampleSPPServer.startServer();
                }catch(Exception e){
                System.err.println(e.toString());
                System.err.println(e.getStackTrace());
                e.printStackTrace();}

}
}


**************************************************************

and this is my client(android) code
package client.side;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
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.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ClientSideActivity extends Activity {
    int REQUEST_ENABLE_BT = 0;
    private BluetoothAdapter mBluetoothAdapter;
    private ArrayAdapter<String> mArrayAdapter;

        /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button btn1 = (Button)findViewById(R.id.button1);
        Button btn2 = (Button)findViewById(R.id.button2);
        final ListView lv1 = (ListView)findViewById(R.id.listView1);
        final TextView out = (TextView)findViewById(R.id.textView1);
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        mArrayAdapter = new
ArrayAdapter<String>(this,android.R.layout.simple_list_item_1);



         if (!mBluetoothAdapter.isEnabled()) {
                    Intent enableBtIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enableBtIntent,
REQUEST_ENABLE_BT);
                }
         out.setText(null);





     btn1.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                // TODO Auto-generated method stub
                        out.setText("Paired Devices");
                         Set<BluetoothDevice> pairedDevices =
mBluetoothAdapter.getBondedDevices();

                 if (pairedDevices.size() > 0){
                                        for(BluetoothDevice device : 
pairedDevices){
                                                
mArrayAdapter.add(device.getName() + "\n" +
device.getAddress());
                                        }
                                }
                        lv1.setAdapter(mArrayAdapter);

                }
        });



     btn2.setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {
                out.setText("Discovered Devices");
                 mBluetoothAdapter.startDiscovery();
                Toast msg = Toast.makeText(ClientSideActivity.this, "Discovering
Devices please wait.", Toast.LENGTH_LONG);
                msg.show();

                final BroadcastReceiver mReceiver = new BroadcastReceiver() {
                    public void onReceive(Context context, Intent intent) {
                        String action = intent.getAction();
                        // When discovery finds a device
                        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                            // Get the BluetoothDevice object from the Intent
                            BluetoothDevice device =
intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                            // Add the name and address to an array adapter to 
show
in a ListView
                            mArrayAdapter.add(device.getAddress());
                        }   }
                };
                // Register the BroadcastReceiver
                IntentFilter filter = new
IntentFilter(BluetoothDevice.ACTION_FOUND);
                registerReceiver(mReceiver, filter); // Don't forget to 
unregister
during onDestroy
                }

        });


    lv1.setOnItemClickListener(new OnItemClickListener()
{
       public void onItemClick(AdapterView<?> arg0, View arg1, int
position,long id)
 
{
 
out.setText(arg0.getItemAtPosition(position).toString());
           BluetoothDevice remoteDev = (BluetoothDevice)
arg0.getItemAtPosition(position);
           ConnectThread conDev = new ConnectThread(remoteDev);
           conDev.start();


       }
       });

    }


    public class ConnectThread extends Thread {
        private final UUID MY_UUID =
UUID.fromString("112f8dbf1e46442292b6796539467bc9");
                private final BluetoothSocket mmSocket;
        private final BluetoothDevice mmDevice;


        public ConnectThread(BluetoothDevice device) {
            // Use a temporary object that is later assigned to
mmSocket,
            // because mmSocket is final
            BluetoothSocket tmp = null;
            mmDevice = device;

            try {
                // MY_UUID is the app's UUID string, also used by the
server code
                tmp =
device.createRfcommSocketToServiceRecord(MY_UUID);
            } catch (IOException e) { }
            mmSocket = tmp;
        }

        public void run() {
            // Cancel discovery because it will slow down the
connection
            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;
            }
                 // Do work to manage the connection (in a separate
thread)

        }
             /** Will cancel an in-progress connection, and close the
socket  */

    }



}

-- 
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en

Reply via email to