이 블로그 검색

2011년 11월 24일 목요일

Remove Override annotation

JDK를 다시 설치하거나 업뎃을 받으면
Remove Override annotation 이란 에러가 @Override 있는 데마다 뜨는 것을
볼 수 있다. 요것은 자바 빌드 버젼이 안 맞아서 그렇다.
따라서 자바 빌드 버젼을 바꿔주면 된다.

Project --> Properties --> Java Compiler --> Enable project specific settings 체크 박스 체크
Compiler compliance settings 리스트박스에서 자신의 자바 버전에 맞게 선택

2011년 11월 21일 월요일

안드로이드 전화번호부 가져오기

누군가 정리를 잘 해놓아서 가져왔음...  감사합니다. ^^

원본:

Android: 내장 주소록 읽기

갤럭시S를 구매한 이후로 자질구레한 안드로이드용 앱을 만들어 사용하고 있다. 회사 직원의 주소록을 관리하는 것을 만들었는데, 안드로이드 주소록이 따로 있어서 검색 기능을 통합하려고 안드로이드의 주소록을 살펴 보았다.

사용법은 3개의 객체로 계층 구조화 되어 있다는 것을 제외하면 다른 ContentProvider를 사용하는 것과 동일 했다.

주소록 입출력

  • Android의 주소록 구조
  • android.provider.ContactsContract.Contacts : 최상위 주소록
  • android.provider.ContactsContract.RawContacts : 주소록의 출처별 주소록
  • android.provider.ContactsContract.Data : 주소록에 포함되어 있는 데이터 (예, 전화번호, 이메일 등)
contacts-2.png
  • 주소록 입출력 권한
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
  • Contacts 조회 (Android 2.2)
StringBuffer buf = null;
Cursor contacts = null;
long contactID = 0l;

buf = new StringBuffer();
// String sortOrder = Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
// Cursor contactCursor = managedQuery(uri, projection, selection, selectionArgs, sortOrder);
contacts = getContentResolver().query(Contacts.CONTENT_URI,
        new String[] {
            Contacts._ID, Contacts.CONTACT_PRESENCE, 
            Contacts.CONTACT_STATUS,
            Contacts.CONTACT_STATUS_ICON, Contacts.CONTACT_STATUS_LABEL, 
            Contacts.CONTACT_STATUS_RES_PACKAGE,
            Contacts.CONTACT_STATUS_TIMESTAMP, Contacts.CUSTOM_RINGTONE, 
            Contacts.DISPLAY_NAME,
            Contacts.HAS_PHONE_NUMBER, Contacts.IN_VISIBLE_GROUP, 
            Contacts.LAST_TIME_CONTACTED,
            Contacts.LOOKUP_KEY, Contacts.PHOTO_ID, 
            Contacts.SEND_TO_VOICEMAIL,
            Contacts.STARRED, Contacts.TIMES_CONTACTED
            },
        null, null, null);

contacts.moveToFirst();
if (!contacts.isAfterLast()) {
    do {
        contactID = contacts.getLong(0);
        buf.append("--- Contacts Lists ---\n");
        for (int idx = 0;idx < contacts.getColumnCount();idx++) {
            if (contacts.getString(idx) != null) {
                buf.append(contacts.getColumnName(idx).toUpperCase() + ": " 
                   + contacts.getString(idx) + "\n");
            }
        }
        buf.append("\n");
    } while (contacts.moveToNext());
}
contacts.close();
return buf.toString();
  • RawContacts 조회 (Android 2.2)
StringBuffer buf = null;
Cursor rawContacts = null;
long rawContactID = 0l;

buf = new StringBuffer();
rawContacts = getContentResolver().query(RawContacts.CONTENT_URI,
        new String[] {
            RawContacts._ID, RawContacts.ACCOUNT_NAME, 
            RawContacts.ACCOUNT_TYPE, 
            RawContacts.AGGREGATION_MODE, RawContacts.CONTACT_ID, 
            RawContacts.CUSTOM_RINGTONE,
            RawContacts.DELETED, RawContacts.DIRTY, 
            RawContacts.LAST_TIME_CONTACTED,
            RawContacts.SEND_TO_VOICEMAIL, RawContacts.SOURCE_ID, 
            RawContacts.STARRED,
            RawContacts.SYNC1, RawContacts.SYNC2, RawContacts.SYNC3, 
            RawContacts.SYNC4, RawContacts.TIMES_CONTACTED, 
            RawContacts.VERSION
            },
        RawContacts.CONTACT_ID + "=?", 
        new String[] {String.valueOf(contactID)}, null);

