이 블로그 검색

2011년 3월 20일 일요일

일반 Server 통신과 AIDL을 이용한 방식

* 사실 일반 Server-Client 통신에서는 아래와 같은 문장만 있으면 Server에서 내려준 정보를 받기에 충분하다.

HttpClient mHttpClient = null;
String response;
String strUrl = "http://220.103.225.114:8083/search/getAddr.do?userid=1300072071621&sk=1bfd94bd74ef0b9f8305af5b21e79892&addr_mode=S&cnt_yn=Y";

 class TransThread extends Thread{   //Key
  public void run(){
   Log.e("", "run");

   response = null;

   try{
    Log.e("", "try");

   /* Server 통신 하는 부분 Start */
   URI uri = new URI(strUrl);  

    HttpGet request = new HttpGet();    // request 서버 접속 요청  
    request.setURI(uri);  

    HttpResponse httpResponse = mHttpClient.execute(request);  
   // HttpClient 형 객체 mHttpClient - Server에서 전송하는 Data가 담긴다. 
   response = EntityUtils.toString(httpResponse.getEntity()).trim(); 
  // String 형 객체 response에 server에서 날려준 정보를 Entity별로 담는다.
    Log.e("", "response" + response);

    messageProc(response); //  --> Jason Parser    }catch(Exception e){
    Log.e("", "catch");
    e.printStackTrace();
   }
  }
 }

위의 Server 통신 부분을 Thread에 넣고 안드로이드 Service를 호출해서 받는다.

public void startTransaction(HttpClient mHttpClient, Context ctx, String url, String params){
  if(readyTransaction(ctx)){
   //readyTransaction에서 true가 떨어졌을 경우
   strUrl = url;
   strParams = params;

   this.mHttpClient = mHttpClient;
   if(this.mHttpClient != null){

   }
   worker = new TransThread();   // Thread 생성
   worker.start();    // Thread 시작
  }
 }

 public void doGetUpgrade() throws RemoteException {
   // TODO Auto-generated method stub
   TestSource ts = new TestSource(getApplicationContext());
   ts.startTransaction(mHttpClient, getApplicationContext());   //startTransaction 호출
}


/*  ServiceConnection 객체 생성 Start*/
 ServiceConnection srvConn = new ServiceConnection() {  

  @Override
  public void onServiceDisconnected(ComponentName name) {
   // TODO Auto-generated method stub
   updateService = null;
  }

  @Override
  public void onServiceConnected(ComponentName name, IBinder service) {   // 요 녀석이네...
   // TODO Auto-generated method stub
   updateService = IService.Stub.asInterface(service);     // 이부분이 AIDL 을 처리하는 부분
   Log.e("", "service");
   if(updateService!=null){
    try{
     updateService.doGetUpgrade();   //doGetUpgrade 호출 
     }catch(Exception e){
     e.printStackTrace();
    }
   }
  }
 };

/* ServiceConnection 객체 생성 End */

/* onResume  Start */
 protected void onResume() {
 super.onResume();

  Intent intent = new Intent("kr.softcast.Metroi.Service.StationService.ACTION");
  this.bindService(intent, srvConn, Context.BIND_AUTO_CREATE); 
   // bindService에서 srvConn 호출  --> 원격 호출 Service (IPC)
}


/*** Jason Parsing 부분 ***/
void messageProc(String response) {
  // TODO Auto-generated method stub
  Log.e("", "messageProc");
 
  this.response = response;
  getResult(response.trim()); 
 }
 boolean bSuccess;
 ArrayList<Station> stationList = new ArrayList<Station>();
  //JSON object parse
 private void getResult(String response){  
   //파씽 - 이미 string 형태로 받아온 response를 Jason으로 다시 파씽
  Log.e("getresult", response);
  JSONObject jsonObj = null;
  JSONArray jsonArr = null;
  try{
   jsonObj = ServerUtils.parserMSG(response);
  }catch(Exception e){
   e.printStackTrace();
  }
 
  try{
   bSuccess = jsonObj.getBoolean("success");
  }catch(Exception e){
   e.printStackTrace();
  }
 
  try{
   if(!bSuccess){ //false
   
   }else{
   
   }
  }catch(Exception e){
  
  }
 }

//* JSONObject *//

