Node.js에서는 데이터 형식으로 JSON을 사용한다. 자바스크립트 객체를 직렬화하여 클라이언트에서 서버로 전달하거나 프로세스에서 프로세스로 전달, 스트림에서 스트림으로 전달, 데이터베이스에 저장시에도 사용된다. 자바스크립트 객체를 직렬화하는 일에 XML보다 JSON이 사용되는 이유는 다음과 같다.

– JSON이 XML보다 객체를 직렬화거나 역직렬화 할때 필요한 문자수가 적다.
– JSON을 직렬화하거나 역직렬화하는 것이 XML로 똑같은 작업을 하는것보다 빠른다.

 

[1] JSON을 자바스크립트 객체로 변환

JSON.parse(string)을 사용하여 자바스크립트 객체로 변환한다.

var accountStr = ‘{ “name”:”John”, “members”:[“Sam”, “Smith”], “number”:12345, “location”:”Seoul”}’;
var accountObj = JSON.parse(accountStr);
console.log(accountObj.name);
console.log(accountObj.members);

 

[2] 자바스크립트 객체를 JSON으로 변환

Node.js는 자바스크립트 객체를 JSON포맷으로 변환할 수 있다. 이를 이용해 문자열 형태 자료를 파일이나 데이터 베이스에 저장하거나 HTTP연결을 사용해 전송, 스트림이나 버퍼에 쓰기 등을 할수 있다. JSON.stringify(object)함수를 사용해 자바스크립트 객체를 파싱해 JSON 문자열을 만들 수 있다.

var accountObj = {
“name”:”John”,
“members”:[“Sam”, “Smith”],
“number”:12345,
“location”:”Seoul”
}
var accountStr = JSON.stringify(accountObj);
console.log(accountStr);


출처 : http://aljjabaegi.tistory.com/40

'Programming > Node.JS' 카테고리의 다른 글

Event개념 이해  (0) 2016.09.03
기본 내장 모듈  (0) 2016.09.03
전역 객체에 대하여  (0) 2016.09.03
node.js 특징  (0) 2016.09.03
Nodejs로 serial통신하기  (0) 2016.08.25
Android는 Java로 되어 있어 Java에서 제공하는 기능을 사용하여 Thread를 구현할 수 있습니다. 그러나, 안드로이드 화면의 각 요소(View)에 정보를 표시한다든지 하는 UI와 관련된 작업을 하는 경우에는 여러가지 제약 사항이 따릅니다.

Google에서는 AsyncTask라는 것을 제공하여 Android에서 UI 작업과 관련된 Thread의 구현을 손쉽게 할 수 있도록 지원 합니다
 
 

  Thread with AsyncTask

UI Thread를 구현하기 위해서는 해당 Thread가 Activity에서 구현이 되어야 하며, 주고 받는 인자들의 타입이 일치 하여야 합니다. 아래 설명에서는 서로 일치해야 하는 인자들의 경우에는 동일한 색으로 표시를 해서 구분 합니다.

* AsyncTask 호출 구현
private Activity activity = null;

activity = this;
(new theAsyncThread()).execute(para1para2para3);


*AsyncTask 구현
private class theAsyncThread extends AsyncTask<StringStringString> {
    //--- Thread를 시작하기 전에 호출되는 함수
    protected void onPreExecute() {
        if ((activity != null) && (activity.isFinishing() == false)) {
            Toast.makeText(activity, "Before thread", Toast.LENGTH_SHORT).show();
        }
        super.onPreExecute();
    }

    //--- Thread의 주요 작업을 처리 하는 함수
    //--- Thread를 실행하기 위해 excute(~)에서 전달한 값을 인자로 받습니다.
    protected String doInBackground(String... arg) {
        int argCnt = 0;
        
        argCnt = arg.length;
        if (argCnt != 3) {
            return "Error";
        }
        
        //--- onProgressUpdate(~) 실행하기 위해서는 아래 함수를 호출 합니다.
        publishProgress("Thread processing.");
        return "OK";
    }

