반복적인작업이싫은안드로이드개발자에게 @geekbeast 진성주
발표자소개 진성주 ( @geekbeast ) Blog : http://softwaregeeks.org 안드로이드프로그래밍 : 제대로된안드로이드앱개발을위한진성주, 최종열, 백정현, 신중훈 ( 공저 )
http://www.hanb.co.kr/network/view.html?bi_id=981
Motivation
Motivation
Motivation 짜증나는안드로이드반복적인작업 1. UI 매핑 (findviewbyid) 2. 파라미터처리 (getintent().getextras() ) 3. 비동기처리 (Async) 4. REST 통신 ( Http )
Motivation 1. UI 매핑 TextView subject = (TextView) findviewbyid(r.id.subject); TextView writer = (TextView) findviewbyid(r.id.writer); TextView date = (TextView) findviewbyid(r.id.date); TextView hit = (TextView) findviewbyid(r.id.hit); @ViewById TextView subject; @ViewById TextView write; @ViewById TextView date @ViewById TextView hit;
Motivation 2. 파라미터처리 String id = intent.getstringextra("id"); String name = intent.getstringextra( name"); String nickname = intent.getstringextra( nickname"); Int sex = intent.getintextra( sex,0); Object object = intent.getextras().get("object"); @Extra( id") String id; @Extra( name") String name; @Extra( nickname") String nickname; @Extra( sex") int sex; @Extra( object") Object object;
Motivation 3. 비동기처리 (Async) @Background private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> { void protected backgroudjob() Long doinbackground(url... { urls) { MovieContents int count = moviecontents urls.length; = daummovieservice.getmoviecontents("love"); String long result totalsize = moviecontents.getquery(); = 0; setdata(result); for (int i = 0; i < count; i++) { } totalsize += Downloader.downloadFile(urls[i]); publishprogress((int) ((i / (float) count) * 100)); @UiThread } void setdata(string return totalsize; data) { textview.settext(data); } } protected void onprogressupdate(integer... progress) {
Motivation 4. REST 통신 private @Rest InputStream download(string url) { public HttpURLConnection interface DaumMovieService con = null; { URL @Get("http://apis.daum.net/contents/movie?apikey=DAUM_CONTENTS_DEMO_APIKEY&outp url; ut=xml&q={query}") InputStream is=null; public MovieContents getmoviecontents(string query); try { } url = new URL(url); con = (HttpURLConnection) url.openconnection(); con.setreadtimeout(10000 /* milliseconds */); con.setconnecttimeout(15000 /* milliseconds */); con.setrequestmethod("get"); con.setdoinput(true);
목표 반복적인코드를줄일수있는 오픈소스 (RoboGuice, AndroidAnnotations) 써보세요 ~
Contents 목차 1. Reflection, Annotation 2. 오픈소스 1. Dependency Injection Framework : RoboGuice 2. Annotation Process Tool Library: AndroidAnnoations 3. 오픈소스를넘어 4. 정리
01 Reflection, Annotation 발표자료 http://softwaregeeks.org
Contents 목차 1. Reflection, Annotation 2. 오픈소스 1. Dependency Injection Framework : RoboGuice 2. Annotation Process Tool Library: AndroidAnnoations 3. 오픈소스를넘어 4. 정리
01 Reflection, Annotation Reflection 1. ( 거울등에비친 ) 상 2. ( 빛 열 소리등의 ) 반사, 반향 3. ( 상태 속성등의 ) 반영 클래스모습을자신이볼수있고, 수정할수도있는기술
01 Reflection, Annotation 이클립스자동완성 (Ctrl+Space)
01 Reflection, Annotation JDBC Programming Class.forName("oracle.jdbc.driver.OracleDriver"); Connection conn = DriverManager.getConnection Statement stmt = conn.createstatement(); ResultSet rs = stmt.executequery(
01 Reflection, Annotation 웹어플리케이션 web.xml <servlet> <servlet-name>action</servlet-name> <servlet-class> org.softwaregeeks.servlet </servlet-class> </ servlet>
01 Reflection, Annotation 스프링프레임워크 ApplicationContext.xml <bean id="messagedao" class="org.softwaregeeks.nateon.messagedao"/> <bean id="nateon" class="org.softwaregeeks.nateon.nateon">
01 Reflection, Annotation Java Complier javac *.java *.class
01 Reflection, Annotation *.class Java Virtual Machine
01 Reflection, Annotation JVM Internal - http://helloworld.naver.com/index.php?vid=helloworld&document_srl=1230
01 Reflection, Annotation java.lang.relect.*
01 Reflection, Annotation 클래스 public class Person { private String name; private int age; private Sex sex; // Setter, Getter
01 Reflection, Annotation 클래스필드가져오기 Class clz = Person.class; Field[] fields = clz.getdeclaredfields(); for(field field : fields) { System.out.println(field.getName()); }
01 Reflection, Annotation 클래스메소드가져오기 Class clz = Person.class; Method[] methods = clz.getdeclaredmethods(); for(method method : methods) { System.out.println(method.getName()); }
01 Reflection, Annotation
01 Reflection, Annotation Annotation 1. 주석 ( 을달기 )
01 Reflection, Annotation 만드는법 @Target @Retention public @interface 이름 { String value(); }
01 Reflection, Annotation ElementType package java.lang.annotation; public enum ElementType { TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE, ANNOTATION_TYPE, PACKAGE } // Class, interface, or enum (but not annotation) // Field (including enumerated values) // Method (does not include constructors) // Method parameter // Constructor // Local variable or catch clause // Annotation Types (meta-annotations) // Java package
01 Reflection, Annotation Retention package java.lang.annotation; public enum RetentionPolicy { SOURCE, CLASS, RUNTIME } // Annotation is discarded by the compiler // Annotation is stored in the class file, but ignored by the VM // Annotation is stored in the class file and read by the VM
01 Reflection, Annotation 어노테이션만들기 @Retention(RetentionPolicy.RUNTIME) public @interface Description { String value(); }
01 Reflection, Annotation 어노테이션만들기 public class Person { @Description(value=" 이름이예요.") private String name; @Description(value=" 나이예요.") private int age; @Description(value=" 성별입니다.") private Sex sex;
01 Reflection, Annotation 어노테이션가져오기 Class clz = Person.class; for(field field : fields) { Annotation[] annotations = field.getdeclaredannotations(); for(annotation annotation : annotations) { if( annotation instanceof Description ) { Description description = (Description)annotation; System.out.println(description.value()); } } }
01 Reflection, Annotation
01 Reflection, Annotation @ViewById TextView subject; @ViewById TextView write; @ViewById TextView date @ViewById TextView hit;
01 Reflection, Annotation 스크린캐스트자료제공 http://goo.gl/egaau
Contents 목차 1. Reflection, Annotation 2. 오픈소스 1. Dependency Injection Framework : RoboGuice 2. Annotation Process Tool Library: AndroidAnnoations 3. 오픈소스를넘어 4. 정리
Contents 목차 1. Reflection, Annotation 2. 오픈소스 1. Dependency Injection Framework : RoboGuice 2. Annotation Process Tool Library: AndroidAnnoations 3. 오픈소스를넘어 4. 정리
02 오픈소스 - Dependency Injection Framework : RoboGuice Google Guice on Android Project!! http://code.google.com/p/roboguice/
02 오픈소스 - Dependency Injection Framework : RoboGuice RoboGuice Google Guice Google Guice on Android Project!! a lightweight dependency injection framework for Java 5 and above, brought to you by Google.
02 오픈소스 - Dependency Injection Framework : RoboGuice
02 오픈소스 - Dependency Injection Framework : RoboGuice class RoboWay extends RoboActivity { class AndroidWay extends Activity { TextView name; @InjectView(R.id.name) ImageView thumbnail; @InjectView(R.id.thumbnail) LocationManager loc; @InjectResource(R.drawable.icon) Drawable icon; @InjectResource(R.string.app_name) String myname; @Inject TextView name; ImageView thumbnail; Drawable icon; String myname; LocationManager loc; public void oncreate(bundle savedinstancestate) { } super.oncreate(savedinstancestate); public void oncreate(bundle savedinstancestate) { } setcontentview(r.layout.main); super.oncreate(savedinstancestate); name = (TextView) findviewbyid(r.id.name); setcontentview(r.layout.main); thumbnail = (ImageView) findviewbyid(r.id.thumbnail); name.settext( "Hello, " + myname ); loc = (LocationManager) getsystemservice(activity.location_service); icon = getresources().getdrawable(r.drawable.icon);
02 오픈소스 - Dependency Injection Framework : RoboGuice RoboGuice 기능 기본클래스 Inject 가능 로깅기능 릴리즈시자동으로디버그메시지제거앱정보 ( 앱이름, 로그메세지라인, TimeStamp, Thread, 다른유용한정보 ) 들이자동으로로깅됨
02 오픈소스 - Dependency Injection Framework : RoboGuice RoboGuice 기능 RoboAsyncTask 기본적인 AsyncTask 를확장하고 onexception(), onfinally() 통해서에러처리가능 Event handlers OnActivityResultEvent, OnConfigurationChangedEvent, OnContentChangedEvent, OnContentViewAvailableEvent OnCreateEvent, OnDestroyEvent 등많은이벤트를받을수있도록어노테이션지원 RoboGuice 2.0 beta3 에서는더많은기능이추가됨 Support for Fragments RoboApplication 에서모듈추가를하지않고, res/values/roboguice.xml 외부파일로모듈을추가할수있음 Guice 3.0 and Maven 2.0 and 3.0 support
02 오픈소스 - Dependency Injection Framework : RoboGuice Custom Class Inject
02 오픈소스 - Dependency Injection Framework : RoboGuice Application RoboApplication addapplicationmodules AbstractModule AbstractModule AbstractModule MyModule MyModule MyModule configure configure configure bind(customclass.class) bind(customclass.class) bind(customclass.class)
02 오픈소스 - Dependency Injection Framework : RoboGuice RoboGuice 2.0 beta3 에서는 XML 파일을이용한 Custom Class Injection 가능
02 오픈소스 - Dependency Injection Framework : RoboGuice Reverse Engineering http://goo.gl/h4x4h
02 오픈소스 - Dependency Injection Framework : RoboGuice
02 오픈소스 - Dependency Injection Framework : RoboGuice
02 오픈소스 - Dependency Injection Framework : RoboGuice
02 오픈소스 - Dependency Injection Framework : RoboGuice RoboGuice 장단점 장점 1. Dependency Injection Framework 인 Google Guice를 Android 에서사용할수있다. 2. 다양한어노테이션과기본클래스들을사용하여코드를줄일수있음 단점 1. 라이브러리용량문제 (guice-2.0-no_aop + roboguice1.1.2 = 533KB) Making Your App Smaller - http://code.google.com/p/roboguice/wiki/proguard 2. 런타임리플렉션사용으로인한성능저하
Contents 목차 1. Reflection, Annotation 2. 오픈소스 1. Dependency Injection Framework : RoboGuice 2. Annotation Process Tool Library: AndroidAnnoations 3. 오픈소스를넘어 4. 정리
02 오픈소스 - Annotation Process Tool Library : AndroidAnnoations androidannotations https://github.com/excilys/androidannotations
02 오픈소스 - Annotation Process Tool Library : AndroidAnnoations @EActivity(R.layout.translate) public class TranslateActivity extends Activity { @ViewById EditText textinput; @AnimationRes Animation facein; @Click void dotranslate() { translateinbackground(textinput.gettext().tostring()); } @Background void translateinbackground(string texttotranslate) { String translatedtext = callgoogletranslate(texttotranslate); showresult(translatedtext); }
02 오픈소스 - Annotation Process Tool Library : AndroidAnnoations RoboGuice 와다르게 AndroidAnnoations 런타임이아니라컴파일시, 모든소스를자동으로생성함.
02 오픈소스 - Annotation Process Tool Library : AndroidAnnoations // DO NOT EDIT THIS FILE, IT HAS BEEN GENERATED USING AndroidAnnotations. public final class TranslateActivity_ extends TranslateActivity { @Override public void oncreate(bundle savedinstancestate) { beforecreate_(savedinstancestate); super.oncreate(savedinstancestate); setcontentview(layout.main); } private void beforecreate_(bundle savedinstancestate) { } private void aftersetcontentview_() { textview = ((TextView) findviewbyid(id.textview));
02 오픈소스 - Annotation Process Tool Library : AndroidAnnoations APT(Annotation Process Tool) JSR 269(JSR 269 Pluggable Annotation Processing API) Annotation을사용하여소스컴파일전에사용자가원한는작업을할수있도록하는규격 Source Code Annotation Process Tool Compiler Class file
02 오픈소스 - Annotation Process Tool Library : AndroidAnnoations AndroidAnnotations ClassA.java 를 Annotation Process Tool API 를통해 ClassA_.java 파일을생성하여처리한다. 1. AndroidManifest.xml 해당액티비티명 + _ 추가 2. Intent 를사용시에작성한액티비티명 + _ 를추가하여야 함
02 오픈소스 - Annotation Process Tool Library : AndroidAnnoations AndroidAnnoations 기능 Cookbook - https://github.com/excilys/androidannotations/wiki/cookbook Activities : @EActivity Application : @App View : @ViewById, @AfterViews Resource : @StringRes, @ColorRes, @AnimationRes @BooleanRes @ColorStateListRes @DimensionRes @DimensionPixelOffsetRes @DimensionPixelSizeRes @DrawableRes @IntArrayRes @IntegerRes @LayoutRes @MovieRes @TextRes @TextArrayRes @StringArrayRes
02 오픈소스 - Annotation Process Tool Library : AndroidAnnoations AndroidAnnoations 기능 Extras : @Extra SystemServices : @SystemService Injecting html : @HtmlRes, @FromHtml WorkingWithThreads : @Background, @UiThread, @UiThreadDelayed HandlingEvents : @Click, @LongClick, @Touch, @ItemClick, @LongItemClick, @ItemSelect Handling options menu : @OptionsMenu, @OptionsItem REST API(With SpringAndroid) : @Rest, @RestService, @Get, @Put, @Post, @Delete, @Options, @Head, @ Accept Trace Method Execution : @Trace
02 오픈소스 - Annotation Process Tool Library : AndroidAnnoations Click Event, Background
02 오픈소스 - Annotation Process Tool Library : AndroidAnnoations REST API AndroidAnnoations + SpringAndroid
02 오픈소스 - Annotation Process Tool Library : AndroidAnnoations AndroidAnnotations Spring Android (core, RestTemplate) Jackson(JSON), Simpleframework(XML) Mashaller
02 오픈소스 - Annotation Process Tool Library : AndroidAnnoations Spring Android HttpHeaders requestheaders = new HttpHeaders(); requestheaders.setaccept(collections.singletonlist(new MediaType("application","json"))); HttpEntity<?> requestentity = new HttpEntity<Object>(requestHeaders); String url = "http://mypretendservice.com/events"; RestTemplate resttemplate = new RestTemplate(); ResponseEntity<Event[]> responseentity = resttemplate.exchange(url, HttpMethod.GET, requestentity, Event[].class); Event[] events = responseentity.getbody();
02 오픈소스 - Annotation Process Tool Library : AndroidAnnoations AndroidAnnotations REST API @Rest public interface DaumMovieService { @Get("http://apis.daum.net/contents/movie?apikey=DAU M_CONTENTS_DEMO_APIKEY&output=xml&q={query}") public MovieContents getmoviecontents(string query); } // 실제액티비티나서비스에서사용시, @RestService DaumMovieService daummovieservice;
02 오픈소스 - Annotation Process Tool Library : AndroidAnnoations
02 오픈소스 - Annotation Process Tool Library : AndroidAnnoations AndroidAnnoations 장단점 장점 1. Annotation Process Tool 이용하여컴파일시에모든코드가생성되어성능상이점이있다. ( 런타임시리플렉션을사용하지않음 ) 2. 다양한커스텀어노테이션이제공됨 단점 1. 인텐트를사용시 _ 문자열처리
02 오픈소스 - RoboGuice + AndroidAnnotations RoboGuice AndroidAnnotations 실제두프로젝트는유사한점이있는데 AndroidAnnotations 커미터가 RoboGuice 컨트리뷰터로참여하고있음 두프로젝트는경쟁관계라기보다 상호보완적인관계
02 오픈소스 - RoboGuice + AndroidAnnotations RoboGuice + AndroidAnnotations https://github.com/excilys/androidannotations/wiki/roboguiceintegration
Motivation 짜증나는안드로이드반복적인작업 1. UI 매핑 (findviewbyid) 2. 파라미터처리 (getintent().getextras().) 3. 비동기처리 (Async) 4. REST 통신 ( Http )
Contents 목차 1. Reflection, Annotation 2. 오픈소스 1. Dependency Injection Framework : RoboGuice 2. Annotation Process Tool Library: AndroidAnnoations 3. 오픈소스를넘어 4. 정리
03 오픈소스를넘어 UI Mapping private TextView hello1; private TextView hello2; private TextView hello3; private TextView hello4; private TextView hello5; @Override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.main); hello1 = (TextView)findViewById(R.string.hello1); hello2 = (TextView)findViewById(R.string.hello2); hello3 = (TextView)findViewById(R.string.hello3); hello4 = (TextView)findViewById(R.string.hello4); hello5 = (TextView)findViewById(R.string.hello5);
03 오픈소스를넘어 직접내가한번만들어보자. @ViewById TextView subject; @ViewById TextView write; @ViewById TextView date @ViewById TextView hit;
03 오픈소스를넘어 UI Mapping 반복적인작업줄이기 ; Reflection 사용하기 1. Reflection으로액티비티에선언된필드리스트가져오기 2. 필드명으로리소스 identifier 값 (R.id.xxxxxx) 을가져오기 3. findviewbyid(r.id.xxxxx) 으로 View 가져오기 4. Reflection으로필드에 View Injection
03 오픈소스를넘어 public static void mappingviews(object object) { Activity activity = (Activity)object; Field[] fields = activity.getclass().getdeclaredfields(); for (Field field : fields) { String identifierstring = field.getname(); int identifier = activity.getresources().getidentifier(identifierstring, "id", activity.getpackagename()); if( identifier == 0 ) {continue; } View findedview = activity.findviewbyid(identifier); if( findedview == null ) { continue; } if( findedview.getclass() == field.gettype() ) { try { field.setaccessible(true); field.set(object, findedview);
03 오픈소스를넘어 UI Mapping 반복적인작업줄이기 ; Reflection + Custom Annotation 사용하기 1. Custom Annotation 만들기 ( InjectView ) 2. 필드에서어노테이션가져와서처리 3. BaseActivity 만들어상속구조로간소화하기
03 오픈소스를넘어 1. 어노테이션만들기 @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface InjectView { int id() default 0; }
03 오픈소스를넘어 2. 어노테이션값가져오기 InjectView injectview = field.getannotation(injectview.class); if( injectview == null ) continue; int identifier = injectview.id();
Contents 목차 1. Reflection, Annotation 2. 오픈소스 1. Dependency Injection Framework : RoboGuice 2. Annotation Process Tool Library: AndroidAnnoations 3. 오픈소스를넘어 4. 정리
Intent 목표 반복적인코드를줄일수있는자바의리플렉션, 어노테이션을이해하고오픈소스 (RoboGuice, AndroidAnnotations) 를활용하여작업능률을높이자!!!
Q & A 질의응답 Twitter : http://twitter.com/geekbeast Mail : moleskine7@gmail.com Blog : http://softwaregeeks.org
Thank you! :D
- 페이지번호 -