rawContacts.moveToFirst();
if (!rawContacts.isAfterLast()) {
    do {
        rawContactID = rawContacts.getLong(0);
        buf.append("--- RawContacts Lists ---\n");
        for (int pos = 0;pos < rawContacts.getColumnCount();pos++) {
            if (rawContacts.getString(pos) != null) {
                buf.append(rawContacts.getColumnName(pos).toUpperCase() 
                   + ": " + rawContacts.getString(pos) + "\n");
            }
        }
        buf.append("\n");
    } while (rawContacts.moveToNext());
}
rawContacts.close();
return buf.toString();
  • Data 조회 (Android 2.2)
StringBuffer buf = null;
Cursor contactData = null;

buf = new StringBuffer();
contactData = getContentResolver().query(Data.CONTENT_URI,
        new String[] {
            Data._ID, Data.MIMETYPE, Data.RAW_CONTACT_ID,
            Data.IS_PRIMARY, Data.IS_SUPER_PRIMARY, Data.DATA_VERSION,
            Data.DATA1, Data.DATA2, Data.DATA3, Data.DATA4, Data.DATA5  
            },
        Data.RAW_CONTACT_ID + "=?", 
        new String[] {String.valueOf(rawContactID)}, null);

buf.append("--- Data Lists ---\n");
contactData.moveToFirst();
if (!contactData.isAfterLast()) {
    do {
        for (int idx = 0;idx < contactData.getColumnCount();idx++) {
            if (contactData.getString(idx) != null) {
                buf.append(contactData.getColumnName(idx).toUpperCase() 
                   + ": " + contactData.getString(idx) + "\n");
            }
        }
        buf.append("\n");
    } while (contactData.moveToNext());
}
contactData.close();
return buf.toString();
  • 전화번호 가져오기
import ContactsContract.CommonDataKinds.Phone;
Cursor PhoneNumberCursor = 
  getContentResolver().query(Phone.CONTENT_URI, null, null, null, null);
  • 연락처 등록
ContentValues values = new ContentValues();
values.put(RawContacts.ACCOUNT_TYPE, "basic");
values.put(RawContacts.ACCOUNT_NAME, "test");
Uri rawContactUri = 
    getContentResolver().insert(RawContacts.CONTENT_URI, values);
long rawContactId = ContentUris.parseId(rawContactUri);
  • 연락처 수정
int resolver.update(Uri uri, ContentValues values, String where, String selectionArgs[])
  • 연락처 삭제
int resolver.delete(Uri url, String where, String selectionArgs[])
  • 자신의 번호를 조회
<uses-permission android:name="android.permission.READ_PHONE_STATE" />

TelephonyManager mTelephonyMgr = 
     (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String myNumber = mTelephonyMgr.getLine1Number();

2011년 11월 17일 목요일



<안드로이드 HttpClient> - 누가 아주 잘 정리해 놓은게 있어서 퍼왔음. (http://wowmymwow.tistory.com/entry/http-%ED%86%B5%EC%8B%A0)


1. java.net 사용법
URL url = new URL(addr);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            if (conn != null) {
                conn.setConnectTimeout(10000);
                conn.setUseCaches(false);
                if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    BufferedReader br = new BufferedReader(
                            new InputStreamReader(conn.getInputStream()));
                    for (;;) {
                        String line = br.readLine();
                        if (line == null) break;
                        html.append(line + '\n'); 
                    }
                    br.close();
                }
                conn.disconnect();
            }

2.번째 org.apache 사용법
HttpGet httpget = new HttpGet(addr);
        DefaultHttpClient client = new DefaultHttpClient();
        StringBuilder html = new StringBuilder(); 
        try {
            HttpResponse response = client.execute(httpget);
            BufferedReader br = new BufferedReader(new 
                    InputStreamReader(response.getEntity().getContent()));
            for (;;) {
                String line = br.readLine();
                if (line == null) break;
                html.append(line + '\n'); 
            }
            br.close();
        } 

2011년 11월 16일 수요일

안드로이드 버전 정보 가져오기

android.os.Build.VERSION.RELEASE
android.os.Build.VERSION.CODENAME

Ex)
public static String getAndroidVersion() {
        String sVersion = android.os.Build.VERSION.RELEASE;
        return sVersion;
    }
   

