Android/XMPP2010. 10. 28. 19:47


http://davanum.wordpress.com/2007/12/31/android-just-use-smack-api-for-xmpp/


Android – Just Use Smack API For XMPP

Filed under: Uncategorized — Davanum Srinivas @ 9:36 am

OUTDATED SAMPLE – Updated code is here:


http://davanum.wordpress.com/2008/12/29/updated-xmpp-client-for-android/

Using Smack XMPP API From Android

Once you get tired of the limitations of android’s built-in IMProvider and the corresponding API – IXmppSession and IXmppService, try the sample below. Inside the source/binary zip (bottom of this article) you will find a smack.jar that works with android. To build the jar yourself, You can download the Smack 3.0.4 sources from here and apply the patch here.

Here Is A Screen Shot Of The XMPP Settings Dialog.

1

Notes



  • For GTalk, use “gtalk.google.com” as host with port 5222. The service name is “gmail.com”

  • Don’t add “@gmail.com” in the user name, just the id will do

Here’s The Code For The Settings Dialog

01 package org.apache.android.xmpp;
02  
03 import android.app.Dialog;
04 import android.util.Log;
05 import android.view.View;
06 import android.widget.Button;
07 import android.widget.EditText;
08 import org.jivesoftware.smack.ConnectionConfiguration;
09 import org.jivesoftware.smack.XMPPConnection;
10 import org.jivesoftware.smack.XMPPException;
11 import org.jivesoftware.smack.packet.Presence;
12  
13 /**
14  * Gather the xmpp settings and create an XMPPConnection
15  */
16 public class SettingsDialog extends Dialog implements android.view.View.OnClickListener {
17     private XMPPClient xmppClient;
18  
19     public SettingsDialog(XMPPClient xmppClient) {
20         super(xmppClient);
21         this.xmppClient = xmppClient;
22     }
23  
24     protected void onStart() {
25         super.onStart();
26         setContentView(R.layout.settings);
27         getWindow().setFlags(44);
28         setTitle("XMPP Settings");
29         Button ok = (Button) findViewById(R.id.ok);
30         ok.setOnClickListener(this);
31     }
32  
33     public void onClick(View v) {
34         String host = getText(R.id.host);
35         String port = getText(R.id.port);
36         String service = getText(R.id.service);
37         String username = getText(R.id.userid);
38         String password = getText(R.id.password);
39  
40         // Create a connection
41         ConnectionConfiguration connConfig =
42                 new ConnectionConfiguration(host, Integer.parseInt(port), service);
43         XMPPConnection connection = new XMPPConnection(connConfig);
44  
45         try {
46             connection.connect();
47             Log.i("XMPPClient""[SettingsDialog] Connected to " + connection.getHost());
48         catch (XMPPException ex) {
49             Log.e("XMPPClient""[SettingsDialog] Failed to connect to " + connection.getHost());
50             xmppClient.setConnection(null);
51         }
52         try {
53             connection.login(username, password);
54             Log.i("XMPPClient""Logged in as " + connection.getUser());
55  
56             // Set the status to available
57             Presence presence = new Presence(Presence.Type.available);
58             connection.sendPacket(presence);
59             xmppClient.setConnection(connection);
60         catch (XMPPException ex) {
61             Log.e("XMPPClient""[SettingsDialog] Failed to log in as " + username);
62             xmppClient.setConnection(null);
63         }
64         dismiss();
65     }
66  
67     private String getText(int id) {
68         EditText widget = (EditText) this.findViewById(id);
69         return widget.getText().toString();
70     }
71 }

Here Is A Screen Shot Of The Main Window.

1

Notes



  • In the Recipient field, make sure you add the “@gmail.com”, not just the user id

Here’s The Code For The Main Activity

001 package org.apache.android.xmpp;
002  
003 import android.app.Activity;
004 import android.os.Bundle;
005 import android.os.Handler;
006 import android.util.Log;
007 import android.view.View;
008 import android.widget.ArrayAdapter;
009 import android.widget.Button;
010 import android.widget.EditText;
011 import android.widget.ListView;
012 import org.jivesoftware.smack.PacketListener;
013 import org.jivesoftware.smack.XMPPConnection;
014 import org.jivesoftware.smack.filter.MessageTypeFilter;
015 import org.jivesoftware.smack.filter.PacketFilter;
016 import org.jivesoftware.smack.packet.Message;
017 import org.jivesoftware.smack.packet.Packet;
018 import org.jivesoftware.smack.util.StringUtils;
019  
020 import java.util.ArrayList;
021  
022 public class XMPPClient extends Activity {
023  
024     private ArrayList<String> messages = new ArrayList();
025     private Handler mHandler = new Handler();
026     private SettingsDialog mDialog;
027     private EditText mRecipient;
028     private EditText mSendText;
029     private ListView mList;
030     private XMPPConnection connection;
031  
032     /**
033      * Called with the activity is first created.
034      */
035     @Override
036     public void onCreate(Bundle icicle) {
037         super.onCreate(icicle);
038         setContentView(R.layout.main);
039  
040         mRecipient = (EditText) this.findViewById(R.id.recipient);
041         mSendText = (EditText) this.findViewById(R.id.sendText);
042         mList = (ListView) this.findViewById(R.id.listMessages);
043         setListAdapter();
044  
045         // Dialog for getting the xmpp settings
046         mDialog = new SettingsDialog(this);
047  
048         // Set a listener to show the settings dialog
049         Button setup = (Button) this.findViewById(R.id.setup);
050         setup.setOnClickListener(new View.OnClickListener() {
051             public void onClick(View view) {
052                 mHandler.post(new Runnable() {
053                     public void run() {
054                         mDialog.show();
055                     }
056                 });
057             }
058         });
059  
060         // Set a listener to send a chat text message
061         Button send = (Button) this.findViewById(R.id.send);
062         send.setOnClickListener(new View.OnClickListener() {
063             public void onClick(View view) {
064                 String to = mRecipient.getText().toString();
065                 String text = mSendText.getText().toString();
066  
067                 Log.i("XMPPClient""Sending text [" + text + "] to [" + to + "]");
068                 Message msg = new Message(to, Message.Type.chat);
069                 msg.setBody(text);
070                 connection.sendPacket(msg);
071                 messages.add(connection.getUser() + ":");
072                 messages.add(text);
073                 setListAdapter();
074             }
075         });
076     }
077  
078     /**
079      * Called by Settings dialog when a connection is establised with the XMPP server
080      *
081      * @param connection
082      */
083     public void setConnection
084             (XMPPConnection
085                     connection) {
086         this.connection = connection;
087         if (connection != null) {
088             // Add a packet listener to get messages sent to us
089             PacketFilter filter = new MessageTypeFilter(Message.Type.chat);
090             connection.addPacketListener(new PacketListener() {
091                 public void processPacket(Packet packet) {
092                     Message message = (Message) packet;
093                     if (message.getBody() != null) {
094                         String fromName = StringUtils.parseBareAddress(message.getFrom());
095                         Log.i("XMPPClient""Got text [" + message.getBody() + "] from [" + fromName + "]");
096                         messages.add(fromName + ":");
097                         messages.add(message.getBody());
098                         // Add the incoming message to the list view
099                         mHandler.post(new Runnable() {
100                             public void run() {
101                                 setListAdapter();
102                             }
103                         });
104                     }
105                 }
106             }, filter);
107         }
108     }
109  
110     private void setListAdapter
111             () {
112         ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
113                 R.layout.multi_line_list_item,
114                 messages);
115         mList.setAdapter(adapter);
116     }
117 }

Download Source And APK From Here – XMPPClient.Zip


Posted by 삼스
Android/App개발2010. 10. 28. 14:18

코드 난독화툴을 안드로이드 프로젝트에 적용하는 포스트를 이미 올린바 있습니다.
이번에는 프로젝트에서 일부 클래스들만 묶어서 배포하고자 하는 경우 jar파일로 만드는 경우가 있을 것인데 이 경우 jar file하나만 proguard를 적용하는 방법에 대해 설명하겠습니다.

프로가드 gui툴을 이용하면 편하게 진행이 가능합니다.
프로가드 사용시 중요한 것이 옵션을 어떻게 지정할 것인가에 대한 것인데.. 그 중에도 -keep옵션이 아주 중요하다 할 것입니다.
안드로이드 소스코드 난독화를 위해서 레퍼런스로 사용할 만한 옵션을 아래 나열해 보았습니다.

# 각종 옵션들 : 설명은 생략~~ proguard site의 설명을 참조하시길...

-dontskipnonpubliclibraryclassmembers

-optimizationpasses 5

-dontusemixedcaseclassnames

-dontpreverify

-verbose


# keep option들.. 

# keep옵션이란 난독화시 난독화를 하지 않아야 하는 코드들을 미리 지정하는 것으로 

# 안드로이드 jar파일이나 프로젝트의 경우 아래의 keep옵션들이 필요할 것입니다.

-keep public class * extends android.app.Activity

-keep public class * extends android.app.Application

-keep public class * extends android.app.Service

-keep public class * extends android.content.BroadcastReceiver

-keep public class * extends android.content.ContentProvider

-keep public class com.android.vending.licensing.ILicensingService

-keepclasseswithmembers,allowshrinking class * {

    public <init>(android.content.Context,android.util.AttributeSet);

}

-keepclasseswithmembers,allowshrinking class * {

    public <init>(android.content.Context,android.util.AttributeSet,int);

}

# Also keep - Enumerations. Keep the special static methods that are required in

# enumeration classes.

-keepclassmembers enum  * {

    public static **[] values();

    public static ** valueOf(java.lang.String);

}

# Keep names - Native method names. Keep all native class/method names.

-keepclasseswithmembers,allowshrinking class * {

    native <methods>;

}


위 옵션들과 함께 입력파일과 출력파일을 지정하고 참조하고 있는 라이브러리까지 지정하는 스크립트 코드는 아래와 같습니다.


# 난독화를 진행할 입력 파일명

-injars myjar.jar

# 난독화를 거친 출력 파일명

-outjars out_myjar.jar


# 입력파일이 참조하는 라이브러리들...

# 안드로이드용 jar라면 android.jar를 반드시 포함해야 할것이다.

# 그 외에 혹시 추가로 참조하는 라이브러리가 있다면 추가해 주어야 한다.

-libraryjars /Users/yosamlee/Desktop/android-sdk-mac_x86/platforms/android-7/android.jar

-libraryjars /Users/yosamlee/_TOOL/workspace/MyJar/lib/referencelib.jar



위의 스크립트를 모두 모아서 확장자 *.pro로 저장한다.


proguard설치 폴더로 가서 bin폴더의 proguardgui를 실행한다. 아래와 같은 커맨드라인 명령을 콘솔에서 입력하면 됩니다.


java -jar ../lib/proguardgui.jar




위 화면에서 "Load configuration ..."을 선택 후 앞서 저장해 둔 스크립트파일을 오픈합니다


스크립트 파일이 성공적으로 열렸다면 Process tab에서 "Process!"버튼을 선택하면 난독화 과정을 거칩니다.


...

  Number of branch peephole optimizations:     0

  Number of simplified instructions:           0

  Number of removed instructions:              0

  Number of removed local variables:           0

  Number of removed exception blocks:          0

  Number of optimized local variable frames:   0

Shrinking...

Removing unused program classes and class elements...

  Original number of program classes: 26

  Final number of program classes:    26

Obfuscating...

Writing output...

Preparing output jar [/Users/yosamlee/_TOOL/workspace/MyJar/bin/out_myjar.jar]

  Copying resources from program jar [/Users/yosamlee/_TOOL/workspace/MyJar/bin/myjar.jar]

Processing completed successfully


정상적으로 과정이 진행되었다면 위와 같은 성공하였다는 메세지를 보게 될것입니다.


이제 out_myjar.jar파일을 리버스엔지니어링 해보길 바랍니다.

원하는 만큼 난독화가 진행되었는지 말이죠~!

만족할 만한 결과가 나왔기를 바랍니다.


ps) 이미 느끼신 분들도 계시겠지만 위 과정은 proguardgui버전에서 그대로 수행이 가능합니다. 저는 왜 수동으로 스크립트를 만들었냐면요.... 옵션들이 하도 많아서 헤깔려서요. GUI버전이 편하신 분들은 그걸 사용하셔도 됩니다.







