I II III IV V. 16 A. 17 B. 18

Similar documents
[ 그림 8-1] XML 을이용한옵션메뉴설정방법 <menu> <item 항목ID" android:title=" 항목제목 "/> </menu> public boolean oncreateoptionsmenu(menu menu) { getme

안드로이드기본 11 차시어댑터뷰 1 학습목표 어댑터뷰가무엇인지알수있다. 리스트뷰와스피너를사용하여데이터를출력할수있다. 2 확인해볼까? 3 어댑터뷰 1) 학습하기 어댑터뷰 - 1 -

어댑터뷰

2) 활동하기 활동개요 활동과정 [ 예제 10-1]main.xml 1 <LinearLayout xmlns:android=" 2 xmlns:tools="

( )부록

03장

2 Application Name: Day10_yhg <LinearLayout android:layout_weight="3" > /> an

13ÀåÃß°¡ºÐ

01장

9 차시고급위젯다루기 1 학습목표 날짜 / 시간과관련된위젯을배운다. 웹뷰를사용하여간단한웹브라우저기능을구현한다. 매니패스트파일의설정법을배운다. 2 확인해볼까? 3 날짜 / 시간위젯 1) 활동하기 활동개요

[ 그림 7-1] 프로젝트 res 폴더 이미지뷰 [ 예제 7-1] 이미지뷰 1 <LinearLayout 2 ~~~~ 중간생략 ~~~~ 3 android:orientation="vertical" > 4 <ImageView

REMON Android SDK GUIDE (SDK Version 1.4.1) 1 / 25

OpenCV와 함께하는 컴퓨터 비전 프로그래밍 캠프

학습목표 메뉴를추가하는방법을이해하고실습할수있다. 프로그램의기본설정 (settings) 을정의하는방법을알고실습할수있다. 대화상자를여는방법을알고실습할수있다. 로그메시지로디버깅하는방법을이해한다. 디버거로디버깅하는방법을이해한다.

학습목표 선언하여디자인을하는방법을이해하고, 실행할수있다. 시작화면을만드는방법과대체리소스를사용하는방법을이해하고실행할수있다. About 과같은상자를구현하고, 테마를적용하는법을이해하고실행할수있다.

리니어레이아웃 - 2 -

슬라이드 1

50_1953.pdf

안드로이드2_14

이것은리스트뷰의 setadapter 메소드에잘표현되어있습니다. setadapter 는리스트뷰에사용할데이터객체를넘겨주는메소드입니다. 일반적으로생각한다면 ArrayAdapter 객체를생성하여사용할데이터를저장할것이고데이터가저장된 ArrayAdapter 객체를 setadapt

PowerPoint 프레젠테이션

XML Parser

Mobile Service > IAP > Android SDK [ ] IAP SDK TOAST SDK. IAP SDK. Android Studio IDE Android SDK Version (API Level 10). Name Reference V

자바-11장N'1-502

rosaec_workshop_talk

PowerPoint 프레젠테이션

JMF3_심빈구.PDF

// 화면을터치하였을때해야할작업구현 case MotionEvent.ACTION_MOVE: // 화면을드래그하였때 // 화면을드래그하였을때해야할작업구현 case MotionEvent.ACTION_UP: // 화면에서터치가사라질때 // 화면에서터치가사라질때해야할자업구현 c

Daum 카페

12-file.key

Microsoft PowerPoint - 04-UDP Programming.ppt

02 C h a p t e r Java

I T C o t e n s P r o v i d e r h t t p : / / w w w. h a n b i t b o o k. c o. k r

전자공학설계실험 A 보고서 화 6A ~ 9B 박종태교수님 제출기한 ( 화 ) Android I.S 작업환경 Eclipse_Juno ver. 전자공학부 이상엽전자공학부 오윤재전자공학부

비긴쿡-자바 00앞부속

신림프로그래머_클린코드.key

rmi_박준용_final.PDF

Microsoft PowerPoint - Supplement-03-TCP Programming.ppt [호환 모드]

Chap 8 호스트시스템개발환경구성및 안드로이드개발환경구축

헬로, 안드로이드 11 주차 위치파악하기와감지하기 강대기동서대학교컴퓨터정보공학부

12 주차 인텐트

RDS_MAN_NO 도로구간일련번호 NUMBER(12) BSI_INT_SN 기초구간일련번호 NUMBER(10) EQB_MAN_SN 건물군일련번호 NUMBER(10) BULD_SE_CD 건물구분코드 VARCHAR2(1) BULD_MNNM 건물본번 NUMBER(5) BUL

슬라이드 1

Microsoft PowerPoint - 03-TCP Programming.ppt

09-interface.key