    //--- doInBackground(~)에서 호출되어 주로 UI 관련 작업을 하는 함수
    protected void onProgressUpdate(String... progress) {
        if ((activity != null) && (activity.isFinishing() == false)) {
            Toast.makeText(activity, progress[0], Toast.LENGTH_SHORT).show();
        }
    }

    //--- Thread를 처리한 후에 호출되는 함수
    //--- doInBackground(~)의 리턴값을 인자로 받습니다.
    protected void onPostExecute(String result) {
        if ((activity != null) && (activity.isFinishing() == false)) {
            Toast.makeText(activity, "After thread", Toast.LENGTH_SHORT).show();
        }
        super.onPostExecute(result);
    }

    //--- AsyncTask.cancel(true) 호출시 실행되어 thread를 취소 합니다.
    protected void onCancelled() {
        super.onCancelled();
    }      
}    


출처 : http://cuteelfluv.cafe24.com/xe/index.php?mid=etc&page=4&document_srl=5803

'Programming > Android' 카테고리의 다른 글

notification 고정시키기  (1) 2016.08.28
JSONobject 과 JSONarray  (0) 2016.08.27
AccessibilityService  (0) 2016.08.26
Intent와 Intent Filter  (0) 2016.08.26
어플 패키지명  (0) 2016.08.25
화면이 변경되었을때 해당 package가 아니면 /*실행*/부분을 실행하는 예제


1
2
3
4
5
6
7
8
9
10
11
12
13
public class WindowDetecter extends AccessibilityService 
{
 
 @Override
 public void onAccessibilityEvent(AccessibilityEvent event) {
  if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED){
   Log.d(TAG, "Package is " + event.getPackageName());
   if!"패키지명".equals(event.getPackageName())){
      /*실행*/
   }
  }
 }
}
cs


AccessibilityService.class란, 접근성에 관련된 클래스이다.

TYPE_WINDOW_STATE_CHANGED

Added in API level 4
int TYPE_WINDOW_STATE_CHANGED

Represents the event of opening a PopupWindowMenuDialog, etc.

팝업윈도우나, 메뉴, 다이얼로그같이 현재 열려있는 이벤트에 대한 상수

Constant Value: 32 (0x00000020)


getEventType

Added in API level 4
int getEventType ()

Gets the event type.

이벤트 타입을 얻는다.

Returns
intThe event type.


출처 : https://developer.android.com/reference/android/view/accessibility/AccessibilityEvent.html

'Programming > Android' 카테고리의 다른 글

JSONobject 과 JSONarray  (0) 2016.08.27
AsyncTask  (0) 2016.08.26
Intent와 Intent Filter  (0) 2016.08.26
어플 패키지명  (0) 2016.08.25
ProgressDialog 와 Toast  (0) 2016.08.25

인텐트


Intent의 첫번째 매개변수는 호출하는 액티비티를 나타내고, 두번째 매개변수에는 호출할 액티비티를 나타냅니다.

  그리고 Intent하는 두 액티비티는 모두 manifest에 등록되어 있어야한다!!!!

1
2
3
 Intent intent = new Intent(this, MainActivity.class);
 startActivity(intent);
 finish();
cs



인텐트(Intent)는 컴포넌트에 액션, 데이터 등을 전달하는 메시지 객체이다. 인텐트 객체의 구성 요소는 다음과 같다.

 

Action (액션): 수행할 액션 이름(ACTION_DIAL)

Data (데이터): 수행할 데이터의 URI(tel:)

Category (카테고리): 수행할 액션에 대한 추가적인 정보

Type (타입): 수행할 인텐트 데이터의 명시적인 타입(MIME 타입) (video/mpeg)

Component name (컴포넌트 이름): 대상 컴포넌트의 완전한 클래스 이름

Extras (추가 정보): 인텐트를 다루는 컴포넌트에 추가적으로 전달할 한 쌍의 키 /

 

컴포넌트 활성화 시점

컴포넌트

활성화 시점

Activity

인텐트에 의해 활성화

Service

인텐트에 의해 활성화

Broadcast Receiver

인텐트에 의해 활성화

Content provider

ContentResolver에 의해 활성화

 

컴포넌트 활성화

컴포넌트

활성화

Activity

Context.startActivity()

Activity.startActivityForResult()에 인텐트 객체를 전달해서 활성화