Posted by 삼스
Android/App개발2010. 10. 20. 11:20

상용이던 개인용이던 안드로이드는 자바코드를 사용하기 때문에 dex tool과 jad tool등을 이용하면 decompile을 통한 reverse engineering이 가능하다.
이를 해결하기 위해 코드난독화툴을 이용하여 reverse를 어렵게 하는 방법을 사용하게 된다. proguard는 코딩을 어떻게 하느냐에 따라 난독이 아니라 불독(?)하게도 가능하다. 즉 전혀 해독이 불가하게 할수도 있다는 것이다.

proguard툴은 stand-alone형태로 사용해도 되나 android project에 포함시켜서 구동시키면 좀더 쉽게 사용이 가능해진다. 
이 포스트는 그 방법에 대해 설명한다.

요구사항
1. Android SDK version 7이상을 사용해야 함
  -> ANT 빌드규칙에 컴파일이전과 이후단계에서 일정한 작업을 추가할 수 있는 구조를 지원한다.
2. Proguard 설치

절차
커맨드라인에서 수행함.
1. 특정프로젝트에 대한 build.xml을 만듦
    android update project --path ./MyAndroidProject
  build.xml파일이 생성됨. 실제 빌드를 아래와 같이 수행.
    ant release
  빌드가 되고 서명되지 않은 앱이 생성됨. 이 후 서명툴을 이용하여 서명된 앱을 만들수 있슴.
