안 드 로 이 드 와 PC 에서 블 루 투 스 통신 demo

돌리다http://royal2xiaose.iteye.com/blog/1420138
 
전제:
      1. 컴퓨터 테스트 사용
      2. 테스트 전에 블 루 투 스 는 핸드폰 과 PC 기기 의 블 루 투 스 어댑터 를 잘 맞 추 십시오. (따라서 블 루 투 스 어댑터 가 PC USB 포트 에 삽입 되 어야 합 니 다)
 
demo 테스트 효과:
      휴대 전화 가 좌우 로 흔 들 릴 때 데 이 터 를 PC 에 전달 하고 인쇄 한다.(android 중력 감지)
 
PC 서버 코드:
import java.io.IOException;
import java.io.InputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;

public class BTServer implements Runnable {

	//              
	private StreamConnectionNotifier myPCConnNotifier = null;
	//    
	private StreamConnection streamConn = null;
	//        
	private byte[] acceptedByteArray = new byte[12];
	//   (  ) 
	private InputStream inputStream = null;

	/**
	 *    
	 *  
	 * @param args
	 */
	public static void main(String[] args) {
		new BTServer();
	}

	/**
	 *     
	 */
	public BTServer() {
		try {
			//        ,   UUID         UUID   。
			myPCConnNotifier = (StreamConnectionNotifier) Connector
					.open("btspp://localhost:0000110100001000800000805F9B34FB");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//             
		new Thread(this).start();
	}

	@Override
	public void run() {
		try {
			String inSTR = null;
			//                
			while (true) {
				//      
				streamConn = myPCConnNotifier.acceptAndOpen();
				//      
				inputStream = streamConn.openInputStream();
				//      
				while (inputStream.read(acceptedByteArray) != -1) {
					inSTR = new String(acceptedByteArray);
					System.out.println(inSTR);
					if (inSTR.contains("EXIT")) {
						//               。
						inputStream.close();
						if (streamConn != null) {
							streamConn.close();
						} 
						break;
					}  
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

 서버 에서 bluecove. jar 와 comons - io. jar 패 키 지 를 가 져 오 십시오.
 
android 핸드폰 클 라 이언 트 코드:
 
BlueTooth.java
package com.royal.bluetooth;

import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.DialogInterface;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

/**
 * BlueTooth & Sensor
 * 
 * @author royal
 * 
 */

public class BlueTooth extends Activity {

	private static final int REQUEST_DISCOVERY = 0x1;
	//        UUID 
	private static final UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
	//         
	private BluetoothAdapter bluetoothAdapter = null;
	//          
	private BluetoothDevice device = null;
	//     socket
	private BluetoothSocket btSocket = null;
	//      
	private OutputStream outStream = null;
	private byte[] msgBuffer = null;
	//      
	private SensorManager sensorMgr = null;
	//      
	private Sensor sensor = null;
	//   x、y、z     
	private int x, y, z;

	/**
	 *    activity              
	 **/
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		/*         */
		//       title     
		this.setTheme(android.R.style.Theme_NoTitleBar_Fullscreen);
		//     
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		//       
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);

		//  bluetooth.xml      
		setContentView(R.layout.bluetooth);

		// Gravity sensing      
		sensorMgr = (SensorManager) this.getSystemService(SENSOR_SERVICE);
		sensor = sensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

		//              
		bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

		//         
		bluetoothAction();

		//                 
		connectToDevice();
	}

	/**
	 *                ,      ,     。            ,      。
	 */
	public void bluetoothAction() {
		//              
		if (hasAdapter(bluetoothAdapter)) {
			if (!bluetoothAdapter.isEnabled()) {
				//       
				bluetoothAdapter.enable();
			}
		} else {
			//     
			this.finish();
		}
	}

	/**
	 *              
	 * 
	 * @param ba
	 *                   
	 * @return boolean
	 */
	public boolean hasAdapter(BluetoothAdapter ba) {
		if (ba != null) {
			return true;
		}
		displayLongToast("         !");
		return false;
	}

	/**
	 *               toast
	 * 
	 * @param str
	 *                 
	 */
	public void displayLongToast(String str) {
		Toast toast = Toast.makeText(this, str, Toast.LENGTH_LONG);
		toast.setGravity(Gravity.TOP, 0, 220);
		toast.show();
	}
	
	/**
	 *               toast
	 * 
	 * @param str
	 *                 
	 */
	public void displayShortToast(String str) {
		Toast toast = Toast.makeText(this, str, Toast.LENGTH_SHORT);
		toast.setGravity(Gravity.TOP, 0, 220);
		toast.show();
	}

	/**
	 *      ,                  
	 */
	public void connectToDevice() {
		if (bluetoothAdapter.isEnabled()) {
			//      activity---DiscoveryActivity,               。
			Intent intent = new Intent(this, DiscoveryActivity.class);
			//       
			displayLongToast("             !");

			//       DiscoveryActivity    。
			//   :  startActivityForResult           。
			//     :http://snmoney.blog.163.com/blog/static/440058201073025132670/
			this.startActivityForResult(intent, REQUEST_DISCOVERY);
		} else {
			this.finish();
		}
	}

	/**
	 * startActivityForResult    DiscoveryActivity     
	 *              ,           
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		// super.onActivityResult(requestCode, resultCode, data);

		//                 
		if (requestCode != REQUEST_DISCOVERY) {
			return;
		}
		if (resultCode != RESULT_OK) {
			return;
		}

		//    DiscoveryActivity              
		String addressStr = data.getStringExtra("address");
		//                  (           ,     )
		device = bluetoothAdapter.getRemoteDevice(addressStr);
		try {
			//  UUID       
			btSocket = device.createRfcommSocketToServiceRecord(uuid);
		} catch (Exception e) {
			displayLongToast("        !");
		}

		if (btSocket != null) {
			try {
				//           ,             。
				btSocket.connect();
				displayLongToast("        !");
			} catch (IOException ioe) {
				displayLongToast("        !");
				try {
					btSocket.close();
					displayLongToast("       !");
				} catch (IOException ioe2) {
					displayLongToast("        ,    !");
				}
			} 
			try {
				//      
				outStream = btSocket.getOutputStream();
				//       
				sendSensorData();
			} catch (IOException e) {
				displayLongToast("       !");
			} 
		}
	}

	/**
	 *                        
	 */
	public void sendSensorData() {
		//       
		SensorEventListener lsn = new SensorEventListener() {
			//       ,              。
			@Override
			public void onAccuracyChanged(Sensor s, int accuracy) {
				// TODO Auto-generated method stub
			}

			//       ,               。
			@Override
			public void onSensorChanged(SensorEvent se) {
				// TODO Auto-generated method stub
				/**
				 *                  x=10,y=0,z=0;              x=0,y=10,z=0;
				 *            x=0,y=0,z=10;     :               , :     X 
				 *     Y          Z           ---SensorDemo
				 */
				x = (int)se.values[SensorManager.DATA_X];
				y = (int)se.values[SensorManager.DATA_Y];
				z = (int)se.values[SensorManager.DATA_Z];
				if (y > 5 || y < -5) {
//					String str = String.valueOf(x).concat(String.valueOf(y)).concat(String.valueOf(z));
					String str = "x" + String.valueOf(x) + "y" + String.valueOf(y) + "z" + String.valueOf(z) + "/";
					msgBuffer = str.getBytes();
					try {
						System.out.println("x=" + x + " y =" + y + " z =" + z);
						outStream.write(msgBuffer);
					} catch (IOException e) {
						displayShortToast("      !");
					}
				}
//				if (y > 5 || y < -5) {
//					DataModel dataModel=new DataModel(x,y,z);
//					try {
//						System.out.println("x=" + x + " y =" + y + " z =" + z);
//						msgBuffer = dataModel.convertSelfToByteArray();
//						System.out.println("--------"+msgBuffer.length);
//						outStream.write(msgBuffer);
//					} catch (IOException e) {
//						Log.e("BlueTooth",e.getMessage());
//						e.printStackTrace();
//						displayShortToast("      !");
//					}
//				}
			}
		};
		

		//           ,  android                  。
		//      。      ,                  。 AndroidManifest.xml  。
		sensorMgr
				.registerListener(lsn, sensor, SensorManager.SENSOR_DELAY_GAME);
	}

	// ////////////////////            ,        /////////////////////////////////
	/**
	 *     :     ,        。
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			Builder alertDialog = new AlertDialog.Builder(this);
			//         
			alertDialog.setIcon(R.drawable.icon);
			//       title
			alertDialog.setTitle(R.string.prompt);
			//           
			alertDialog.setMessage(R.string.quit);
			//             
			alertDialog.setPositiveButton(R.string.confirm,
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog,
								int whichButton) {
							// TODO Auto-generated method stub
							try {
								outStream.write("QUIT".getBytes());
								btSocket.close();
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							finish(); 
						}
					});
			//             (      )
			alertDialog.setNegativeButton(R.string.cancel,
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
						}
					});
			//      
			alertDialog.show();
			return true;
		} else {
			//             ,              。
			return super.onKeyDown(keyCode, event);
		}
	}

	/**
	 *     :    ,    。
	 */
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		System.exit(0);
	}

}

 DiscoveryActivity.java
package com.royal.bluetooth;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import android.app.ListActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ListView;
import android.widget.SimpleAdapter;

/**
 *     ListActivity,                        BlueTooth
 * 
 * @author royal
 */
public class DiscoveryActivity extends ListActivity {

	//              
	private BluetoothAdapter blueToothAdapter = BluetoothAdapter
			.getDefaultAdapter();

	//     HashMap             list                  
	private ArrayList<HashMap<String, String>> list = null;
	//                  list
	private List<BluetoothDevice> _devices = new ArrayList<BluetoothDevice>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		/*         */
		//       title     
		this.setTheme(android.R.style.Theme_NoTitleBar_Fullscreen);
		//     
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		//       
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);

		//  discovery.xml      
		setContentView(R.layout.discovery);

		list = new ArrayList<HashMap<String, String>>();

		//               list ,       
		showDevices();
	}

	/**
	 *               list ,       。
	 */
	public void showDevices() {
		//             
		Set<BluetoothDevice> devices = blueToothAdapter.getBondedDevices();

		if (devices.size() > 0) {
			Iterator<BluetoothDevice> it = devices.iterator();
			BluetoothDevice bluetoothDevice = null;
			HashMap<String, String> map = new HashMap<String, String>();
			while (it.hasNext()) {
				bluetoothDevice = it.next();
				//                      HashMap   ,  :xx:xx:xx:xx:xx: royal
				map.put("address", bluetoothDevice.getAddress());
				map.put("name", bluetoothDevice.getName());
				//  list           ,         map
				list.add(map);
				//  list                  
				_devices.add(bluetoothDevice);
			}

			//               ,            。   google  SimpleAdapter       
			SimpleAdapter listAdapter = new SimpleAdapter(this, list,
					R.layout.device, new String[] { "address", "name" },
					new int[] { R.id.address, R.id.name });
			this.setListAdapter(listAdapter);
		}
	}

	/**
	 * list                  ,              。
	 */
	protected void onListItemClick(ListView l, View v, int position, long id) {
		Intent result = new Intent();
		String addressStr = _devices.get(position).getAddress();
		//     17 ,  addressStr address    xx:xx:xx:xx:xx:xx
		String address = addressStr.substring(addressStr.length() - 17);
		
		result.putExtra("address", address);
		//          ,      BlueTooth---activity
		//    resultCode RESULT_OK,BlueTooth---activity  onActivityResult    resultCode    RESULT_OK
		//  resultCode    ,    result       。
		setResult(RESULT_OK, result);
		//    finish,  finish        BlueTooth---activity
		//   onActivityResult   
		finish();
	}

}

 AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.royal.bluetooth"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
    
        <activity android:name=".BlueTooth"
                  android:label="@string/app_name" 
                  android:screenOrientation="landscape">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
        <activity android:name=".DiscoveryActivity"
        		  android:screenOrientation="landscape">
        	<intent-filter>
        		<action android:name="android.intent.action.MAIN"/>
        		<category android:name="android.intent.category.DEFAULT"/>
        	</intent-filter>
        </activity>

    </application>
    
    <!--              -->
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
    <uses-permission android:name="android.permission.BLUETOOTH"/>
    
    <uses-sdk android:minSdkVersion="7" />

</manifest> 

 device.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    android:paddingBottom="1dip"
    android:paddingLeft="10dip"
    android:paddingRight="10dip"
    android:paddingTop="1dip" >

    <TextView
        android:id="@+id/address"
        android:layout_width="180dip"
        android:layout_height="30dip"
        android:singleLine="true"
        android:textSize="10pt" />

    <TextView
        android:id="@+id/name"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="right"
        android:textSize="10pt" />

</LinearLayout>

 discovery.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical"
	android:layout_width="fill_parent" 
	android:layout_height="fill_parent">

	<LinearLayout
		android:id="@+id/listLinearLayout"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"
		android:orientation="vertical">
		
		<ListView
			android:id="@id/android:list"
			android:layout_width="fill_parent"
			android:layout_height="wrap_content"
			android:drawSelectorOnTop="false"
			android:scrollbars="vertical"/>
			
	</LinearLayout>
	
</LinearLayout>

좋은 웹페이지 즐겨찾기