Service

Context.startService()에 인텐트 객체를 전달해서 활성화 
안드로이드는 인텐트 객체를 ServiceonStart() 메소드에 전달

Broadcast Receiver

Context.sendBroadcast()

Context.sendOrderedBroadcast()

Context.sendStickyBroadcast()에 인텐트 객체를 전달해서 활성화



인텐트 필터

인텐트 필터(Intent Filter)는 특정 인텐트를 받을지 말지를 정의하는 역할을 수행하며, 이를 통해 컴포넌트의 특징이 정해진다. 예를 들어, 인텐트 필터에 android.intent.action.MAIN을 선언하고 다음에 android.intent.category.HOME을 선언하면, 해당 컴포넌트는 홈 애플리케이션이 되어 디바이스가 시작될 때 자동으로 시작될 수 있는 애플리케이션이 된다. 인텐트 필터를 구성하는 요소는 인텐트에 작성할 수 있는 요소들과 동일하다.

- 앱 컴포넌트는 인텐트 필터를 가질 수 있고, 안드로이드는 인텐트 필터를 이용하여 어떤 앱 컴포넌트에 암시적 인텐트를 전달할지를 결정.


- 명시적 인텐트에는 클래스 이름이 설정되어 있어 무엇을 실행할지가 명확함.

-  - 묵시적 인텐트는 클래스 이름 대신 액션 이름이 설정됨.

         (액션 이름만으로는 어떤 앱 컴포넌트를 실행할지가 명확하지 않다.)

 


새로운 액티비티가 뜨면, HOME화면으로 이동하는 예제와 설명


1
2
3
4
5
6
7
8
9
10
 private void fobidden_activity() {
  Intent intent = new Intent();
  intent.setAction("android.intent.action.MAIN");
  intent.addCategory("android.intent.category.HOME");
  intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS 
   | Intent.FLAG_ACTIVITY_FORWARD_RESULT
      | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP
      | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
  startActivity(intent);
 }
cs

setAction

Added in API level 1
Intent setAction (String action)

Set the general action to be performed.

Parameters
actionString: An action name, such as ACTION_VIEW. Application-specific actions should be prefixed with the vendor's package name.
Returns
IntentReturns the same Intent object, for chaining multiple calls into a single statement.


ACTION_MAIN

Added in API level 1
String ACTION_MAIN

Activity Action: Start as a main entry point, does not expect to receive data.

Input: nothing

Output: nothing

Constant Value: "android.intent.action.MAIN"



addCategory

Added in API level 1
Intent addCategory (String category)

Add a new category to the intent. Categories provide additional detail about the action the intent performs. When resolving an intent, only activities that provide all of the requested categories will be used.

Parameters
categoryString: The desired category. This can be either one of the predefined Intent categories, or a custom category in your own namespace.
Returns
IntentReturns the same Intent object, for chaining multiple calls into a single statement.


addFlags

Added in API level 1
Intent addFlags (int flags)

Add additional flags to the intent (or with existing flags value).

Parameters
flagsint: The new flags to set.
Returns
IntentReturns the same Intent object, for chaining multiple calls into a single statement.

CATEGORY_HOME

Added in API level 1
String CATEGORY_HOME

This is the home activity, that is the first activity that is displayed when the device boots.

Constant Value: "android.intent.category.HOME"



intFLAG_ACTIVITY_EXCLUDE_FROM_RECENTS

If set, the new activity is not kept in the list of recently launched activities.

intFLAG_ACTIVITY_FORWARD_RESULT

If set and this intent is being used to launch a new activity from an existing one, then the reply target of the existing activity will be transfered to the new activity.

intFLAG_ACTIVITY_NEW_TASK

If set, this activity will become the start of a new task on this history stack.

intFLAG_ACTIVITY_PREVIOUS_IS_TOP

If set and this intent is being used to launch a new activity from an existing one, the current activity will not be counted as the top activity for deciding whether the new intent should be delivered to the top instead of starting a new on

intFLAG_ACTIVITY_RESET_TASK_IF_NEEDED

If set, and this activity is either being started in a new task or bringing to the top an existing task, then it will be launched as the front door of the task.