2. 서명된 앱 빌드하기
  ant release명령으로 빌드하면 빌드과정에서 생성된 local.properties파일을 수정
    key.store=/Path/to/my/keystore/MyKeystore.ks
    key.alias=myalias
  ant release
3. 코드 난독화과정 
  add-proguard-release.xml, procfg.txt파일을 build.xml파일 위치에 복사
  local.properties에 proguard설치 경로 지정
    proguard.dir=/Directory/Proguard/proguard4.5.1/lib
  build.xml에(최상단에위치) 아래 내용 추가
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE project [
      <!ENTITY add-proguard-release SYSTEM "add-proguard-release.xml">
    ]>
  build.xml의 project tag안에 위에서 선언한 XML entity를 포함시킴
    <project name="MyProjectName" default="help">
    &add-proguard-release;
  위의 모든과정이 완료되었으면 빌드
    ant release

**  주의 사항  **
난독화 도구를 사용하는 경우 빌드후 앱이 정상적으로 동작하지 않을 수있다. 이는 난독화를 하지 않아야 하는 부분들까지도 난독화가 이루어져서 코드가 동작하지 못하는 경우가 발생하는 경우이다. 예를 들어 AndroidManifest나 class name, jni or reflection등을 통해 실제 메소드의 이름을 참조하고 있는 메소드들까지도 난독화를 통해서 작업이 이루어질 수 있다.
첨부된 procfg.txt에는 이런 룰을 지정할수가 있습니다. 이는 proguard 인자들중 keep인자 파라메터를 지정하는 방법에 따름인데 아래와 같은 명령을 추가하면 클래스이름을 찾지 못하는 문제는 방지 가능하다.