화면 크기 가져오기

    public static int getDeviceDisplayWidth(Context context){    // 가로 사이즈
    Display display = ((WindowManager)  context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
    return display.getWidth();
    }
    
    public static int getDeviceDisplayHeight(Context context){    // 세로 사이즈
    Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
    return display.getHeight();
    }

가져오는 값은 px 픽셀임..

ConnectivityManager 안드로이드 네트워크 상태 값을 가져오는 API

ConnectivityManager 를 통해 네트워크 환경 값을 가져올 수 있다.
그리고 가져온 환경 값은 NetworkInfo 클래쓰의 객체를 통해 저장되어서 사용한다.

Ex)

public static int getNetworkType(Context context) {
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo_3G = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
NetworkInfo networkInfo_WIFI = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo networkInfo_WIMAX = manager.getNetworkInfo(ConnectivityManager.TYPE_WIMAX);

if (networkInfo_WIFI != null && networkInfo_WIFI.isConnectedOrConnecting()) {
return NETWORK_WIFI;
} else if (networkInfo_3G !=null && networkInfo_3G.isConnectedOrConnecting()) {
return NETWORK_3G;
} else if (networkInfo_WIMAX !=null && networkInfo_WIMAX.isConnectedOrConnecting()) {
return NETWORK_WIMAX;
}

return NETWORK_NONE;
}

manifest.xml 에 다음과 같은 permission 이 추가 되어야 함.
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

해당 객체의 클래쓰 이름을 가져올 때

객체의 getClass() 의 getName()을 사용하면 팩키지 이름을 포함한 클래쓰 이름을 가져온다.

Ex)
if(this.getClass().getName().equals("com.lge.readersworld.view.DiscoverDetailListLandView"))
{
           .................................
           .................................
}

2011년 11월 15일 화요일

동적으로 화면 전환 고정시키기

어떤 특정 상황에서만 화면을 고정시켜야 될 때가 있다.
그럴 때는

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);   // 세로 고정
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); // 가로 고정
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);  // 다시 원래 대로

를 사용하자.

Ex)


if(bottomLayout.getVisibility() == View.VISIBLE){
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}

bottomLayout 이 보일때는 화면 세로로 고정...



@Override
public void onBackPressed() {
selectedBubbleNum = -1;
if(bottomLayout.getVisibility() == View.VISIBLE){
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
}else{
finish();
}
}



Back 키를 누루면 다시 자유자재로 변환

2011년 11월 14일 월요일

안드로이드 HardKey 사용

로그 캣을 보면 하드키를 누를 때, 아래와 같이 해당 하드키에 대한 KeyCode 값이 나오는 걸 알 수 있다.

================

11-15 13:13:21.859: INFO/WindowManager(201): [e] [interceptKeyTq] event.scancode139
11-15 13:13:21.859: DEBUG/WindowManager(201): keyEvent event=KeyEvent{action=0 code=82 repeat=0 meta=0 scancode=0 chars=null mFlags=0}
11-15 13:13:21.867: INFO/InputMethodService(293): [T] Scancode = 139,  Keycode = 82
11-15 13:13:21.882: INFO/WindowManager(201): [e] [interceptKeyTq] event.scancode139
11-15 13:13:21.882: DEBUG/WindowManager(201): keyEvent event=KeyEvent{action=1 code=82 repeat=0 meta=0 scancode=0 chars=null mFlags=0}


=================