출처 : https://developer.android.com/reference/android/content

'Programming > Android' 카테고리의 다른 글

AsyncTask  (0) 2016.08.26
AccessibilityService  (0) 2016.08.26
어플 패키지명  (0) 2016.08.25
ProgressDialog 와 Toast  (0) 2016.08.25
HttpURLConnection  (0) 2016.08.25

kakao 패키지명 - com.kakao.talk

카메라 패키지명 - com.android.camera

갤러리 패키지명 -  com.android.gallery

'Programming > Android' 카테고리의 다른 글

AccessibilityService  (0) 2016.08.26
Intent와 Intent Filter  (0) 2016.08.26
ProgressDialog 와 Toast  (0) 2016.08.25
HttpURLConnection  (0) 2016.08.25
SharedPreferences  (1) 2016.08.24

1. ProgressDialog

setMessage로 세팅하고,

show로 보여주고 dismiss로 안보여주고...


1
2
3
4
5
6
7
8
9
10
static ProgressDialog dialog;
 
dialog = new ProgressDialog(this);
        dialog.setMessage(string);
        dialog.show();
    }
)
 
dialog.dismiss();
   
cs


2. Toast

Toast는 첫번째 매개변수에 Context를 넣어야하는데 GetApplicationContext()를 사용하여 해당 Context를 받아 오도록하자

Toast.LENGTH_SHORT와 LONG가 있는데 취향에 맞춰 골라 쓰세요.


1
2
 Toast.makeText(getApplicationContext(), "Test",Toast.LENGTH_SHORT).show();
 
cs


'Programming > Android' 카테고리의 다른 글

Intent와 Intent Filter  (0) 2016.08.26
어플 패키지명  (0) 2016.08.25
HttpURLConnection  (0) 2016.08.25
SharedPreferences  (1) 2016.08.24
Context  (0) 2016.08.24

 HttpURLConnection이 Httppost와 다른 이유는 전송 데이터를 URL에 넣어 전송하느냐 body에 넣어 전송하느냐이다.

후자가 데이터를 감추기에 더 좋을꺼 같긴하다..


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

try {
 
                URL obj = new URL(url+"?"+paramString.toString());
                HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
 
                conn.setReadTimeout(5000);
                conn.setConnectTimeout(5000);
                conn.setDefaultUseCaches(false);
                conn.setRequestMethod("POST");
                conn.setDoInput(true);
                conn.setDoOutput(true);
 
                PrintWriter pw = new PrintWriter(new OutputStreamWriter(conn.getOutputStream()));
                pw.write(paramString);
                pw.flush();
                pw.close();
                int retCode = conn.getResponseCode();
 
                if (retCode == HttpURLConnection.HTTP_OK) {
                    InputStream is = conn.getInputStream();
                    BufferedReader br = new BufferedReader(new InputStreamReader(is)."UTF-8");
                    String line;
                    StringBuffer response = new StringBuffer();
                    while((line = br.readLine()) != null){
                        response.append(line);
                    }
                    br.close();
                    Log.d(TAG,"responvalue: "+response.toString());
                    return response.toString();
                }else{
                    Log.d(TAG,"error code is " + retCode);
                }
 
            } catch (Exception e) {
                e.printStackTrace();
            }
cs

22번 라인에 "UTF-8"을 추가하면 한글깨짐현상을 막을수 있다.



'Programming > Android' 카테고리의 다른 글

어플 패키지명  (0) 2016.08.25
ProgressDialog 와 Toast  (0) 2016.08.25
SharedPreferences  (1) 2016.08.24
Context  (0) 2016.08.24
Activity 생명주기  (0) 2016.08.24

아두이노를 사용하여 시리얼 통신을할때 문자열을 합쳐야 하는 경우가 생긴다

이때는 concat(string str); 이나 String변수끼리 + 연산을 하면되는데

사실 뭘하든지 결과는 같다.


1
2
3
4
5
6
String str1 = "안녕";
String str2 = "하세요";
 
println(str1.concat(str2));
 
println(str1+str2);
cs


같은 값이 나오는 걸 확인할 수 있을 것이다.

+ Recent posts