-keep public class * [my classname]

** 빌드중 obj directory가 생성되는데 여기에는 디버깅을 위한 다양한 출력파일들이 저장된다. 디버깅시 이용가능한다.
** mapping.txt 은 클래스가 어떤식으로 난독화 되었는지 기록한다.
** mac에서만 발생하는지 확인되지 않았으나 위 과정 진행중.. 아래와 같은 에러메세지가 나올수 있다.
add-proguard-release.xml:31: Expecting class path separator ':' before ';' in argument number 1
  이 경우 add-proguard-release.xml파일의 line35을 아래와 같이 수정하면 된다.
-libraryjars ${external.libs.dir};${libraryjarpath} -> -libraryjars ${external.libs.dir}:${libraryjarpath}


Posted by 삼스
HTML52010. 10. 18. 13:18


100 : Continue(계속) 
101 : Switching protocols (통신규약 전환)
200 : OK, 에러없이 전송 성공 
201 : Created, POST 명령 실행 및 성공 
202 : Accepted, 서버가 클라이언트 명령을 받음 
203 : Non-authoritative information, 서버가 클라이언트 요구중 일부만 전송
204 : No content, 클라언트 요구을 처리했으나 전송할 데이터가 없음
205 : Reset content (내용 원위치)
206 : Partial content (부분내용)
300 : Multiple choices, 최근에 옮겨진 데이터를 요청 
301 : Moved permanently, 요구한 데이터를 변경된 임시 URL에서 찾았음 
302 : Moved temporarily, 요구한 데이터가 변경된 URL에 있음을 명시
303 : See other, 요구한 데이터를 변경하지 않았기 때문에 문제가 있음 
304 : Not modified (수정안됨)
305 : Use proxy (프록시 사용)
400 : Bad request, 클라이언트의 잘못된 요청으로 처리할 수 없음 
401 : Unauthorized, 클라이언트의 인증 실패 
402 : Payment required, 예약됨 
403 : Forbidden, 접근이 거부된 문서를 요청함 
404 : Not found, 문서를 찾을 수 없음 (특히 이게 많죠.)
405 : Method not allowed, 리소스를 허용안함 
406 : Not acceptable, 허용할 수 없음 
407 : Proxy authentication required, 프록시 인증 필요 
408 : Request timeout, 요청시간이 지남 
409 : Conflict (충돌)
410 : Gone, 영구적으로 사용할 수 없음 
411 : Length required (필요조건 너무 김)
412 : Precondition failed, 전체조건 실패 
413 : Request entity too large, (본건 요구사항 너무 큼)
414 : Request-URI too long, URL이 너무 김 
415 : Unsupported media type (인증 안된 미디어 유형)
500 : Internal server error, 내부서버 오류(잘못된 스크립트 실행시) 
501 : Not implemented, 클라이언트에서 서버가 수행할 수 없는 행동을 요구함 
502 : Bad gateway, 서버의 과부하 상태 
503 : Service unavailable, 외부 서비스가 죽었거나 현재 멈춤 상태 
504 : Gateway timeout (접속장치 설정시간지남
505 : HTTP version not supported (http 버전 지원않됨)
Posted by 삼스
Android/App개발2010. 10. 14. 18:20

안드로이드는 사정에 따라 서비스를 죽이기도 하며 나중에 다시 살리기도 한다.
만일 항상 떠있는 서비스를 구현하고자 하는 경우에는 이런 일이 발생하는것에 대해 아주 당황할것이다.
이럴경우 서비스를 죽지 않도록 하고자 할것인데.
이런 경우 알람서비스를 이용하여 서비스가 죽으면 다시 살리는 방법이 있다.
많은 경우 이런 방식을 이용하는것으로 보인다.

PersistentService가 죽지 않아야 할 서비스이다. 아래 예제에서 보면 onCreate시 기존 알람이 있으면 제거하고 onDestroy시 알람을 기동한다. 
알람은 일정시간이 지나면 PendingIntent를 날리는 알람이며 이 인텐트를 받을 수 있는 BroadcastReceiver가 있게 된다. 여기서는 RestartService receiver가 해당 인텐트를 받아서 이 때 종료된 PersistentService를 재기동 시키는 역할을 한다.

PersistentService.java
class PersistentService extends Service {

  onCreate(..) {
    unregisterRestartAlram(); //이미 등록된 알람이 있으면 제거
  }

  onDestroy(..) {
    registerRestartAlram(); // 서비스가 죽을때 알람을 등록
  }
 
  // support persistent of Service 
  void registerRestartAlarm() {
    Log.d(TAG"registerRestartAlarm");
    Intent intent = new Intent(PersistentService.this, RestartService.class);
    intent.setAction(RestartService. ACTION_RESTART_PERSISTENTSERVICE);
    PendingIntent sender = PendingIntent.getBroadcast(PersistentService.this, 0, intent, 0);
    long firstTime = SystemClock.elapsedRealtime();
    firstTime += 10*1000; // 10초 후에 알람이벤트 발생
    AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
    am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, 10*1000, sender);
  }

  void unregisterRestartAlarm() {
    Log.d(TAG"unregisterRestartAlarm");
    Intent intent = new Intent(PersistentService.this, RestartService.class);
    intent.setAction(RestartService.ACTION_RESTART_PERSISTENTSERVICE);
    PendingIntent sender = PendingIntent.getBroadcast(PersistentService.this, 0, intent, 0);
    AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
    am.cancel(sender);
  }
}