아래와 같이 onKeyDown() 메서드를 이용해 키 클릭에 대한 이벤트를 잡아 올 수 있다.

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == 82){
                      /* 이부분에 구현할 Action 을 넣는다.   */
Intent intent = new Intent(this, DiscoverSearchActivity.class);
intent.putExtra("cpName", app_id);
intent.putExtra("package_nm", package_nm);
Util.startActivity(this, intent);
                   /* Action */
}
return super.onKeyDown(keyCode, event);
}


2011년 11월 9일 수요일

안드로이드 서버 통신 API

public String getData(String url, Map<String, String> headers, Map<String, String>[] params, boolean isPostType) throws Exception {

StringBuilder sb = new StringBuilder();
InputStream is = null;
DefaultHttpClient httpclient = null;
BufferedReader reader = null;
try {
httpclient = new DefaultHttpClient();

HttpParams httpParams = httpclient.getParams();
HttpConnectionParams.setConnectionTimeout(httpParams, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpParams, HTTP_TIMEOUT);

HttpResponse response = null;

if (params != null && isPostType) {     // Post 방식 일때
HttpPost httpPost = new HttpPost(url);
    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

    for (int i=0;i<params.length;i++) {
for (Map.Entry<String, String> entry: params[i].entrySet()) {
        nameValuePairs.add(new BasicNameValuePair(entry.getKey(), (String)entry.getValue()));
        Util.log("param :: "+ entry.getKey() +"="+entry.getValue());
}
    }
    UrlEncodedFormEntity entityRequest = new UrlEncodedFormEntity(nameValuePairs, "UTF-8");
    httpPost.setEntity(entityRequest);
    if (headers != null) {
       for (Map.Entry<String, String> entry2: headers.entrySet()) {
        httpPost.addHeader(entry2.getKey(), entry2.getValue());
        Util.log("header :: "+entry2.getKey()+"="+ entry2.getValue());
       }
}
    response httpclient.execute(httpPost);


//DefaultHttpClient 객체의 execute 함수의 파라메터에 httpRequest 객체    (httpPost, httpGet)를 넘겨주면 HttpResponse 객체를 리턴

} else {                                                          //Get 방식일때
if (params != null) {
if (params[0].entrySet().size() > 0) url += "?";
for (Map.Entry<String, ?> entry : params[0].entrySet()) {
if (entry.getValue() instanceof String[]) {
String[] values = (String[]) entry.getValue();
for (int i = 0; i < values.length; i++) {
url += entry.getKey() + "=" + values[i] + "&";
}
} else {
url += entry.getKey() + "=" + entry.getValue() + "&";
}
}
}

       HttpGet httpget = new HttpGet(url);
       Util.log("network", "url = "+url);
if (headers != null) {
       for (Map.Entry<String, String> entry2: headers.entrySet()) {
        httpget.addHeader(entry2.getKey(), entry2.getValue());
       }
}
response = httpclient.execute(httpget);
}

is = response.getEntity().getContent();

reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);

String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}

} catch (Exception e) {
Util.logError(e);
throw e;
} finally {
try {
if (is != null) is.close();
if (reader != null) reader.close();

} catch (Exception e) {throw e;}
}

xmlValue = sb.toString();
Log.d("debug", "url = " + url);
Log.d("debug", xmlValue);
return xmlValue;
}

Intent Action을 통한 다른 Application 끼리 통신.

http://alnova2.tistory.com/365   <-- 요기서 퍼옴.

setAction(key) 와 intent-filter 의 action tag 로 통신 할 수 있음. 


* 인텐트 Sender & Receiver  <-- Application 1
1. intentsender.java
package com.android.intentsender;
....
public class intentsender extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        // sendIntent
        Intent i = new Intent();
        i.setAction("com.android.intentsender.sendintent");   <-- setAction 으로 Action Key 값을 날린다.
        i.putExtra("send", "Hello I'am Intent sender");
        startActivityForResult(i,1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        TextView tv=(TextView)findViewById(R.id.tv01);
        if(resultCode==RESULT_OK){
            if (requestCode==1){
                tv.setText(data.getStringExtra("reply"));
            }
        }
    }
}
2. layout/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"
    >