학습목표 인텐트로다른액티비티나프로그램을실행시킬수있다. 웹뷰를통해웹화면을액티비티화면의일부로구성할수있다. 자바스크립트를통해안드로이드프로그램을호출하는방법을안다. 안드로이드응용프로그램에서웹서비스를이용하는방법을안다.

Analytics > Log & Crash Search > Unity ios SDK [Deprecated] Log & Crash Unity ios SDK. TOAST SDK. Log & Crash Unity SDK Log & Crash Search. Log & Cras

슬라이드 1

01 [ 일기장 ] 애플리케이션프로젝트작성 - [MyDiary] 앱 Mobile Apps >> [MyDiary] 앱프로젝트구조설계 일기장애플리케이션인 [MyDiary] 앱은메인화면과일기장의내용을작성하는화면으로이루어져있다. 화면이 2개라는것은액티비티가 2개이고액티비티에대

헬로, 안드로이드 7 주차 멀티미디어 강대기동서대학교컴퓨터정보공학부

교육2 ? 그림

歯JavaExceptionHandling.PDF

Chap12

슬라이드 1

1부


변수이름 변수값 PATH ;C:\Program Files\Java\jdk1.8.0_45\bin CLASSPATH.;C:\Program Files\jdk1.8.0_45\lib\tools.jar JAVA_HOME C:\Program Files\Java\jdk1.8.0_45

구글안드로이드프로그래밍액티비티, 인텐트수신자, 그리고서비스 안드로이드애플리케이션의구성요소에는액티비티, 인텐트수신자, 서비스, 컨텐트제공자가있다. 이번호에서는사용자인터페이스를위한액티비티와백그라운드서비스를위한인텐트수신자, 그리고서비스의라이프사이클과활용법에대해살펴보도록하자.

JMF2_심빈구.PDF

adlibr-android_4.x

1

Interstage5 SOAP서비스 설정 가이드

untitled

DocsPin_Korean.pages

Secure Programming Lecture1 : Introduction

Microsoft PowerPoint - 4주차_Android_UI구현.ppt [호환 모드]

ch09

목차 INDEX JSON? - JSON 개요 - JSONObject - JSONArray 서울시공공데이터 API 살펴보기 - 요청인자살펴보기 - Result Code - 출력값 HttpClient - HttpHelper 클래스작성 - JSONParser 클래스작성 공공

Eclipse 와 Firefox 를이용한 Javascript 개발 발표자 : 문경대 11 년 10 월 26 일수요일

01-OOPConcepts(2).PDF

MasoJava4_Dongbin.PDF

PowerPoint 프레젠테이션