RestartService.java
public class RestartService extends BroadcastReceiver {
  public static final String ACTION_RESTART_PERSISTENTSERVICE = "ACTION.Restart. PersistentService";

@Override
  public void onReceive(Context context, Intent intent) {
    Log.d("RestartService""RestartService called!@!@@@@@#$@$@#$@#$@#");
    if(intent.getAction().equals(ACTION_RESTART_PERSISTENTSERVICE)) {
      Intent i = new Intent(ctx, PushService.class);
      context.startService(i);
  }
}

manifest.xml
<application android:icon="@drawable/icon" android:label="@string/app_name">
<receiver android:name="RestartService" android:process=":remote"/>
Posted by 삼스
기타/Security2010. 10. 12. 17:10
기초적인 내용에 대해 잘 설명됨.

http://wiki.kldp.org/wiki.php/DocbookSgml/SSL-Certificates-HOWTO
Posted by 삼스
Android/XMPP2010. 10. 6. 17:17
smack project site -> http://www.igniterealtime.org/projects/smack/index.jsp
javadoc -> http://www.igniterealtime.org/builds/smack/docs/latest/javadoc/
android project talkmyphone -> http://code.google.com/p/talkmyphone/
Posted by 삼스
Android/XMPP2010. 10. 6. 16:55
http://www.igniterealtime.org/builds/smack/docs/latest/documentation/processing.html
Processing Incoming Packets 

수신되는 패킷을 처리하는데 두가지 방식을 지원한다.