<TextView  
    android:id ="@+id/tv01"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
</LinearLayout>

- 이 어플리케이션은 com.android.intentsender.sendintent(임의의) 라는 action 을 가지고 activity를 실행한다. 실행한 결과를 TextView에 뿌리도록 한다

* 인텐트 Receiver/Reply   <-- application 2
1. intentreceiver.java
package com.android.intentreceiver;
....
public class intentreceiver extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Intent i = getIntent();
        TextView tv=(TextView)findViewById(R.id.tv01);
        tv.setText(i.getStringExtra("sender"));
        i.putExtra("reply","Hello I'am IntentReceiver");
        setResult(RESULT_OK,i);
        finish();
    }
}
- 이 어플리케이션은 intent를 받아서 reply를 설정하고 종료한다.

* 인텐트 sender/receiver를 호출하면 화면 맨 위에 인텐트 Receiver/Reply 어플리케이션에서 받은 문자열을 출력하는 것을 알수 있다. 그런데 인텐트 Receiver/Reply 어플리케이션에서 해당 인텐트를 받기 위해서는  intentreceiver의 AndroidManifest.xml에 다음과 같이 intent-filter설정을 해주어야 한다
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.android.intentreceiver"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".intentreceiver"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
                <action android:name="com.android.intentsender.sendintent" />   <-날린 Action Key로 받는다. 
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    </application>
    <uses-sdk android:minSdkVersion="3" />
</manifest> 

2011년 11월 7일 월요일

텍스트 컬러에 셀렉터를 넣는 법

아래와 같이 글씨에도 셀렉터를 줄 수 있다.
텍스트컬러 속성에 파일을 연동시키고, 일반 셀렉터 파일을 쓰는 것과 같은 원리로 쓰면 된다.

  <TextView android:id="@+id/item_title"
      android:layout_width="match_parent"
      android:textSize="17.5dp"
       android:textColor="@color/discover_category_title" 
      android:gravity="center_horizontal"
      android:textStyle="bold"
      android:paddingTop="3dp"
      android:layout_height="wrap_content"
               android:layout_below="@id/item_icon"/>  


discover_category_title.xml


<?xml version="1.0" encoding="utf-8"?>

<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:state_selected="true" android:color="@color/white" />

<item android:state_pressed="true" android:color="@color/white" />

<item android:state_focused="true" android:color="@color/white" />

<item android:color="@color/black" />

</selector>

스크롤 뷰 막기

아래와 같이 onScrollChanged 를 오버라이딩 한다.

@Override      //스크롤 막음
public void onScrollChanged(int x, int y, int x2, int y2){
Util.log(" x-position = " + x + " this.getWidth() = " + this.getWidth() );
if(x < this.getWidth()){
scrollTo(0, 0);
return;
}
}

가로뷰였는데, 그래서 x좌표가 this.getWidth() 즉 해당 뷰의 가로 크기보다 작을 때, 
바로 scrollTo(0,0) 로 박아주었더니 가로 스크롤이 안 움직임. 
세로 뷰 같은 경우는 y와 getHeight()를 쓰면 될 듯.

또 한가지 방법. 
onTouchEvent()를 이용 - 특정 조건에 해당하면 바로 return 한다.


public boolean onTouchEvent(MotionEvent ev) {      // 데이타가 없는 경우 스크롤 안되게 고정.
if (WishListActivity.wishListDataArr.get(0).getTitle().equals(""))  // 데이터가 없을 조건 
                   return false;
else 
                   return super.onTouchEvent(ev);
}

2011년 10월 30일 일요일

이미지 한장으로 커스텀 프로그레시브 바 만들기

<intro.xml>  ======  intro.xml  -> 이 인트로 화면에 들어가는 프로그레시브 바의 배경이 이미지 단 한장짜리이다.
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/intro_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/intro_bg"> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="38.2dp" android:layout_alignParentBottom="true"> <TextView android:id="@+id/intro_text" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="6.5dp" android:textSize="13.5dp" android:textColor="#303030" android:textStyle="bold" android:text="@string/intro_greetings" android:gravity="center_horizontal" /> <TextView android:id="@+id/intro_text" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="13.5dp" android:textSize="12dp" android:textColor="@color/txt_100_9" android:text="@string/intro_text" android:gravity="center_horizontal" />
<ProgressBar android:id="@+id/intro_progress" android:layout_width="wrap_content" android:layout_height="wrap_content" android:indeterminateDrawable="@drawable/progress_custom" android:layout_gravity="center_horizontal" android:visibility="invisible" /> 
 </LinearLayout>