import org.json.JSONException;
import org.json.JSONObject;
public class ServerUtils {
 // json object
 public static JSONObject parserMSG(String msg) {
  JSONObject jObj = null;
  try {
   jObj = new JSONObject(msg.trim());  // 생성자 인자에 때려 넣으면 자동으로 파씽되나 보네...
  } catch (JSONException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   return null;
  }
  return jObj;
 }
}

HttpPut으로 서버에 Data 보내기

 거의 완벽한 예제가 있어서 퍼온다..
깔끔하게 정리가 잘되어 있음.. 감사.
http://roter.pe.kr/121

  1. public class PutJSONtoServer {   
  2.        
  3.     public PutJSONtoServer() {   
  4.   
  5.         String strURL = "/*WRITE DOWN SERVER ADDRESS*/"//이곳에 Server URL을 적자   
  6.                    
  7.         byte[] postBodyByte; //Entity로 보낼 려면 우선은 byte로 바꿔야 함   
  8.         String postBody=""//Entity로 보낼 값   
  9.            
  10.         postBody = "THIS IS THE ENTITY DATA";   
  11.         postBodyByte=postBody.getBytes(); //Entity를 Byte로 바꿔준다.   
  12.            
  13.         HttpEntity httpBody = new ByteArrayEntity(postBodyByte); //Byte로 바뀐 Entity를 HttpEntity로 바꿔준다.   
  14.         HttpResponse response = null;   
  15.         HttpParams params = new BasicHttpParams();    
  16.         HttpClient client = new DefaultHttpClient(); //HttpClient 선언   
  17.         HttpPut httpPut = new HttpPut(strURL); //만약 put이 아니고 post로 할거면 걍 HttpPost로 바꿔주면 된다.   
  18.         httpPut.setHeader("Content-type","application/json"); //이건 json쓸거라서 이렇게 했다.. 쓸 사람 맘대로 바꾸면 된다.   
  19.         httpPut.setEntity(httpBody); //이곳에 httpBody를 넣는다. httpBody는 엔티티이다~   
  20.         httpPut.setParams(params);   
  21.         try {   
  22.             response=client.execute(httpPut); //서버로 전송한다.   
  23.             Log.i("PUTJSONtoServer","SendJSONData");   
  24.         } catch (ClientProtocolException e) {   
  25.             e.printStackTrace();   
  26.         } catch (IOException e) {   
  27.             e.printStackTrace();   
  28.         }   
  29.         Log.i("PUTJSONtoServer","GET TATUS LINE: " + response.getStatusLine());    
  30.     }   

2011년 3월 17일 목요일

Intro 화면 만들기

 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  
  MyView vw = new MyView(this);    // <- OnCreate() 에 요렇게 View 객체 생성 
  setContentView(vw);                   // <- SetContentView 에 요렇개 삽입
 
  /* 요부분에 시간이 많이 소요되는 작업을 해준다 */
  init();
  setStationList(Define.SUBWAY_LOCAL_SEOUL);

 /* 시간이 많이 소요되는 작업들 */

    handler = new Handler();                   // <-  요런식으로 Handler 를 생성해주고       
     if(flag == true){
         handler.postDelayed(new Runnable() {
             public void run() {
              bitmap.recycle();
              intent = new Intent(Act_Intro.this, Act_Main.class);
               // <- Intent로 실제 Main 객체로 이동.        
              startActivity(intent);
              finish();
              overridePendingTransition(0, 0);
             }
            }, 3000);    
        }
}

 protected class MyView extends View {        // <- 요런식으로 View 클래쓰를 만들고...
  public MyView(Context context) {
   super(context);
   bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.intro);  // Bitmap 객체  }
   public void onDraw(Canvas canvas){                     // OnDraw() 함수...  
   canvas.drawBitmap(bitmap, null, new Rect(0,0,this.getWidth(),this.getHeight()), pnt);  
          }   // <- 캔바스에 bitmap 객체 넣으면, 그 비트맵이 그려짐.
 }

2011년 3월 16일 수요일