  • org.jivesoftware.smack.PacketCollector -- 새로운 패킷이 올때까지 동기적으로 대기하는 클래스
  • org.jivesoftware.smack.PacketListener -- 수신되는 패킷을 비동기적으로 받는 인터페이스
패킷리스너는 이벤트스타일의 프로그래밍이다. 반면에 패킷콜렉터는 당신이 폴링으로 수집한 데이터를 큐잉하여 받게되며 그 동작은 블럭된다. 패킷리스너는 수신중에 언제든지 다른 작업이 가능하며 콜렉터는 원하는 패킷이 올때가지 대기할때 유용하다. 이 두가지는 모두 XMPPConnection의 인스턴스로부터 얻을수 있다.

org.jivesoftware.smack.filter.PacketFilter인터페이스는 패킷리스너와 패킷콜렉터가 전달받을킷을러주는 역할을 한다. org.jivesoftware.smack.filter패키지에 미리정의된 많은 사용가능한 필터들이 정의되어 있다.

아래 코드는 패킷리스너와 패킷콜렉터를 모두 사용하는 데모이다.

 // Create a packet filter to listen for new messages from a particular
// user. We use an AndFilter to combine two other filters.
PacketFilter filter = new AndFilter(new PacketTypeFilter(Message.class), 
        new FromContainsFilter("mary@jivesoftware.com"));
// Assume we've created an XMPPConnection name "connection".

// First, register a packet collector using the filter we created.
PacketCollector myCollector = connection.createPacketCollector(filter);
// Normally, you'd do something with the collector, like wait for new packets.

// Next, create a packet listener. We use an anonymous inner class for brevity.
PacketListener myListener = new PacketListener() {
        public void processPacket(Packet packet) {
            // Do something with the incoming packet here.
        }
    };
// Register the listener.
connection.addPacketListener(myListener, filter);



Standard Packet Filters

아래는 Smack에서 제공하는 패킷필터들의 셋이다. PacketFilter인터페이스로 새로운 필터를 정의할수도 있다. 디폴트셋은 아래와 같다.
  • PacketTypeFilter -- 클래스타입을 지정할 수 있다. 
  • PacketIDFilter -- 패킷 ID별로 지정할 수 있다.
  • ThreadFilter -- 메세지패킷의 스레드 ID별로 지정할 수 있다.
  • ToContainsFilter -- 받는 주소로 지정할 수 있다.
  • FromContainsFilter -- 보내는 주소로 지정할 수 있다.
  • PacketExtensionFilter -- 패킷의 확장부분을 지정할 수 있다.
  • AndFilter -- 논리적 AND 연산을 두개이상의 필터로 지정할 수 있도록 해준다.
  • OrFilter -- 논리적 OR 연산을 두개이상의 필터로 지정할 수 있도록 해준다.
  • NotFilter -- 논리적 NOT 연산을 두개이상의 필터로 지정할 수 있도록 해준다.

Posted by 삼스
Android/XMPP2010. 10. 6. 16:31
Smack은 opensource로 제공되는  XMPP library이다. 안드로이드에서 사용이 가능하다.
실시간으로 XMPP server와 통신이 가능하고 인스탄트메세징과 채팅이 가능하다

아래와 같이 지극히 단순한 코드로 단문메세지를 전송할 수 있다.
XMPPConnection connection = new XMPPConnection("jabber.org");
connection.connect();
connection.login("mtucker", "password");
Chat chat = connection.getChatManager().createChat("jsmith@jivesoftware.com", new MessageListener() {

    public void processMessage(Chat chat, Message message) {
        System.out.println("Received message: " + message);
    }
});
chat.sendMessage("Howdy!"); 

프로그래머에게 패킷레벨의 접근이 필요없으며 Chat, Roater같은 상위레벨의 클래스를 사용하여 프로그래밍이 가능하다
XMPP XML format이나 XML에 대해서도 알필요가 없다.


Posted by 삼스
Android/App개발2010. 9. 28. 19:54

안드로이드에서 Push notification을 구현하기 위한 방법으로 XMPP를 이용하는 방법과 MQTT를 이용하는 방법이 있다..
여기서는 MQTT를 이용하여 C2DM을 지원하지 않는 안드로이드 2.1이하 버전에서 PUSH notification을 지원하기 위한 방법에 대해 설명한다.

안드로이드 앱에서 Push notification을 지원하기 위한 방안은 3가지정도의 방안이 있다.
1. 폴링
  이게 진정 push일까?? 어쨌든 단말에서 주기적으로 서버에 가져갈 메세지가 있는지 확인하여 push event를 수신할 수 있다. 
  장점 : 구현이 쉽고 비용도 안든다.
  단정 : 실시간이 아니지 않은가... 이런 젝일~!, 이는 배터리소모까지 발생시킨다.. 끔찍하다.이에 대한 정보는 링크를 참조하자. https://labs.ericsson.com/apis/mobile-java-push/blog/save-device-battery-mobile-java-push
2. SMS
  안드로이드는 SMS message의 가로채기가 가능하다. 서버에서 특별한 SMS를 단말에 날리면 앱에서는 모든 SMS 메세지를 가로채서 서버에서 날린것인지 확인하고 Popup Message를 띄울 수 있을것이다.
  장점 : 구현이 쉽다. 완전한 실시간이 보장된다. 알려진 솔루션도 있다. Ericsson lab의 자료를 참조하라 https://labs.ericsson.com/apis/mobile-java-push/
  단점 : 비용이 발생한다.
3. 끊김없는 TCP/IP
  폰과 서버가 TCP/IP 연결을 유지한다. 그리고 주기적으로 keepalive메세지를 날린다. 서버는 이 연결을 통해 필요할경우 메세지를 보낸다.
  장점 : 완전한 실시간이 보장된다.
  단점 : 신뢰성을 보장하는 구현이 아주 까다롭다. 폰과 서버쪽 모두 구현하려면 이야기가 복잡해진다. 또 안드로이드는 low memory등의 상황에서 서비스가 종료될 수도 있다. 그러면 동작을 안할것이다. 또한 단말이 sleep에 들어가지 않아야 하므로 유저들은 배터리문제로 클레임을 걸수 있다.

1, 2의 방법은 중대한 단점이 있다. 3번째는 가능하기는 하다. 하지만 먼가 개운치는 않다.

구글링을 통해서 몇몇 개발자들의 TCP/IP방식의 몇가지 좋은 시도를 찾았다.
Josh guilfoyle은 AlarmManager에 기반하여  오랬동안 살아있는 connection을 어떻게 만들것인가에 대해 언급했다. 그는 백그라운드에서 동작하면서 그 연결을 만들어내는 멋진 샘플코드도 제공하였다. http://devtcg.blogspot.com/2009/01/push-services-implementing-persistent.html

Dave Rea는  Deacon project를 최근에 시작했다. Meteor server상에서 comet technology를 사용하여 안드로이드에서 push notification을 지원하는 3rd party library를 개발할 예정이다. 아주 초기 단계이다.  http://deacon.daverea.com/

Dale Lane는 IBM에서 개발한 MQTT protocol로 android에서 push notification을 지원하는것과 관련한 많은 자료를 만들었으며 아주 훌룡한 샘플코드도 제공한다. http://dalelane.co.uk/blog/?p=938

위의 훌룡한 시도들을 기반으로 예제를 만들었다. 이 는 Josh Guilfoyle의 TestKeepAlive project 와 Dale Lane의 MQTT를 이용한 것이다.

TestKeepAlive project의 문제점은 raw TCP connection을 만든다는 것이다. 이는 push를 관리하는 서버를 별도로 작성해야 한다는것을 의미한다. MQTT를 이용한 예제의 경우 서버작업을 위해 IBM의 MQTT broker를 이용한다. 

mqtt는 publish/subscribe messaging protocol로 가볍게 설계 되었다. 가볍게 설계 되었다는 것은 '저전력 소모'를 지원한다는 것이다. 이는 끊김없는 TCP/IP connection을 고려해야 하는 모바일환경에서 가장 이상적인 해결책이다. 다만 MQTT의 단점은 개인의 프라이버시 보장이 약하다는 것등 몇가지 단점이 있기는 하다.

KeepAliveService와 raw TCP/IP connection을 MQTT connection으로 변경하는 것이 아이디어의 핵심이다.

Architecture
예제에서는 서버에서 PHP를 사용하였다. 이는 Simple Asynchronous Messaging library(http://project-sam.awardspace.com/)를 사용하였다.

system_diagram

wmqtt.tar 는 IBM에서 제공하는 MQTT protocol의 간단한 drop-in implementation이다.  http://www-01.ibm.com/support/docview.wss?rs=171&uid=swg24006006에서 다운로드 가능하다. 

Really Small Message Broker(RSMB)는 간단한 MQTT broker로 마찬가지로 IBM에서 제공한다. http://www.alphaworks.ibm.com/tech/rsmb에서 다운가능하다. 1833포트가 디폴트로 동작한다. 위 아키텍쳐에서 서버로부터 메세지를 받아서 단말에 전송하는 역할을 한다. RSMB는 Mosquitto server(http://mosquitto.atchoo.org/)로 변경이 가능하다.
SAM은 MQTT와 다른 요소들을 모아놓은 PHP library이다. http://pecl.php.net/package/sam/download/0.2.0에서 다운가능하다.

send_mqtt.php는 POST를 통해 메세지를 받아서 SAM을 이용하여 broker에 메세지를 전달하는 역할을 한다.

Sample code and Demo
push-app
이 예제는 TextView하나와 두개의 Button이 있다. 폰에 설치 후 서비스를 시작한 후 http://tokudu.com/demo/android-push/  에 가서 deviceID를 입력하고 메세지를 입력하라. 그러고 난 후 "Send Push Message"를 누르면 폰에서 메세지를 받을 것이다. 
























MQTT는 사실 안드로이드에서 Push를 지원하기 위한 최적의 방법은 아니다. 하지만 잘 동작한다. MQTT의 가장 취약한 점은 broker가 동작하는 IP와 PORT정보를 누군가 알아낸다면 모든 Push message들을 가로챌수 있다는 것이다. 따라서 그런 정보를 encrypt하는것은 좋은 대안이 될것이다. 대안으로 당신만의 broker를 작성하여 MQTT에 인증을 추가하는것이 있을 수 있다.

이 예제는 더 테스트되어야 한다. 안정성은 보장못한다. 연결이 끊어지거나 예외상황들에 대한 처리가 더 개선되어야 한다. 





Posted by 삼스