</RelativeLayout>

==============================================================================


<progress_custom.xml>  ====== progress_custom.xml 파일이다. 
<?xml version="1.0" encoding="utf-8"?>
<animated-rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:drawable="@drawable/loading"    --> 1장 짜리 이미지 파일 
    android:pivotX="50%"
    android:pivotY="50%"
  />

==============================================================================

특정 이미지(뷰)만 셀렉터를 안 먹게 하는 방법

커스텀 리스트 뷰 같은 곳에서
list_detail_item.xml 의 background 속성에 셀렉터를 넣으면
전체가 전부 셀렉터가 먹는다.

이 때  list_detail_item 안의 특정 뷰에는 셀렉터를 안 먹게 할려면
그 이미지만 별도의 셀렉터를 설정해, 그 셀렉터를 setVisibility 에서 Gone 처리 하면 된다.

예컨데,
list_detail_item.xml 에 아래와 같이 여러개의 뷰가 있고, 전체 백그라운데 셀렉터를 넣은 상태에서 이중 View2 만 셀렉터를 안먹게 하려면

android:background="@drawable/list_item_selector"
<View 1>
<View 2>
<View 3>


View2 를 따로 imageView 로 떠서,
View2에 android:background="@drawable/list_item_View2_selector" 라는 셀렉터를 만든 후,
(이 셀렉터는 위의 list_detail_item 셀렉터와 동일하게 해 주면 된다.)
이 셀렉터를 Gone 처리해 주면, 셀렉터가 적용 되지 않는다.
왜냐하면 배경 셀렉터보다 직접 해당 뷰에 해주는 셀렉터가 위에 먹기(우선 순위가 높기) 때문이다. 따라서 해당 뷰에 직접 따로 셀렉터를 해 주면 그 배경이 되는 셀럭터 자체는 무시되는 듯 하다.

 

[토크게임엔진] onCollison

두 객체 A,B 의 충돌 처리 시

B::onCollision(){ .... A.XXX } 와 같이

B객체의 onCollison 메서드 내에서 A의 충돌 처리를 하면
충돌이 일어난 후 A.XXX 가 동작한다.

따라서 충돌이 일어나기 전 객체의 행동을 제어하려면

A::onCollison(){ ..... A.XXX} 와 같이 A객체 onCollision 메서드 내에서
처리를 해 줘야 한다.

[토크게임엔진] %this 로 받기

같은 객체에 이름을 중복해서 줘도 상관없지만,
보장할 수 없다.

각각의 객체의 값을 구현하려면 ,

onlevelloaded(%this){
%this.XXXX
} 와 같이 %this로 주고 받아야 한다.

2011년 10월 25일 화요일

WebView 컴포넌트 : WebActivity

아래의 웹액티비티로 Intent의 putExtra로 URL만 인자값으로 날려주면 됨.

Ex)

Intent intent = new Intent(DiscoverSearchActivity.this, WebActivity.class);
try {
// intent.putExtra("Discover_search", searchKey);
Util.log(">>>>>>>>>>>>>>>>>>>>>>>" + Define.audibleURL+searchKey);
intent.putExtra("url", Define.audibleURL+searchKey);
startActivity(intent);

**********************************************

<WebActivity.java>

package com.lge.readersworld.activity;

import com.lge.readersworld.R;
import com.lge.readersworld.util.Util;

import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.CookieSyncManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class WebActivity extends Activity {

public WebView webview;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
   setContentView(R.layout.web);

webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);

   String url = getIntent().getStringExtra("url");
   Util.log("WEBVIEW URL = "  + url);
    webview.loadUrl(url);
   
   webview.setWebViewClient(new WebViewClient(){
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url)  {
    view.loadUrl(url);
    return true;
    }
   
    @Override
    public void onPageFinished(WebView view, String url){
        CookieSyncManager.getInstance().sync();
        }
    });

   webview.setOnKeyListener(new View.OnKeyListener() {

@Override
public boolean onKey(View arg0, int arg1, KeyEvent arg2) {

return false;
}
});

     
     
}