@OneToOne(cascade = = "addr_id") private Addr addr; public Emp(String ename, Addr addr) { this.ename = ename; this.a

제11장 프로세스와 쓰레드

Connection 8 22 UniSQLConnection / / 9 3 UniSQL OID SET

iii. Design Tab 을 Click 하여 WindowBuilder 가자동으로생성한 GUI 프로그래밍환경을확인한다.

1. 개요 - 계획서 프로젝트개요프로그램명 : 닥터 119 제작배경애완견을키우는사람들이부득이하게병원에가지못할경우에이앱을통해서자가진단을통해상태의심각성을알수있게되고또가까운동물병원으로갈수있는지도와전화번호를제공한다. 그리고애견다이어리기능을통해애견의성장과정과추억들을저

목차 1. Samsung In-App Purchase 소개 다운로드 IAP 3.0 Helper & Sample IAP 3 제약사항 IAP 3 개발모드 지원상품타입 IAP 3

Spring Boot/JDBC JdbcTemplate/CRUD 예제

¾Èµå·ÎÀÌµå ³¹Àå-Åë.PDF

<C0CCBCBCBFB52DC1A4B4EBBFF82DBCAEBBE7B3EDB9AE2D D382E687770>

mytalk

05-class.key

PowerPoint Presentation

PowerPoint 프레젠테이션

자바GUI실전프로그래밍2_장대원.PDF

FileMaker ODBC and JDBC Guide

한이음 IT 멘토링프로젝트 Android App 개발가이드 (2) - Google Maps 와 GPS 를연동한 Android App 개발 - Ver 1.02 (Update )

14-Servlet

위젯과레이아웃위젯은 View 클래스를상속해화면디스플레이와이벤트처리를할수있도록구현된스크린구성의최소단위를말한다. android.widget 패키지에는여러유형의위젯들이포함되어있다. TextView, ImageView, Button, ImageButton 등은가장간단한위젯들이

PowerPoint Presentation

5장.key

Dialog Box 실행파일을 Web에 포함시키는 방법

학습목표 게임이나프로그램에옵션을추가하는방법을알아본다. 이전의프로그램을계속하기위해상태를저장하는방법을알아본다. 게임에서현재의실행위치를저장하는방법에대해알아본다. 내부의파일시스템을읽고쓰는방법에대해알아본다. SD 카드에접근하는방법에대해알아본다. 여러 UI 위젯들에대해알아본다.

Cluster management software

3ÆÄÆ®-11

오핀 (OFIN) SDK Guide Fintech Mobile SDK Guide - Android V 1.0 OPPFLIB 1

안드로이드애플리케이션과통합하는데는자바가편하므로대표적인두가지라이브러리를비교해보자. 자바 ID3 태그라이브러리 jaudiotagger ID3v1, ID3v1.1, Lyrics3v1, Mp3, Mp4 (Mp4 오디오, M4a 지원범위 Lyrics3v2, ID3v2.2, ID

chapter4

04장

Transcription:

2016 12 2 : ( )

I. 1 1.1 1 1.2 1 1.3 1 II. 3 2.1 3 2.2 4 2.3 5 III. 6 3.1 6 3.2 7 3.3 7 3.4 7 IV. 11 4.1 11 4.2 12 4.3 13 4.4 15 V. 16 A. 17 B. 18

I. 1.1,.. NFC(Near Field Communication) NFC. NFC.. 1.2.... 1.3.. 1. 1.. - 1 -

그림 1 예상구상도 100%.. 300.. 그림 2 쿠도이노사진..... - 2 -

.. MAC(Media Access Control Address). MAC NIC(Network Interface Card) 48. MAC MAC. II. 2.1....,,.,.. ' (OHA Open Handset Alliance)' 2007 11. (Google), ' '. (Linux) 2.6 (OS;operating system),, - 3 -

... ' '..,..., (Microcontroller). LED.... (Atmel AVR),...,. C++++ C++.,, LED,,, ( ).. - 4 -

그림 3 쿠도이노핀번호 2.2 그림 4 어플리케이션의동작순서 - 5 -

2.3 2.2 MAC.. Lock/Unlock. 그림 5 어플리케이션기본레이아웃. if (BTSerial.available()) Serial.println(BTSerial.read());. 3 4. Lock/Unlock. - 6 -

III. 3.1 표 3.1 업무분담표 팀원 김동식 송지호 업무분담업무 - 어플리케이션프로그램제작 - 아두이노스케쳐를사용하여쿠도이소소스코딩 - 프로그래밍화면디자인 - 졸업작품전시회출품및결과발표 - 쿠도이노를이용한하드웨어적부분제작 - 프로그램디버깅 - 작품실행및성능평가 - 졸업작품전시회출품및결과발표 3.2 표 2 15. 15. 15. 16. 16. 16. 16. 16. 16. 16. 16. 16. 주제선정도어락회로분석블루투스모듈, 쿠도이노 set 10 11 12 1 2 3 4 5 7 8 9 10 자료조사회로구성블루투스통신및쿠도이노 코딩도어락모터제어오픈소스활용도어락블루 투스제어어플리케이션제작기능수정 - 7 -

3.3 3.3.1 l (NT910S3Q-MD1S, ) l ( SⅡ) 3.3.2 l l l l 3.4 l l l Microsoft Windows 7 pro 32 Eclips l Java SE 2.1a l - 8 -

IV. 4.1 그림 6 작품전체사진 그림 7 도어락본체사진 - 9 -

그림 8 쿠도이노사진 4.2-10 -

그림 9 어플리케이션 4.3 -. -. - -. - - 11 -

4.4 -. - -, - -. RSSI -. LED - 12 -

V. [1],,, 2016 1 3 [2],,, [3],,, - 13 -

A. (, ) #include<softwareserial.h> SoftwareSerial BTSerial(13, 12); int input_1 = 11; int input_2 = 10; // & // void setup() { Serial.begin(9600); BTSerial.begin(9600); pinmode(11,output); pinmode(10,output); void loop() { if (BTSerial.available()) { // Serial.println(BTSerial.read()); // int abc; abc = BTSerial.read(); //data if(abc=='4') { digitalwrite(11, HIGH); digitalwrite(10, LOW); delay(800); digitalwrite(11, HIGH); digitalwrite(10, HIGH); - 14 -

if(abc =='0') { digitalwrite(11, LOW); digitalwrite(10, HIGH); delay(800); digitalwrite(11, HIGH); digitalwrite(10, HIGH); if(abc =='5') { digitalwrite(11, LOW); digitalwrite(10, LOW): if(abc =='7') { digitalwrite(11, HIGH); digitalwrite(10, HIGH); - 15 -

B. <MainActivity.java> package kr.re.dev.arduinoecho; import java.io.ioexception;import java.io.inputstream; import java.io.outputstream; import java.lang.reflect.field; import java.nio.bytebuffer; import java.util.linkedlist; import java.util.set; import kr.re.dev.bluetooth.bluetoothserialclient; import kr.re.dev.bluetooth.bluetoothserialclient.bluetoothstreaminghandler; import kr.re.dev.bluetooth.bluetoothserialclient.onbluetoothenabledlistener; import kr.re.dev.bluetooth.bluetoothserialclient.onscanlistener; import kr.re.dev.bluetoothecho.r; import android.app.activity; import android.app.alertdialog; import android.app.progressdialog; import android.bluetooth.bluetoothdevice; import android.bluetooth.bluetoothsocket; import android.content.dialoginterface; import android.content.intent; import android.content.dialoginterface.oncancellistener; import android.graphics.color; import android.os.bundle; import android.text.html; import android.text.method.scrollingmovementmethod; import android.util.log; import android.view.menu; import android.view.menuitem; import android.view.view; import android.view.view.onclicklistener; import android.view.viewconfiguration; import android.widget.adapterview; import android.widget.adapterview.onitemclicklistener; import arduino.bt.simplebt.bluetoothservice; import arduino.bt.simplebt.devicelistactivity; import android.widget.arrayadapter; import android.widget.button; import android.widget.edittext; import android.widget.listview; import android.widget.textview; import android.widget.toast; public class MainActivity extends Activity { private static final boolean D = false; - 16 -

private static final String TAG = null; protected static final String mdevices = null; private LinkedList<BluetoothDevice> mbluetoothdevices = new LinkedList<BluetoothDevice>(); private ArrayAdapter<String> mdevicearrayadapter; private EditText medittextinput; private TextView mtextview; private Button mbuttonsend; private Button mrock; private Button munrock; private boolean mconnecttoselectddevice; private ProgressDialog mloadingdialog; private AlertDialog mdevicelistdialog; private Menu mmenu; private BluetoothSerialClient mclient; private boolean write; private Object mremotedevice; private Object mbluetoothadapter; protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); mclient = BluetoothSerialClient.getInstance(); if(mclient == null) { Toast.makeText(getApplicationContext(), "Cannot use the Bluetooth device.", Toast.LENGTH_SHORT).show(); finish(); overflowmenuinactionbar(); initprogressdialog(); initdevicelistdialog(); initwidget(); private void overflowmenuinactionbar(){ try { ViewConfiguration config = ViewConfiguration.get(this); Field menukeyfield = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey"); if(menukeyfield!= null) { menukeyfield.setaccessible(true); menukeyfield.setboolean(config, false); catch (Exception ex) { //. 3.x. //, 3.x. - 17 -

protected void onpause() { mclient.cancelscan(getapplicationcontext()); super.onpause(); protected void onresume() { super.onresume(); enablebluetooth(); private void initprogressdialog() { mloadingdialog = new ProgressDialog(this); mloadingdialog.setcancelable(false); private void initwidget() { mtextview = (TextView) findviewbyid(r.id.textviewterminal); mtextview.setmovementmethod(new ScrollingMovementMethod()); medittextinput = (EditText) findviewbyid(r.id.edittextinput); mbuttonsend = (Button) findviewbyid(r.id.buttonsend); mrock=(button)findviewbyid(r.id.rock); munrock=(button)findviewbyid(r.id.unrock); mbuttonsend.setonclicklistener(new OnClickListener(){ public void onclick(view v) { sendstringdata(medittextinput.gettext().tostring(), 0); medittextinput.settext(""); ); mrock.setonclicklistener(new OnClickListener(){ public void onclick(view v) { sendstringdata(medittextinput.gettext().tostring(), 0); medittextinput.settext(" (00)\n**************************"); sendstringdata(medittextinput.gettext().tostring(), 0); medittextinput.settext(""); ); munrock.setonclicklistener(new OnClickListener(){ public void onclick(view v) { sendstringdata(medittextinput.gettext().tostring(), 0); medittextinput.settext(" (44)\n**************************"); sendstringdata(medittextinput.gettext().tostring(), 0); medittextinput.settext(""); - 18 -

{ ); private void initdevicelistdialog() { mdevicearrayadapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.item_device); ListView listview = new ListView(getApplicationContext()); listview.setadapter(mdevicearrayadapter); listview.setonitemclicklistener(new OnItemClickListener() { public void onitemclick(adapterview<?> parent, View view, int position, long id) String item = (String) parent.getitematposition(position); for(bluetoothdevice device : mbluetoothdevices) { if(item.contains(device.getaddress())) { connect(device, mclient); mdevicelistdialog.cancel(); ); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.settitle("select bluetooth device"); builder.setview(listview); builder.setpositivebutton("scan", new DialogInterface.OnClickListener() { public void onclick(dialoginterface dialog, int id) { scandevices(); ); mdevicelistdialog = builder.create(); mdevicelistdialog.setcanceledontouchoutside(false); private void adddevicetoarrayadapter(bluetoothdevice device) { if(mbluetoothdevices.contains(device)) { mbluetoothdevices.remove(device); mdevicearrayadapter.remove(device.getname() + "\n" + device.getaddress()); mbluetoothdevices.add(device); mdevicearrayadapter.add(device.getname() + "\n" + device.getaddress() ); mdevicearrayadapter.notifydatasetchanged(); private void enablebluetooth() { BluetoothSerialClient btset = mclient; btset.enablebluetooth(this, new OnBluetoothEnabledListener() { - 19 -

public void onbluetoothenabled(boolean success) { if(success) { getpaireddevices(); else { finish(); ); private void addtext(string text) { mtextview.append(text); final int scrollamount = mtextview.getlayout().getlinetop(mtextview.getlinecount()) - mtextview.getheight(); if (scrollamount > 0) mtextview.scrollto(0, scrollamount); else mtextview.scrollto(0, 0); private void getpaireddevices() { Set<BluetoothDevice> devices = mclient.getpaireddevices(); for(bluetoothdevice device: devices) { adddevicetoarrayadapter(device); mconnecttoselectddevice(); private void mconnecttoselectddevice() { // TODO Auto-generated method stub private void scandevices() { BluetoothSerialClient btset = mclient; btset.scandevices(getapplicationcontext(), new OnScanListener() { String message =""; public void onstart() { Log.d("Test", "Scan Start."); mloadingdialog.show(); message = "Scanning..."; mloadingdialog.setmessage("scanning..."); - 20 -

mloadingdialog.setcancelable(true); mloadingdialog.setcanceledontouchoutside(false); mloadingdialog.setoncancellistener(new OnCancelListener() { public void oncancel(dialoginterface dialog) { BluetoothSerialClient btset = mclient; btset.cancelscan(getapplicationcontext()); ); public void onfounddevice(bluetoothdevice bluetoothdevice) { adddevicetoarrayadapter(bluetoothdevice); message= "\n" + bluetoothdevice.getname() + "\n" + bluetoothdevice.getaddress(); mloadingdialog.setmessage(message); public void onfinish() { Log.d("Test", "Scan finish."); message = ""; mloadingdialog.cancel(); mloadingdialog.setcancelable(false); mloadingdialog.setoncancellistener(null); mdevicelistdialog.show(); ); void connecttoselectddevice(object msocket) { mremotedevice = getdevicefrombondedlist(accessibility_service); java.util.uuid uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); try { // msocket = ((BluetoothDevice) mremotedevice).createrfcommsockettoservicerecord(uuid); // RFCOMM ((BluetoothSocket) msocket).connect(); // OutputStream moutputstream = ((BluetoothSocket) msocket).getoutputstream(); Object minputstream = ((BluetoothSocket) msocket).getinputstream(); // beginlistenfordata(); - 21 -

catch(exception e) { // finish(); // private void beginlistenfordata() { // TODO Auto-generated method stub private Object getdevicefrombondedlist(string selecteddevicename) { // TODO Auto-generated method stub return null; private void connect(bluetoothdevice device, BluetoothSerialClient handler) { mloadingdialog.setmessage("connecting..."); mloadingdialog.setcancelable(false); mloadingdialog.show(); BluetoothSerialClient btset = mclient; btset.connect(getapplicationcontext(), device, mbthandler); handler.write("44".getbytes()); /* try { Thread.sleep(12000); catch (InterruptedException e) { // TODO Auto-generated catch block e.printstacktrace(); handler.write("00".getbytes());*/ /* */ private BluetoothStreamingHandler mbthandler = new BluetoothStreamingHandler() { ByteBuffer mmbytebuffer = ByteBuffer.allocate(1024); public void onerror(exception e) { mloadingdialog.cancel(); addtext("blue : Connection error - " + e.tostring() + "\n"); mmenu.getitem(0).settitle(r.string.action_connect); public void ondisconnected() { mmenu.getitem(0).settitle(r.string.action_connect); mloadingdialog.cancel(); addtext("blue : Disconnected.\n"); - 22 -

public void ondata(byte[] buffer, int length) { if(length == 0) return; if(mmbytebuffer.position() + length >= mmbytebuffer.capacity()) { ByteBuffer newbuffer = ByteBuffer.allocate(mmByteBuffer.capacity() * 2); newbuffer.put(mmbytebuffer.array(), 0, mmbytebuffer.position()); mmbytebuffer = newbuffer; mmbytebuffer.put(buffer, 0, length); if(buffer[length - 1] == '\0') { addtext(mclient.getconnecteddevice().getname() + " : " + new String(mmByteBuffer.array(), 0, mmbytebuffer.position()) + '\n'); mmbytebuffer.clear(); public void onconnected() { addtext(" 1.. ## & ##\n" 2.. ## ## \n " + "3..\n 4. 5.\n # bluetooth name : " + " " + mclient.getconnecteddevice().getname() + "\n\n\n"); mloadingdialog.cancel(); mmenu.getitem(0).settitle(r.string.action_disconnect); ; private BluetoothSerialClient handler; private void sendmessage(charsequence message) { if (mbtservice.getstate()!= BluetoothService.STATE_CONNECTED) Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show(); return; public void sendstringdata(string data, int length) { data += '\0'; byte[] buffer = data.getbytes(); if(mbthandler.write(buffer)) { addtext("blue : " + data + '\n'); //************************************************************************* protected void ondestroy() { super.ondestroy(); - 23 -

mclient.claer(); ; public boolean oncreateoptionsmenu(menu menu) { getmenuinflater().inflate(r.menu.main, menu); mmenu = menu; return true; public boolean onoptionsitemselected(menuitem item) { boolean connect = mclient.isconnection(); if(item.getitemid() == R.id.action_connect) { if (!connect) { mdevicelistdialog.show(); else { mbthandler.close(); return true; else { showcodedlg(); return true; private void showcodedlg() { TextView codeview = new TextView(this); codeview.settext(html.fromhtml(readcode())); codeview.setmovementmethod(new ScrollingMovementMethod()); codeview.setbackgroundcolor(color.parsecolor("#202020")); new AlertDialog.Builder(this, android.r.style.theme_holo_light_dialogwhenlarge).setview(codeview).setpositivebutton("ok", new AlertDialog.OnClickListener() { public void onclick(dialoginterface dialog, int which) { dialog.cancel(); ).show(); private String readcode() { try { InputStream is = getassets().open("hc_06_echo.txt"); int length = is.available(); byte[] buffer = new byte[length]; is.read(buffer); is.close(); String code = new String(buffer); buffer = null; - 24 -

return code; catch (IOException e) { e.printstacktrace(); return ""; public void Rock(View view){ sendmessage("00"); public void Unrock(View view){ sendmessage("44"); //************************************************************************* - 25 -

<Bluetoothserialclient.java> package kr.re.dev.bluetooth; import java.io.ioexception; import java.io.inputstream; import java.io.outputstream; import java.util.set; import java.util.uuid; import java.util.concurrent.executorservice; import java.util.concurrent.executors; import java.util.concurrent.atomic.atomicboolean; 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.os.handler; import android.os.looper; public class BluetoothSerialClient { static final private String SERIAL_UUID = "00001101-0000-1000-8000-00805F9B34FB"; static private BluetoothSerialClient sthis = null; private static String address = "20:15:06:10:58:94"; private BluetoothAdapter mbluetoothadapter; private OnBluetoothEnabledListener monbluetoothuplistener; private OnScanListener monscanlistener; private BluetoothSocket mbluetoothsocket; private UUID muuid = UUID.fromString(SERIAL_UUID); private AtomicBoolean misconnection = new AtomicBoolean(false); private ExecutorService mreadexecutor; private ExecutorService mwriteexecutor; private BluetoothStreamingHandler mbluetoothstreaminghandler; private Handler mmainhandler = new Handler(Looper.getMainLooper()); private BluetoothDevice cbnublue; private BluetoothDevice mconnecteddevice= cbnublue; private InputStream minputstream; private OutputStream moutputstream; /** * BluetoothSerialClient. * @return BluetoothSerialClient. null. - 26 -

*/ public static BluetoothSerialClient getinstance() { if(sthis == null) { sthis = new BluetoothSerialClient(); if(sthis.mbluetoothadapter == null) { sthis = null; return null; return sthis; private BluetoothSerialClient() { mbluetoothadapter = BluetoothAdapter.getDefaultAdapter(); mreadexecutor = Executors.newSingleThreadExecutor(); mwriteexecutor = Executors.newSingleThreadExecutor(); /** *. *. */ public void claer() { close(); mreadexecutor.shutdownnow(); mwriteexecutor.shutdownnow(); sthis = null; /** *. <br/> *,. * @param context activity * @param onbluetoothenabledlistener on/off. */ public void enablebluetooth(context context, OnBluetoothEnabledListener onbluetoothenabledlistener) { if(!mbluetoothadapter.isenabled()) { monbluetoothuplistener = onbluetoothenabledlistener; Intent intent = new Intent(context, BluetoothUpActivity.class); context.startactivity(intent); else { onbluetoothenabledlistener.onbluetoothenabled(true); /** - 27 -

*. * @return false off. */ public boolean isenabled() { return mbluetoothadapter.isenabled(); /** *. * @param context * @param device. {@link getpaireddevices {@link scandevices. * @param bluetoothstreaminghandler. * @return false. {@link enablebluetooth. */ public boolean connect(final Context context,final BluetoothDevice device, final BluetoothStreamingHandler bluetoothstreaminghandler) { if(!isenabled()) return false; mconnecteddevice = device; mbluetoothstreaminghandler = bluetoothstreaminghandler; if(isconnection()) { mwriteexecutor.execute(new Runnable() { public void run() { try { misconnection.set(false); mbluetoothsocket.close(); Thread.sleep(2000); catch (InterruptedException e) { e.printstacktrace(); catch (IOException e) { e.printstacktrace(); connect(context, device, bluetoothstreaminghandler); ); else { misconnection.set(true); connectclient(); return true; /** *. * @return */ - 28 -

public Set<BluetoothDevice> getpaireddevices() { Set<BluetoothDevice> paireddevices = mbluetoothadapter.getbondeddevices(); if(paireddevices.size() > 0){ BluetoothDevice getdevicefrombondedlist; { BluetoothDevice selecteddevice = null; //. return paireddevices; // TODO Auto-generated method stub /** *. * @param context * @param OnScanListener. * @return */ public boolean scandevices(context context, OnScanListener OnScanListener) { if(!mbluetoothadapter.isenabled()) return false; if(mbluetoothadapter.isdiscovering()) { mbluetoothadapter.canceldiscovery(); try { context.unregisterreceiver(mdiscoveryreceiver); catch(illegalargumentexception e) { e.printstacktrace(); monscanlistener = OnScanListener; IntentFilter filterfound = new IntentFilter(BluetoothDevice.ACTION_FOUND); filterfound.addaction(bluetoothadapter.action_discovery_started); filterfound.addaction(bluetoothadapter.action_discovery_finished); context.registerreceiver(mdiscoveryreceiver, filterfound); mbluetoothadapter.startdiscovery(); return true; /** *. * @param context */ public void cancelscan(context context) { if(!mbluetoothadapter.isenabled()!mbluetoothadapter.isdiscovering()) return; - 29 -

mbluetoothadapter.canceldiscovery(); try { context.unregisterreceiver(mdiscoveryreceiver); catch(illegalargumentexception e) { e.printstacktrace(); if(monscanlistener!= null) monscanlistener.onfinish(); /** *. * @return true/false */ public boolean isconnection() { return misconnection.get(); /** *. * @return null. */ public BluetoothDevice getconnecteddevice() { return mconnecteddevice; private void connectclient() { try { mbluetoothsocket = mconnecteddevice.createrfcommsockettoservicerecord(muuid); catch (IOException e) { close(); e.printstacktrace(); mbluetoothstreaminghandler.onerror(e); return; mwriteexecutor.execute(new Runnable() { public void run() { try { mbluetoothadapter.canceldiscovery(); mbluetoothsocket.connect(); manageconnectedsocket(mbluetoothsocket); callconnectedhandlerevent(); mreadexecutor.execute(mreadrunnable); catch (final IOException e) { close(); e.printstacktrace(); mmainhandler.post(new Runnable() { public void run() { - 30 -

mbluetoothstreaminghandler.onerror(e); ); misconnection.set(false); try { mbluetoothsocket.close(); catch (Exception ec) { ec.printstacktrace(); ); private void manageconnectedsocket(bluetoothsocket socket) throws IOException { minputstream = socket.getinputstream(); moutputstream = socket.getoutputstream(); private void callconnectedhandlerevent() { mmainhandler.post(new Runnable() { public void run() { mbluetoothstreaminghandler.onconnected(); ); public boolean write(final byte[] buffer) { if(!misconnection.get()) return false; mwriteexecutor.execute(new Runnable() { public void run() { try { moutputstream.write(buffer); catch (Exception e) { close(); e.printstacktrace(); mbluetoothstreaminghandler.onerror(e); ); return true; private boolean close() { mconnecteddevice = null; if(misconnection.get()) { misconnection.set(false); try { - 31 -

; ; mbluetoothsocket.close(); catch (IOException e) { e.printstacktrace(); mmainhandler.post(mcloserunable); return true; return false; private Runnable mcloserunable = new Runnable() { public void run() { if(mbluetoothstreaminghandler!= null) { mbluetoothstreaminghandler.ondisconnected(); private Runnable mreadrunnable = new Runnable() { public void run() { try { final byte[] buffer = new byte[256]; final int readbytes = minputstream.read(buffer); mmainhandler.post(new Runnable() { public void run() { if(mbluetoothstreaminghandler!= null) { mbluetoothstreaminghandler.ondata(buffer,readbytes); ); mreadexecutor.execute(mreadrunnable); catch (Exception e) { close(); e.printstacktrace(); private BroadcastReceiver mdiscoveryreceiver = new BroadcastReceiver() { public void onreceive(context context, Intent intent) { String action = intent.getaction(); if (BluetoothDevice.ACTION_FOUND.equals(action)) { BluetoothDevice device = intent.getparcelableextra(bluetoothdevice.extra_device); if(monscanlistener!= null) monscanlistener.onfounddevice(device); - 32 -

; else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { if(monscanlistener!= null) monscanlistener.onfinish(); try { context.unregisterreceiver(mdiscoveryreceiver); catch(illegalargumentexception e) { e.printstacktrace(); else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) { if(monscanlistener!= null) monscanlistener.onstart(); public static class BluetoothUpActivity extends Activity { private static int REQUEST_ENABLE_BT = 2; protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); getwindow().getdecorview().postdelayed(new Runnable() { public void run() { upbluetoothdevice();, 100); private void upbluetoothdevice() { BluetoothAdapter btadapter = BluetoothAdapter.getDefaultAdapter(); if (!btadapter.isenabled()) { Intent enablebtintent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); overridependingtransition(android.r.anim.fade_in, android.r.anim.fade_out); startactivityforresult(enablebtintent, REQUEST_ENABLE_BT) ; protected void onactivityresult(int requestcode, int resultcode, Intent data) { super.onactivityresult(requestcode, resultcode, data); if(requestcode == REQUEST_ENABLE_BT) { OnBluetoothEnabledListener onbluetoothenabledlistener = getinstance().monbluetoothuplistener; if (resultcode == Activity.RESULT_OK) { if(onbluetoothenabledlistener!= null) onbluetoothenabledlistener.onbluetoothenabled(true); finish(); else { if(onbluetoothenabledlistener!= null) onbluetoothenabledlistener.onbluetoothenabled(false); - 33 -

finish(); // End BluetoothUpActivity public static interface OnBluetoothEnabledListener { public void onbluetoothenabled(boolean success); public static interface OnScanListener { public void onstart(); public void onfounddevice(bluetoothdevice bluetoothdevice); public void onfinish(); public abstract static class BluetoothStreamingHandler { public abstract void onerror(exception e); public abstract void onconnected(); public abstract void ondisconnected(); public abstract void ondata(byte[] buffer, int length); public final boolean close() { BluetoothSerialClient btset = getinstance(); if(btset!= null) return btset.close(); return false; public final boolean write(byte[] buffer) { BluetoothSerialClient btset = getinstance(); if(btset!= null) return btset.write(buffer); return false; public void ondata(int i, int length) { // TODO Auto-generated method stub public void Rock(String string) { // TODO Auto-generated method stub public void Unrock(String string) { // TODO Auto-generated method stub public static String getaddress() { return address; public static void setaddress(string address) { BluetoothSerialClient.address = address; - 34 -

<androidmanifest.xml> <?xml version="1.0" encoding="utf-8" <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="kr.re.dev.bluetoothecho" android:versioncode="1" android:versionname="1.0" > <uses-permission android:name="android.permission.bluetooth" /> <uses-permission android:name="android.permission.bluetooth_admin" /> <uses-sdk android:minsdkversion="14" android:targetsdkversion="19" /> <application android:allowbackup="true" android:icon="@drawable/dsd" android:label="@string/app_name" android:theme="@style/apptheme" > <activity android:name="kr.re.dev.arduinoecho.mainactivity" android:label="@string/action_back" android:configchanges="screensize orientation keyboard" android:windowsoftinputmode="adjustresize"> <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> <activity android:name="kr.re.dev.bluetooth.bluetoothserialclient$bluetoothupactivity" android:theme="@android:style/theme.translucent.notitlebar" android:configchanges="orientation screensize keyboard"></activity> </application> </manifest> - 35 -

<activity_main.xml> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="kr.re.dev.arduinoecho.mainactivity" tools:ignore="mergerootframe" > <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:id="@+id/textviewterminal" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1" android:background="#f0f8ff" android:scrollbars="vertical" android:textsize="12sp" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" > <EditText android:id="@+id/edittextinput" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="2" android:ems="4" android:inputtype="textpersonname" > <requestfocus /> </EditText> <Button android:id="@+id/buttonsend" style="?android:attr/buttonstylesmall" android:layout_width="80dp" android:layout_height="wrap_content" - 36 -

android:text="send" /> <Button android:id="@+id/rock" android:onclick="rock" android:layout_width="0px" android:layout_weight="2" android:layout_height="wrap_content" android:text="rock" android:textsize="12sp" /> <Button android:id="@+id/unrock" android:onclick="unrock" android:layout_width="0px" android:layout_weight="2" android:layout_height="wrap_content" android:text="unrock" android:textsize="12sp" /> </LinearLayout> </LinearLayout> </FrameLayout> <strings.xml> <?xml version="1.0" encoding="utf-8" <resources> <string name="app_name">5pen </string> <string name="action_connect">connect</string> <string name="action_arduinocode">arduino code</string> <string name="action_back">rock 5pen(feat., ) </string> <string name="action_disconnect">disconnect</string> <string name="action_settings"> </string> </resources> - 37 -