뷰에 뷰를 추가하기 - AddView 하기

  
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        final LinearLayout inLayout = (LinearLayout)findViewById(R.id.inLayout); 
        //추가 될 곳을 지정 -> R.layout.main 안에 지정
   
        Button btn = (Button)findViewById(R.id.aaa);
         // 버튼을 누르면 새 뷰가 추가됨.
        btn.setOnClickListener(new Button.OnClickListener(){
         @Override
       public void onClick(View v)
      {
          LayoutInflater inflater = (LayoutInflater) getSystemService        (Context.LAYOUT_INFLATER_SERVICE);
          LinearLayout route_info_tab = (LinearLayout) inflater.inflate(R.layout.route_info_tab, null); 
    // 추가할 녀석(route_info_tab 이라는 다른 xml 파일에 있다.ㅎ)
    inLayout.addView(route_info_tab);
   //inLayout에 route_info_tab을 넣는다.
   }
        });
       
    }

<main.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"
    android:id="@+id/viewMain"
    >
<TextView 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
<Button android:text="@+id/Button01"      // 버튼
  android:id="@+id/aaa"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content">
</Button>
<LinearLayout
 android:id="@+id/inLayout"        // 이렇게 첨가 되는 부분을 지정한다.
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    >
    </LinearLayout>
</LinearLayout>

Final 을 써서 지역변수를 전역화

함수나 조건, 루프 등에서 쓴 지역변수를 다른 인스턴스에서도 쓸 때,
final 로 처리해 주면 전역변수화 된다.

inflate와 setContentView

Inflate를 시켜서 생성한 View 객체와 그 내부의 View들을 findViewById 로 바로 가져 올 수 없다. 아직 메모리에 올라온 것이 아닌가 보다. (Null pointer Exception)
예를들어,
   LinearLayout testA = (LinearLayout)inflater.inflate(R.layout.XXX, null) 로 인플레잇을 시키고,
   testA 안에 있는 testB라는 레이아웃을
   LinearLayout testB =  (LinearLayout)findViewById(R.id.testB) 라고 해서 찾을 수 없다.

그럼 어떻게 하느냐?
=>
1. setContentView(testA) 를 먼저 호출하고 그 뒤에 써 준다.

2. LinearLayout testB =  (LinearLayout)testA.findViewById(R.id.testB) 라고 써 준다.



* 참고

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
 //       setContentView(R.layout.main);
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        LinearLayout main =  (LinearLayout)inflater.inflate(R.layout.main, null);

      final LinearLayout inLayout = (LinearLayout)findViewById(R.id.inLayout);   
// --> 에러 난다. Nullpointer Exception.               
     setContentView(main);   // setContentView 가 어디 있느냐에 따라.. 달라진다.
     final LinearLayout inLayout = (LinearLayout)findViewById(R.id.inLayout); 
// 에러 안난다. setContentView 에서 메모리에 올렸기 때문에 찾을 수 있다.   
        Button btn = (Button)findViewById(R.id.aaa);
         // 버튼을 누르면 새 뷰가 추가됨.
        btn.setOnClickListener(new Button.OnClickListener(){
         @Override
   public void onClick(View v) {
          LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
          LinearLayout route_info_tab = (LinearLayout) inflater.inflate(R.layout.route_info_tab, null);  // 추가할 녀석
    inLayout.addView(route_info_tab);
   }
        })

2011년 3월 15일 화요일

Log Cat 한글로 보기

* 로그캣 도스 창에서 보기 (한글 출력)
도스 창에서 다음 입력
chcp 65001
adb logcat

창 속성에서 (오를쪽 마우스 클릭)
글꼴을 lucida 로 바꾸면됨

2011년 3월 7일 월요일

drawable-hdpi // drawable-mdpi

drawable-hdpi // drawable-mdpi : 차이점 - 해상도 dpi(dot per inch- 1인치 * 1인치에 몇개의 점(dot)이 들어갈 수 있느냐?) 가 hdpi에는 240개 mdpi에는 160개가 들어간다. 
각 해상도 방식에 따라 적합한 방식이 다름
- Nexus One, GlaxyS 등의 대부분의 안드로이드 폰은 WVGA(Wide VGA - 가로 비율이 VGA 보다 약간 높은) 방식이고 이는 hdpi에 좀 더 맞는다.
- LG Optimus One, iPhone 3G등은 HGVA(Half VGA - 일반 VGA와 비율이 같음) 방식이므로 mdpi에 맞는다.