@Override
public void onResume() {
        super.onResume();
     
}

@Override
public void onPause() {
        super.onPause();
     
        if (CookieSyncManager.getInstance() != null) {

        CookieSyncManager.getInstance().stopSync();

        }
}

@Override
public void onDestroy() {

super.onDestroy();
}

}

2011년 10월 23일 일요일

서버 연동 컴포넌트

package com.lge.readersworld.async;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.content.Context;
import android.os.Build;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;

import com.lge.readersworld.util.Define;
import com.lge.readersworld.util.RWDeviceUtil;
import com.lge.readersworld.util.RWPreference;
import com.lge.readersworld.util.Util;

public class RWServerNetwork {

public static final int HTTP_TIMEOUT = 5000;

private String xmlValue = null;
private String fileLength = null;
private String fileName = null;

public static HashMap<String, String> getHeader(Context context) {

Display defaultDisplay = ((WindowManager)context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int width = defaultDisplay.getWidth();
int height = defaultDisplay.getHeight();

HashMap<String, String> header = new HashMap<String, String>();
    header.put("x-lg-accept", "text/xml");
//     header.put("x-lg-language", "EN");
//     header.put("x-lg-country", "AU");
//     header.put("x-lg-model", "GW820");    
    // jh.lee : 선택한 국가에 맞춰서 Header를 보낸다.
    header.put("x-lg-language", RWPreference.getInstance(context).getData(Define.SHARED_LOGIN_LANGUAGECODE, "EN"));
    header.put("x-lg-country", RWPreference.getInstance(context).getData(Define.SHARED_LOGIN_COUNTRYCODE, "US"));
    header.put("x-lg-model", RWDeviceUtil.getModelInfo());
    //-------------------------------------------------------------------------------------------------------------------

    header.put("x-lg-agent", "LGRW;1.0.0.1;id");
    header.put("x-lg-platform", "AN"+Build.VERSION.RELEASE);

    if (RWDeviceUtil.isLandscape(context)) {
    header.put("x-lg-resolution", width + "X" + height);
    } else {
    header.put("x-lg-resolution", height + "X" + width);
    }

return header;
}

/**
* Carrier 코드를 출력한다.
*
* @param context
* @return
*/
public static String getCRCode(Context context) {
return "NET_2015";
}

/**
* XML에서 원하는 값을 추출한다. Level1만 지원함.
* @param str
* @return
*/
public String parser(String str) {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputStream istream = new ByteArrayInputStream(xmlValue.getBytes("utf-8"));
Document doc = builder.parse(istream);

Element order = doc.getDocumentElement();
NodeList items = order.getElementsByTagName(str);
Node item = items.item(0);
if (item==null) return null;
Node text = item.getFirstChild();
String ItemName = text.getNodeValue();

return ItemName;

} catch (Exception e) {
Util.logError(e);
}
return null;
}

public Element getParser() {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputStream istream = new ByteArrayInputStream(xmlValue.getBytes("utf-8"));
Document doc = builder.parse(istream);

Element order = doc.getDocumentElement();
return order;

} catch (Exception e) {
Util.logError(e);
}
return null;
}

public static Element getParser(String filename) {
try {
String xmlValue = Util.getFileContent(filename);
if (xmlValue==null) return null;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputStream istream = new ByteArrayInputStream(xmlValue.getBytes("utf-8"));
Document doc = builder.parse(istream);

Element order = doc.getDocumentElement();
return order;

} catch (Exception e) {
Util.logError(e);
}
return null;
}

@SuppressWarnings("unchecked")
public String getData(String url, Map<String, String> headers, Map<String, String> params, boolean isPostType) throws Exception {
return getData(url, headers, new Map[]{params}, isPostType);
}

public String getData(String url, Map<String, String> headers, Map<String, String>[] params, boolean isPostType) throws Exception {

StringBuilder sb = new StringBuilder();
InputStream is = null;
DefaultHttpClient httpclient = null;
BufferedReader reader = null;
try {
httpclient = new DefaultHttpClient();

HttpParams httpParams = httpclient.getParams();
HttpConnectionParams.setConnectionTimeout(httpParams, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpParams, HTTP_TIMEOUT);

HttpResponse response = null;

if (params != null && isPostType) {
HttpPost httpPost = new HttpPost(url);
    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

    for (int i=0;i<params.length;i++) {
for (Map.Entry<String, String> entry: params[i].entrySet()) {
        nameValuePairs.add(new BasicNameValuePair(entry.getKey(), (String)entry.getValue()));
        Util.log("param :: "+ entry.getKey() +"="+entry.getValue());
}
    }
    UrlEncodedFormEntity entityRequest = new UrlEncodedFormEntity(nameValuePairs, "UTF-8");
    httpPost.setEntity(entityRequest);
    if (headers != null) {
       for (Map.Entry<String, String> entry2: headers.entrySet()) {
        httpPost.addHeader(entry2.getKey(), entry2.getValue());
        Util.log("header :: "+entry2.getKey()+"="+ entry2.getValue());
       }
}
    response = httpclient.execute(httpPost);
} else {
if (params != null) {
if (params[0].entrySet().size() > 0) url += "?";
for (Map.Entry<String, ?> entry : params[0].entrySet()) {
if (entry.getValue() instanceof String[]) {
String[] values = (String[]) entry.getValue();
for (int i = 0; i < values.length; i++) {
url += entry.getKey() + "=" + values[i] + "&";
}
} else {
url += entry.getKey() + "=" + entry.getValue() + "&";
}
}
}

       HttpGet httpget = new HttpGet(url);
       Util.log("network", "url = "+url);
if (headers != null) {
       for (Map.Entry<String, String> entry2: headers.entrySet()) {
        httpget.addHeader(entry2.getKey(), entry2.getValue());
       }
}
response = httpclient.execute(httpget);
}

is = response.getEntity().getContent();

reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);

String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}

} catch (Exception e) {
Util.logError(e);
throw e;
} finally {
try {
if (is != null) is.close();
if (reader != null) reader.close();

} catch (Exception e) {throw e;}
}

xmlValue = sb.toString();
Log.d("debug", "url = " + url);
Log.d("debug", xmlValue);
return xmlValue;
}

public InputStream getDownload(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
InputStream is = null;
DefaultHttpClient httpclient = null;
try {

if (params != null) {
url +="?";
       for (Map.Entry<String, String> entry: params.entrySet()) {
           url += entry.getKey()+"="+URLEncoder.encode(entry.getValue())+"&";
       }
}
Util.log("network", "url = "+url);
HttpGet httppost = new HttpGet(url);

if (headers != null) {
       for (Map.Entry<String, String> entry: headers.entrySet()) {
        httppost.addHeader(entry.getKey(), entry.getValue());
       }
}
httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
Header[] rheaders = response.getAllHeaders();
for (int i=0;i<rheaders.length;i++) {
if (rheaders[i].getName().toLowerCase().equals("result")) {
boolean tmp = "700".equals(rheaders[i].getValue());
if (tmp==false) throw new Exception("Server Error.");
}

if (rheaders[i].getName().toLowerCase().equals("content-length")) {
fileLength = rheaders[i].getValue();
}
if (rheaders[i].getName().toLowerCase().equals("content-disposition")) {
String tmp = rheaders[i].getValue();
fileName = tmp.substring(tmp.indexOf("filename=")+9);
}

Util.log("debug", "headers["+i+"] "+ rheaders[i].getName()+"="+rheaders[i].getValue());
}
is = response.getEntity().getContent();
return is;

} catch (Exception e) {
Util.logError(e);
throw e;
}
}

public int getFileLength() {
int size = 0;
try {
size = Integer.parseInt(fileLength);
}catch (Exception e) {}
return size;
}

public String getFileName() {
return fileName;
}

}