팝업으로 띄우는 액티비티 클래스 내에 다음 코드를 추가하면 끝.


 protected void onApplyThemeResource(Resources.Theme theme, int resid, boolean first) {

   

    super.onApplyThemeResource(theme, resid, first);

   

    theme.applyStyle(style.Theme_Panel, true);

}  

     


또는



 getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));



안드로이드 TextView는 글씨를 다루는 뷰인 만큼 폰트를 교체 할 수 있습니다 .

안드로이드에서는 네가지의 기본 폰트를 제공하고, 추가로 폰트를 추가하면 해당 폰트를 

사용 할 수 있는데요, 먼저 기본폰트는 narmal , sans, serif, monospace 네가지로 


이런 폰트 모양입니다. 폰트 적용은 간단한데요 xml의 TextView에서 

android:typeface= "normal" 이런식으로 추가해 주시면 됩니다. 


이제 다른 폰트를 다운받아 적용시키는 방법인데요 , 



위에 Frutiger55Roman 이라는 이름의 폰트가 있습니다 , 이걸 프로젝트의 assets 폴더에 넣어주시고



소스 상에서 추가를 해주여야 합니다. 간단한 테스트 이므로 저는 onCreate에 추가를 하였습니다.



두번째 줄이 핵심입니다, 뒤에 확장자까지 써주셔야하는거 잊지마시구요 . 저렇게 등록을 해주면 


이런 추가된 폰트로 글씨가 나타나게 됩니다 ! 


항상 최상위에 나오는 뷰 만들기2 (팝업 비디오 + Q슬라이드)


이전에 쓴 글 '항상 최상위에 나오는 뷰 만들기'는 뷰는 나오지만 터치 이벤트를 받지 못했다. 터치 이벤트를 받더라도 ACTION_OUTSIDE 이벤트만 받을 수 있었다.


이제는 그냥 최상위 뷰만 나오게 하는 것이 아니라 뷰를 최상위에 나오게 하면서 모든 터치 이벤트를 받아보자. 터치로 뷰를 이동해보고(갤럭시의 팝업 비디오 처럼) 투명도를 조절해보자!!(옵티머스의 Q슬라이드)


이전에 쓴 '항상 최상위에 나오는 뷰 만들기' 와 방식은 같다.

1. 최상위에 나오게 하기 위해서는 Window에 뷰는 넣는다.

2. 다른 화면에서도 나오게 하기위해서는 서비스에서 뷰를 생성하여야 한다.

3. 뷰에 들어오는 터치 이벤트를 OnTouchListener를 통해서 받는다.


1. 서비스 생성

자신의 앱이 종료된 후에도 항상 해당 뷰가 떠 있어야 한다. 그래서 Activity에서 뷰를 추가하는 것이 아니라 Service에서 뷰를 추가 해야 한다.


AlwaysOnTopService.java

public class AlwaysOnTopService extends Service {
    @Override
    public IBinder onBind(Intent arg0) { return null; }
    
    @Override
    public void onCreate() {
        super.onCreate();
    }

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


2. 뷰 생성 및 최상위 윈도우에 추가

간단하게 텍스트뷰 하나 추가하는 코드이다.

    private TextView mPopupView;                            //항상 보이게 할 뷰
    private WindowManager.LayoutParams mParams;  //layout params 객체. 뷰의 위치 및 크기
    private WindowManager mWindowManager;          //윈도우 매니저

    @Override
    public void onCreate() {
        super.onCreate();

        mPopupView = new TextView(this);                                         //뷰 생성
        mPopupView.setText("이 뷰는 항상 위에 있다.");                        //텍스트 설정
        mPopupView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18); //텍스트 크기 18sp
        mPopupView.setTextColor(Color.BLUE);                                  //글자 색상
        mPopupView.setBackgroundColor(Color.argb(127, 0, 255, 255)); //텍스트뷰 배경 색

        //최상위 윈도우에 넣기 위한 설정
        mParams = new WindowManager.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.TYPE_PHONE,//항상 최 상위. 터치 이벤트 받을 수 있음.
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,  //포커스를 가지지 않음
            PixelFormat.TRANSLUCENT);                                        //투명
        mParams.gravity = Gravity.LEFT | Gravity.TOP;                   //왼쪽 상단에 위치하게 함.
        
        mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);  //윈도우 매니저
        mWindowManager.addView(mPopupView, mParams);      //윈도우에 뷰 넣기. permission 필요.
    }


 이전 글에서는 TYPE을 TYPE_SYSTEM_OVERLAY로 주었다. 이러면 화면 전체를 대상으로 뷰를 넣지만 터치 이벤트를 받지는 못한다.

 하지만 TYPE을 TYPE_PHONE으로 설정하면 터치 이벤트를 받을 수 있다. 하지만 Status bar 밑으로만 활용가능하고 뷰가 Focus를 가지고 있어 원래 의도대로 뷰 이외의 부분에 터치를 하면 다른 앱이 터치를 사용해야 하는데 이것이 불가능 하고 키 이벤트 까지 먹어 버린다.

 이것을 해결하기 위해 FLAG 값으로 FLAG_NOT_FOCUSABLE을 주면 뷰가 포커스를 가지지 않아 뷰 이외의 부분의 터치 이벤트와 키 이벤트를 먹지 않아서 자연스럽게 동작할 수 있게 된다.


3. 매니페스트에 퍼미션 설정

WinodwManager에 addView 메소드를 사용하려면 android.permission.SYSTEM_ALERT_WINDOW 퍼미션이 필요하다.


<manifest  ................ >
    <application ................ >
        <activity
           ................
        </activity>
        <service 
           ................
        </service>
    </application>
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
    <uses-sdk android:minSdkVersion="7" />
</manifest>


이전 글에는 service 태그 안에 퍼미션을 주라고 했지만 service에 주지 않아도 된다. 그냥 uses-permission을 주면 된다.


4. 터치 이벤트 받기

뷰에 터치 리스너를 등록하면 터치 이벤트를 받을 수 있다.


mPopupView.setOnTouchListener(mViewTouchListener);              //팝업뷰에 터치 리스너 등록


private OnTouchListener mViewTouchListener = new OnTouchListener() {
    @Override public boolean onTouch(View v, MotionEvent event) {
        switch(event.getAction()) {
            case MotionEvent.ACTION_DOWN:                //사용자 터치 다운이면
                if(MAX_X == -1)
                    setMaxPosition();
                START_X = event.getRawX();                    //터치 시작 점
                START_Y = event.getRawY();                    //터치 시작 점
                PREV_X = mParams.x;                            //뷰의 시작 점
                PREV_Y = mParams.y;                            //뷰의 시작 점
                break;
            case MotionEvent.ACTION_MOVE:
                int x = (int)(event.getRawX() - START_X);    //이동한 거리
                int y = (int)(event.getRawY() - START_Y);    //이동한 거리
                
                //터치해서 이동한 만큼 이동 시킨다
                mParams.x = PREV_X + x;
                mParams.y = PREV_Y + y;
                
                optimizePosition();        //뷰의 위치 최적화
                mWindowManager.updateViewLayout(mPopupView, mParams);    //뷰 업데이트
                break;
        }
        
        return true;
    }
};


터치로 뷰를 이동하거나 크기 조절을 하려면 WindowManager.LayoutParams 객체의 값을 변경해 주면 된다. x, y는 뷰의 시작점 좌표이다. Q슬라이드 처럼 투명도 조절은alpha값을 변경하면 된다. 0~1사의 값을 넣어 주면 된다.

이렇게 WindowManager.LayoutParams의 값을 변경해준 다음 WindowManager의 updateViewLayout메소드를 사용하여 뷰의 변경사항을 적용한다.



5. 뷰 제거

서비스 종료시 뷰를 제거 해야 한다.

    @Override
    public void onDestroy() {
        if(mWindowManager != null) {        //서비스 종료시 뷰 제거. *중요 : 뷰를 꼭 제거 해야함.
            if(mPopupView != null) mWindowManager.removeView(mPopupView);
            if(mSeekBar != null) mWindowManager.removeView(mSeekBar);
        }
        super.onDestroy();
    }


6. 서비스 실행/중지 할 activity 만들기

AlwaysOnTopActivity.java


public class AlwaysOnTopActivity extends Activity implements on_clickListener {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        findViewById(R.id.start).seton_clickListener(this);        //시작버튼
        findViewById(R.id.end).seton_clickListener(this);            //중시버튼
    }
    
    @Override
    public void on_click(View v) {
        int view = v.getId();
        if(view == R.id.start)
            startService(new Intent(this, AlwaysOnTopService.class));    //서비스 시작
        else
            stopService(new Intent(this, AlwaysOnTopService.class));    //서비스 종료
    }
}


실행 결과


 앱 시작뷰 추가 바탕화면 (위치 이동)

 동영상 재생
 Dragon Flight 게임
인터넷 (투명값 변경)




 AlwaysOnTop.zip

전체 샘플 코드 첨부하였습니다.

*글과 자료는 출처만 밝히시면 얼마든지 가져다 쓰셔도 됩니다.

안드로이드는 sp와 dip(화면 표시 단위)을 권장하고 있습니다.
이에 대해서 포스팅하여 글을 적어 봅니다.

프로젝트 생성 시 폴더로 LDPI(저해상도), MDPI(중해상도), HDPI(고해상도)로 생성이 됩니다.

Density(밀도)값은 LDPI->120, MDPI->160, HDPI->240으로 각각 인치당 필셀수를 의미합니다.
참조 링크 :http://developer.android.com/guide/practices/screens_support.html

LDPI는 120/240 = 1/2,
MDPI는 160/240 = 2/3로 길이당 픽셀수가 감소한다.

레이아웃용 xml 파일에 기술되어야 할 dip값은 다음과 같이 계산 할 수 있다.
dip = px * (160/density)

Density값은 HDPI, MDPI, LDPI의 값이다.
결국 MDPI일때 dip값과 px값은 동일하다.

출처 : http://ezcocoa.com/?p=507

출처 : http://www.androidpub.com/57847


안녕하세요.  

대부분의 프로그램이 설정 관련 화면을 만들게 되는데요.  

안드로이드에서 이 부분도 거의 정형화가 되어 있어서 기본적으로다  지원하더군요. 

"알짜만 골라 배우는 안드로이드 프로그래밍" 책은  이 부분을 잘 설명하고 있는데요. 
"프로페셔널  안드로이드 개발"은   그냥 보통의  activity를 만들어서 전부 코딩하는 것으로 알려주더군요. 

두 방법다 장점이 있기는 하지만, 
일관된  UI 와  작업을 효율성을 위해서는  "알짜..." 의 방법이  좋을 듯합니다. 


아래 내용은  설정 화면을  만드는 쉬운 방법입니다. 


1.  환경설정 xml 파일 만들기  

  이클립스의  File  -  New  - Other  에 가면  아래와 같은 창이 나옵니다. 
set00.png 

Android XML File을 선택합니다. 

set01.png 

빨간색 사각형 한 곳만   알맞은 값으로  넣어 놓고  [Finish] 버튼을 누릅니다. 

그럼,  setting.xml 파일이    /res/xml 아래에 생성이 됩니다. 


2.  화면 구성

/res/xml/setting.xml 파일을 선택하면, 

PreferenceScreen 이라는 것이 보이는 데요.  이것을 선택하고,   [Add] 버튼을 누르면   아래처럼 추가 가능한 것들이 나옵니다.
set02.png 

이것들이 설정화면에  사용가능한 것들인데요. 

이름 그대로   CheckBox,  List  , Edit 등을  추가할 수 있구요. 
Ringtone은   벨소리 종류 선택을 추가 할 수 있답니다. 

RreferenceCategory 는    설정의 종류를 그룹 지을 때 사용하구요. 

PreferenceScreen은   서브 화면으로  전환해서 사용하는 경우에 사용한답니다. 

set03.png 

위 그림처럼  CheckBoxPreference 를 추가하면  오른쪽에  속성값을  넣을 수가 있는데요. 

이중에 중요한 것이 

Key  인데요,   설정에 저장된 값을  읽어 올때 사용한답니다.
Title 과  Summary 는  화면에 출력되는 값이구요. 

set04.png 

ListPreference는  Key, Title, Summary  말고도, 
Entries 와  Entry values 를  넣어주어야 하는데요. 

리스트이기 때문에 출력할 내용을  배열로  넣어 주어야 합니다. 

set05.png 

strings.xml 에   출력할  내용을 가지고 있는 배열을  만듭니다. 

1개는  화면 출력용으로,  1개는  실제값을 가진 배열로 만듭니다. 

set06.png 


그런 후에   setting.xml 에서  Entries 의 옆의 [Browse...] 버튼을 누르면 ,  위 그림처럼 선택할 수 있는 것이 나온답니다. 

set07.png 

위  그림처럼  선택해 주시면 됩니다. 

이런식으로  화면 작업을  다 하신 후에  java class를 만들어 주시면 됩니다. 


3. 환경설정 java class 만들기 

이클립스의   File - New - class 를 선택합니다. 
  set08.png 

SuperClass를    옆의 [Browse...]버튼을  눌러서  선택해 줍니다. 
set09.png 

그리고  [Finish]를 눌러서  소스를 생성합니다. 


--------------------  소스 -----------------------------

public class Setting extends PreferenceActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        addPreferencesFromResource(R.xml.setting);
    }

}
------------------------------------------------------

빨간색 부분만 추가해 주시면  된답니다. 




4.   AndroidManifast.xml 에서 activity  추가 

환경설정화면도   activity 이기 때문에  매니패스트 파일에 추가해 주어야 합니다. 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.bolero.texttest"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".TextTest"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    <activity android:name="Setting" android:label="@string/app_name"></activity>
</application>
    <uses-sdk android:minSdkVersion="4" />

</manifest> 



5.  호출 부분 작업 

이제  메인 activity 에서  환경설정 activity를 호출해 주어야 하는데요. 


     private void setting()
    {
        Intent i = new Intent(this, Setting.class);
        
        startActivity(i);
    }

위와 같이  Intent를 만들어서 호출하는 함수하나 만들어서,  원하는 곳 아무곳에서나 호출하면 된답니다. 

이렇게 해서 호출하면   아래와 같이 나온답니다. 

cap01.png 

cap02.png 



6.  환결 설정화면에서  선택한  값 가져오기 

위와 같이 작업한  환경설정값을   안드로이드가  알아서  저장하고 불러오고 한답니다.  
그래서 코드의 어디에서도   저장하거나  로드하는 코드는 없구요. 

이렇게  만들어준 환경설정 값은  getDefaultSharedPreferences 를   통해서 읽어 올 수 있답니다. 

환경 설정도 하나의 activity  이기 때문에   메인에서 환경설정으로 가면,   메인의 화면을 가리게 되어서  OnPause 가 호출되고, 

환경설정에서  돌아오면 때 (환경설정이 닫히면 ),   메인의  OnResume 이 호출 된답니다. 

그러므로,  OnResume에서  환경설정에서 지정한 값을 읽어 오면 된답니다. 


@Override
    protected void onResume() {
        super.onResume();
        
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
        
        boolean check_value =  pref.getBoolean("keycheck", false);
        String list_value = pref.getString("keylist", "");

        
        m_vt2.setText("List = " + list_value + ", check = " + check_value);
    }

위의 파란 글씨 부분이  환경 설정값을 가져오는 부분이랍니다. 


이렇게  구성한 환경 설정을   프로그램을  종료했다가 다시 실행 하여도  유지가 된답니다. 


수고하세요 ^^

여기에 블루투스 관련글 참조

http://docs.androidside.com/docs/guide/topics/wireless/bluetooth.html

출처한글 : http://techblog.textcube.com/153

안드로이드는 블루투스 프로토콜 스택을 포함하고 있기 때문에 블루투스 디바이스들과 무선으로 데이터를 교환할 수 있다. 어플리케이션 프레임웍은 안드로이드 블루투스 API를 사용해 블루투스에 억세스 할 수 있다. 블루투스 API를 사용하면 다음과 같은 작업을 할 수 있다.

  • 다른 블루투스 디바이스 검색
  • 페어링 된 블루투스 디바이스를 위한 로컬 블루투스 아답터 퀘리
  • RFCOMM 채널 설정
  • SDP(Service Discovery Protocol)을 통한 다른 디바이스와의 커넥션
  • 양방향 데이터 전송
  • 복수 커넥션 관리


- 기초

이 문서는 블루투스를 사용해 통신하는데 필요한 4가지 주요 태스크(블루투스 셋업, 페어링 되어 있거나 주변에 있는 기기 검색, 디바이스와 연결, 디바이스간 데이터 전송)를 수행하기 위해 안드로이드 블루투스 API를 어떻게 사용하는가를 설명한다. 
모든 블루투스 API는 android.bluetooth 패키지에 들어있다.  다음은 블루투스 연결을 만드는데 필요한 클래스들의 요약이다.

  • BluetoothAdapter - 로컬 블루투스 아답터 하드웨어를 나타낸다. BluetoothAdapter는 모든 블루투스를 통한 상호작용의 엔트리포인트이다. 이 객체를 사용해서 다른 블루투스 디바이스 찾기, 페어링 된 디바이스 퀘리, 알려진 MAC address를 사용해 BluetoothDevice 인스턴스 얻기, 다른 디바이스에서 부터의 통신 요구를 기다리기 위한 BluetoothServerSocket 만들기를 할 수 있다.
  • BluetoothDevice - 상대방의 블루투스 디바이스를 나타낸다. 이 객체를 사용하면 BluetoothSocket을 통해 상대방 디바이스와 커넥션을 요구하거나 이름, 주소, 클래스, 페어링 상태등의 정보를 퀘리할 수 있다.
  • BluetoothSocket - 블루투스 소켓을 위한 인터페이스를 나타낸다. 어플리케이션이 InputStream과OutputStream을 사용해서 다른 블루투스 디바이스와 데이터 교환을 할 수 있는 연결 포인트이다.
  • BluetoothServerSocket – Incoming 리퀘스트를 위해 listen하고 있는 오픈된 서버소켓(TCPServerSocket과 유사)을 나타낸다. 두대의 안드로이드 디바이스를 연결하기 위해 한쪽의 디바이스는 이 클래스를 사용해서 서버소켓을 오픈해야만 한다. 원격 블루투스 디바이스가 디바이스에 커넥션 리퀘스트를  때 BluetoothServerSocket은 커넥션이 연결되면 연결된 BluetoothSocket을 리턴해준다.
  • BluetoothClass - 블루투스 디바이스의 일반적 특성과 기능을 나타낸다. 이 클래스는 디바이스의 디바이스 클래스와 서비스를 정의하는 읽기 전용 속성의 집합이다.


블루투스 퍼미션

어플리케이션에서 블루투스 기능을 사용하려면 최소한 BLUETOOTH와 BLUETOOTH_ADMIN 둘중에 하나의 블루투스 퍼미션을 선언해줘야 한다. 커넥션 요구, 커넥션 accept, 데이터 전송등의 블루투스 통신을 하기 위해서는 BLUETOOTH 퍼미션이 필요하다.
디바이스 discovery를 시작하거나 블루투스 설정을 조작하려면 BLUETOOTH_ADMIN 퍼미션이 필요하다. 
BLUETOOTH_ADMIN 퍼미션을 사용하려면 BLUETOOTH 퍼미션도 꼭 있어야만 한다. 매니페스트 파일에 블루투스 퍼미션을 선언해준다. 

<uses-permission android:name="android.permission.BLUETOOTH" /> 
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> 




- 블루투스 셋업

어플리케이션이 블루투스로 통신을 하기 전에 디바이스가 블루투스를 지원하는지 확인할 필요가 있다. 그리고 블루투스를 지원한다면 활성화 되었는지도 확인해줘야 한다. 만일 블루투스를 지원하지 않으면 블루투스 기능을 비활성화 시켜야 한다. 블루투스를 지원하지만 활성화 되어 있지 않으면 사용자가 어플리케이션을떠나지 않고 블루투스를 활성화하도록 요구할 수 있다. 이 작업은 BluetoothAdapter를 사용해서  단계로 수행할 수 있다. 

1.BluetoothAdapter 를 얻는다.
모든 블루투스 액티비티를 위해 BluetoothAdapter가 요구된다. BluetoothAdapter를 얻기 위해서는 스태틱 메소드인 getDefaultAdapter()를 호출하면 된다. 그러면 디바이스의 블루투스 아답터를 나타내는 BluetoothAdapter 인스턴스를 리턴한다. 

BluetoothAdapter mBTAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBTAdapter == null) {
    // device does not support Bluetooth
}


2.블루투스 활성화
블루투스가 활성화 되어있는지 확인해야 한다. isEnabled()를 호출해서 블루투스가 현재 활성화되어 있는지 확인한다. 메소드가 false를 리턴하면 블루투스가 비활성화되어 있는 것이다. 블루투스를 활성화 시키려면 ACTION_REQUEST_ENABLE 인텐트로 startActivityForResult()를 호출하면 된다. 

If (!mBTAdapter.isEnabled()) {
    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT) ;
}


그림 1과 같이 블루투스를 활성화하기 위한 퍼미션을 요구하는 대화창이 나타난다. 사용자가 “Yes”를 선택하면 시스템은 블루투스를 활성화시키고 그 과정이 끝나면 어플리케이션으로 포커스가 돌아오게 된다.
블루투스 활성화가 성공하면 액티비티는 onActivityResult() 콜백에서 RESULT_OK를 리턴받게 된다. 블루투스가 에러로 인해 (또는 사용자가 “No”를 선택해서) 활성화되지 못하면 RESULT_CANCELED가 리턴된다. 옵션으로 블루투스 상태가 변경될  마다 시스템이 브로드캐스하는 ACTION_STATE_CHANGED 인텐트를 listen하도록 할 수도 있다. 

- 디바이스 검색

BluetoothAdapter를 사용하면 디바이스 discovery 또는 페어링 된 디바이스 목록을 퀘리해서 원격 블루투스 디바이스를 찾을 수 있다.
디바이스 discovery는 주변의 활성화 된 블루투스 디바이스를 찾고 각각에 대한 정보를 요구하는 검색 단계이다. 하지만 통신가능 범위에 들어있는 블루투스 디바이스라 해도 현재 discoverable 하도록 활성화 되어 있어야만 discovery 요구에 응답한다. 디바이스가 discoverable 상태인 경우 discovery 요구에 디바이스 이름, 클래스, MAC 주소같은 정보를 공유함으로서 응답한다. 이 정보를 사용해서 discovery를 수행한 디바이스는 발견된 디바이스에 커넥션을 시작하도록 선택할 수 있다.
일단 원격 디바이스와 처음으로 연결이 이루어지면 자동으로 사용자에게 페어링을 할 것인가 물어보게 된다.  디바이스 페어링이 이루어지면 상대 디바이스에 대한 기본 정보(디아비스 이름, 클래스, MAC 주소 등)가 저장되고 그 내용은 블루투스 API를 통해 읽을 수 있게 된다. 이미 알고 있는 원격디바이스의 MAC 주소를 사용하면 아무때나 (물론 해당 디바이스가 통신 가능범위에 있다는 가정 하에) discovery를 수행할 필요 없이 바로 커넥션 과정을 시작할 수 있다. 
페어링과 연결된것의 차이점은 잘 알고 있어야 한다. 페어링은 두 디바이스가 각자 상대방의 존재를 알고 있고 인증과정에 사용할 link-key를 공유하고 있어 서로간에 암호화 된 연결을 설정할 수 있다는걸 의미한다. 연결된것은 디바이스가 현재 RFCOMM 채널을 공유하고 있어 서로 데이터를 전송할 수 있는 상태를 의미한다.
현재 안드로이드 블루투스 API는 RFCOMM 커넥션을 설정하기 전에 디바이스가 페어링 되어야만 한다. (블루투스 API에서 암호화된 커넥션을 시작하려고 할 때 페어링이 자동을 이루어진다.)
다음의 섹션은 페어링 된 디바이스를 찾거나, 디바이스 discovery를 사용해 새 디바이스를 찾는 방법을 설명한다. 
주: 안드로이드 디바이스는 기본적으로 not discoverable 상태이다. 시스템 설정을 통해 짧은 시간동안 디바이스를 discoverable 상태로 만들거나 어플리케이션에서 직접 discoverable 상태로 만들어 줄 수 있다.

- 페어링 된 디바이스 퀘리

디바이스 discovery를 수행하기 전에 원하는 디바이스가 이미 페어링 되어 있는가 확인해 볼 필요가 있다.  확인하기 위해서 getBondedDevices()를 호출하면 된다. 그러면 페어링 된 디바이스들의 집합인 BluetoothDevices 를 돌려준다. 예를 들어 페어링 된 모든 디바이스를 퀘리한 다음 ArrayAdapter를 사용해 페어링 된  디바이스의 이름을 보여줄 수 있다.

Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() <> 0) {
    for (BluetoothDevice device : pairedDevices) {
        mArrayAdapter.add(device.getName() + “\n” + device.getAddress());
    } 
}


BluetoothDevice 객체에서 연결을 시작하기 위해 필요한 정보는 MAC address만 있으면 된다. 위의 예제에서 이 정보는 사용자에게 보여지는 ArrayAdapter의 일부분에 저장되어 있다. MAC 주소는 나중에 연결을 시작하기 위해 추출할수도 있다. 

- 디바이스 discovery

디바이스 discovery를 시작하려면 startDiscovery()를 호출하면 된다. 이 과정은 비동기식이라 메소드를 호출하면 discovery가 성공적으로 시작되었나 결과를 알려주는 boolean값을 곧바로 돌려준다. Discovery과정은 보통 12초간의 inquiry scan후 발견된 각 디바이스에 대해 이름을 가져오기 위한 page scan으로 이루어진다.
어플리케이션은 각 발견된 디바이스에 대한 정보를 받기 위해  ACTION_FOUND 인텐트를 위한 BroadcastReceiver를 등록해야만 한다. 각 디바이스마다 시스템이 ACTION_FOUND 인텐트를 브로드캐스트한다. 이 인텐트는 각각 BluetoothDevice와  BluetoothClass가 들어있는 EXTRA_DEVICE와 EXTRA_CLASS 필드를 전달한다. 예제로 디바이스가 발견되었을 때 브로드캐스트를 처리하는 핸들러를 등록하는 방법이다.

Final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            mArrayAdapter.add(device.getName() + “\n” + device.getAddress());
        }
    }
};

BroadcastReceiverIntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND;
registerReceiver(mReceiver, filter);


커넥션을 시작하기 위해 BluetoothDevice 객체에서 필요한 정보는 MAC 주소뿐이다. 이 예에서는 사용자에게 보여지는 ArrayAdapter의 일부분에 저장되어 있다. 

주의: 디바이스  discovery를 수행하는건 블루투스 아답터에게 매우 부담이 큰 작업으로 매우 많은 리소스를 요구한다. 커넥션 할 디바이스를 찾았다면 커넥션을 시작하려고 시도하기 전에  cancelDiscovery()를 호출해서 discovery를 멈춰야 한다. 또한 이미 다른 디바이스와 커넥션 되어 있으면   discovery과정동안  대역폭이 활 떨어질수도 있기 때문에 커넥션 된  상태에서는 discovery를 하지 않아야 한다.                                                           
- Discoverable 활성화

다른 디바이스가 자신의 디바이스를 검색할 수 있도록 해 주려면 startActivityForResult(Intent, int)에 ACTION_REQUEST_DISCOVERABLE 액션 인텐트를 넣어 호출해주면 된다. 이 메소드를 호출하면 어플리케이션을 멈추지 않고 시스템 설정을 통해 discoverable 모드를 활성화 하도록 요청한다. 기본적으로 디바이스는 120초동안 discoverable 모드로 있게 된다. EXTRA_DISCOVERABLE_DURATION 인텐트 extra를 추가해서 시간을 바꿔줄 수 있다. (최대 300초)

Intent discoverableIntent = new Intent(BluetoothAdpater.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);




그림 2와 같은 다이얼로그가 떠서 사용자에게 디바이스를 discoverable 상태로 만들도록 허가할 것인지 묻는다. “Yes”를 선택하면 디바이스는 정해진 시간동안 discoverable상태가 된다. 액티비티는 result code에 디바이스가 discoverable되는 시간값이 들어가서 onActivityResult() 콜백을 호출받게 된다. 사용자가 “No”를 선택하거나 에러가 발생하면 result code는 Activity.RESULT_CANCELLED가 된다.
디바이스는 discoverable 시간동안 아무 반응이 없이 조용히 있는다. 만일 discoverable모드가 변경될 때 통보를 받고 싶으면 ACTION_SCAN_MODE_CHANGED 인텐트에 대한 BroadcastReceiver를 등록할 수 있다. 이 인텐트에는 각각 이전 스캔모드와 변경된 새 스캔모드가 들어있는 EXTRA_PREVIOUS_SCAN_MODE와 EXTRA_SCAN_MODE라는 extra 필드를 가지고 있다. 각 필드에 들어갈  있는 값은 SCAN_MODE_CONNECTABLE_DISCOVERABLE,  SCAN_MODE_CONNECTABLE,  SCAN_MODE_NONE으로 각각 discoverable 모드, discoverable은 아니지만 커넥션을 받아들일 수는 있는 모드, discoverable도 아니고 커넥션도 받아들일 수 없는 모드를 나타낸다.
원격 디바이스와 커넥션을 시작하고 싶은 경우는 자신의 디바이스를 discoverable모드로 만들 필요는 없다. 원격 디바이스가 커넥션을 시작하기 전에 디바이스를 발견해야만 하기 때문에 내 디바이스의 discoverable 모드를 활성화 시키는건 어플리케이션이 서버소켓을 사용해서 incoming 연결을 accept할 때만 필요하다.

- 디바이스 커넥션

두 디바이스에서 실행되는 어플리케이션간에 커넥션을 만들기 위해서는 서버쪽과 클라이언트쪽 메카니즘을 모두 구현해 줘야만 한다. 한 디바이스는 서버소켓을 열어줘야 하고 다른 디바이스가 서버 디바이스의 MAC 주소를 사용해서 커넥션을 시작해야만 하기 때문이다. 서버와 클라이언트는 같은 RFCOMM 채널에 각각 커넥션 된 BluetoothSocket을 가지고 있을 때 서로 커넥트 된 것으로 간주된다. 이 지점에서 각 디바이스는 입, 출력 스트림을 얻어 데이터 전송을 시작할 수 있다. 이 섹션에서는 두 디바이스간에 커넥션을 시작하는 방법에 대해서 설명한다.
서버 디바이스와 클라이언트 디바이스는 서로 다른 방법으로 필요한 BluetoothSocket을 얻는다. 서버는 incoming 연결이 accept될 때 소켓을 받게 된다. 클라이언트는 서버로의 RFCOMM 채널을 열 때 소켓을 받게 된다.



한가지 구현 테크닉은 두 디바이스를 모두 서버로 동작하도록 하기 위해 서버소켓을 열고 커넥션을 기다리는 것이다. 그러면 어느 디바이스건 클라이언트로서 상대 디바이스로 커넥션을 시작할 수 있다. 다른 방법으로는 한 디바이스는 명시적으로 서버로 지정해 서버소켓을 열고 커넥션을 기다리고 다른 디바이스는 단순히 클라이언트로 커넥션을 시작할 수 있다.
주) 두 디바이스가 미리 페어링 되어 있지 않으면 안드로이드 프레임웍은 그림 3과 같이 자동으로 페어링을 요구하는 다이얼로그를 띄워준다. 그러므로 디바이스를 커넥트 하려고 할 때 어플리케이션은 디바이스가 미리 페어링 되어 있는지 여부를 걱정할 필요가 없다. RFCOMM 커넥션 시도는 사용자가 성공적으로 페어링을 마치거나 페어링을 거부하거나 또는 어떤 이유로건 페어링이 실패할 때 까지 블럭된다.

서버로 동작
두 디바이스를 커넥트하려고 할 때 하나의 디바이스는 BluetoothServerSocket을 열어 서버로 동작해야만 한다. 서버소켓의 목적은 incoming 커넥션 요구를 기다리다 accept되면 커넥션 된 BluetoothSocket을 제공해 주는 것이다. BluetoothServerSocket에서 BluetoothSocket이 얻어지고 더 이상의 커넥션을 accept할 필요가 없으면  BluetoothServerSocket은 제거해도 된다. 

UUID란... 
Universally Unique IDentifier(UUID)는 유일하게 정보를 식별하는데 사용하기 위한 128비트 포맷의 표준화 된 문자열 ID이다. UUID의 포인트는 이 숫자가 충분히 크기 때문에 랜덤하게 아무 숫자나 골라도 다른 UUID들과 겹치지 않는다는 것이다. 여기서는 어플리케이션의 블루투스 서비스를 식별하는데 사용된다. 어플리케이션에 사용할 UUID를 얻기 위해서 인터넷상의 여러가지 랜덤 UUID 생성기중에 하나를 사용할 수 있고 fromString(String)으로 UUID를 초기화 하면 된다.
서버소켓을 셋업하고 연결을 accept하는 기본적인 절차이다.

1.listenUsingRfcommWithServiceRecord(String, UUID)를 호출해서 BluetoothServerSocket을 얻어온다.
스트링은 서비스에 대한 식별할 수 있는 이름으로 시스템이 디바이스의 새 SDP 데이터베이스 엔트리에 자동으로 그 이름을 기록한다. UUID 또한 SDP엔트리에 포함되어 클라이언트와 커넥션 agreement를 위한 기초가 된다. 즉 클라이언트가 디바이스와 커넥션하려고 시도할 때 커넥션하길 원하는 서비스를 유일하게 식별하는 UUID를 제공한다. 커넥션이 이뤄지기 위해서는 이 UUID가 일치해야만 한다.
 
2.accept()를 호출해서 커넥션 요구를 listen하기 시작한다.
이 메소드는 블럭킹 호출이다. 커넥션이 accept되거나 익셉션이 발생해야만 리턴된다. 리모트 디바이스가 listen하고 있는 서버소켓에 등록한 UUID와 일치하는 커넥션 요구에만 연결이 만들어진다. 성공하면 accept()는 커넥션 된 BluetoothSocket을 리턴한다.
 

3.더 이상의 추가 커넥션이 필요하지 않으면 close()를 호출한다.
이 메소드를 호출하면 서버소켓과 관련된 리소스를 release한다. 하지만 accept()가 리턴한 커넥션 된 BluetoothSocket은 닫지 않는다. TCP/IP와 달리 RFCOMM은 클라이언트에서 한번에 하나의 커넥션만 허용하기 때문에 대부분의 경우에 커넥션이 만들어지면 곧바로 BluetoothServerSocket을 close()하는게 합리적이다.

accept()는 블럭킹 메소드라 어플리케이션의 다른 동작을 막기 때문에 메인 액티비티 UI 스레드에서 호출하면 안된다. 일반적으로 새로운 스레드에서 BluetoothSocket이나 BluetoothServerSocket에 관련된 모든 작업을 처리하는게 합리적이다. 다른 스레드에서 BluetoothServerSocket의 accept() 같이 블럭킹  것을 취소하고 바로 리턴하도록 하려면 close()를 호출하면 된다. 그리고 BluetoothServerSocket 또는 BluetoothSocket의 모든 메소드는 스레드-세이프하다.

예제) incoming 연결을 accept하는 서버 컴포넌트를 위한 간단한 스레드
private class AcceptThread extends Thread {
    private final BluetoothServerSocket mmServerSocket;
    
    public AcceptThread() {
        // Use a temporary object that is later assigned to mmServerSocket,
        // because mmServerSocket is final
        BluetoothServerSocket tmp = null;
        try {
            // MY_UUID is the app's UUID string, also usedby the client code
            tmp =mAdapter.listenUsingRfcommWithServiceRecord(NAME,MY_UUID);
        } catch (IOException e) { }
        mmServerSocket = tmp;
    }
    public void run() {
        BluetoothSocket socket = null;
        // Keep listening until exception occurs or a socket is returned 
        while (true) {
            try {
                socket = mmServerSocket.accept();
            } catch (IOException e) { 
                break;
            }
            // If a connection was accepted
            if (socket != null) {
                // Do work to manage the connection (in a separate thread)
                manageConnectedSocket(socket);
                mmServerSocket.close();
                break; 
            }
        }
    }
    /** Will cancel the listening socket, and cause the thread to finish */
    public void cancel() {
        try {
            mmServerSocket.close();
        } catch (IOException e) { }
    }
}

이 예제에서 한개의 incoming 커넥션만 필요하기 때문에 커넥션이 accept되고 BluetoothSocket이 얻어지자 마자 어플리케이션은 얻은 BluetoothSocket을 별도의 스레드로 보낸 다음 BluetoothServerSocket을 닫고 루프를 빠져나온다. 
accept()가 BluetoothSocket을 리턴할 때 소켓은 이미 커넥션 되어 있기 때문에 따로 connect()를 호출할 필요는 없다. manageConnectedSocket()은 어플리케이션에서 데이터 전송을 위한 스레드를 시작하는 fictional 메소드이다. 
일반적으로 incoming 커넥션을 listen하는게 끝나면 곧바로 BluetoothServerSocket을 닫아준다. 이 예제에서도 BluetoothSocket이 얻어지자 마자 close()를 호출했다. 또한 listen하고 있는 서버소켓을 멈출 필요가 있을 때 private BluetoothSocket을 닫을  있는 public 메소드를 스레드에서 제공하기도 한다. 

클라이언트로 동작 
원격 디바이스와 커넥션을 시작하려면 우선 원격 디바이스를 나타내는 BluetoothDevice 객체를 얻어야만 한다. 그리고 나면 BluetoothDevice를 사용해서 BluetoothSocket을 얻어 커넥션을 시작한다.

기본적인 절차이다.

1.BluetoothDevice를 사용해서 createRfcommSocketToServiceRecord(UUID)를 호출해서 BluetoothSocket을 얻는다.
이 호출은 BluetoothDevice에 연결하는 BluetoothSocket을 초기화한다. 여기서 건네지는 UUID는 서버 디바이스가 자신의 BluetoothServerSocket(listenUsingRfcommWithServiceRecord(String, UUID)를 사용해서)을 열었을 때 사용한 UUID와 일치해야만 한다. 동일한 UUID를 사용하는건 UUID스트링을 어플리케이션 코드에 하드코딩하고 서버와 클라이언트 양쪽 코드에서 그걸 참조하면 되는 간단한 문제이다.

2.connect()를 호출해서 연결을 시작한다.
시스템은 UUID를 매치하기 위해 원격 디바이스 SDP lookup을 수행한다. Lookup이 성공하고 원격 디바이스가 커넥션을 accept하면 연결동안 사용할 RFCOMM채널을 공유하고 connect()가 리턴한다.  메소드는 블럭킹 호출이다. 어떤 이유로건 커넥션이 실패하거나 connect() 메소드가 time out (약 12초)이 되면 exception을 발생한다.
connect()는 블럭킹 호출이기 때문에 이 커넥션 절차는 언제나 메인 액티비티 스레드와 독립된 별개의 스레드에서 수행되어야만 한다.
주: connect()를 호출할 때 디바이스는 언제나 디바이스 discovery를 수행하고 있지 않는지 확인해야만 한다. Discovery가 진행중이면 커넥션 시도는 확연히 느려져서 실패할 가능성이 커진다.

예제) Bluetooth 커넥션을 시작하는 스레드

private class ConnectThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final BluetoothDevice mmDevice;
    public ConnectThread(BluetoothDevice device) {
        // Use a temporary object that is later assigned to mmSocket,
        // because mmSocket is final
        BluetoothSocket tmp = null;
        mmDevice = device;
        // Get a BluetoothSocket to connect with the given BluetoothDevice
        try {
            // MY_UUID is the app's UUID string, also used by the server code 
            tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) { }
        mmSocket = tmp;
    }

    public void run() {
        // Cancel discovery because it will slow down the connection 
        mAdapter.cancelDiscovery();
        try {
            // Connect the device through the socket. This will block
            // until it succeeds or throws an exception
            mmSocket.connect();
        } catch (IOException connectException) {
            // Unable to connect; close the socket and get out 
            try {
                mmSocket.close();
            } catch (IOException closeException) { }
            return;
        }
        // Do work to manage the connection (in a separate thread)
        manageConnectedSocket(mmSocket);
    }
    /** Will cancel an in-progress connection, and close the socket */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
}

cancelDiscovery()는 커넥션이 만들어지기 전에 호출되는걸 볼 수 있다. 커넥션이 되기 전에라도 언제나 호출할 수 있고 실제적으로 실행 여부를 확인하지 않고 호출해도 안전하다. (하지만 그래도 상태를 확인하고 싶으면 isDiscovering()을 사용하면 된다.) manageConnectedSocket()은 데이터 전송을 위한 스레드를 시작하는 어플리케이션에 있는 fictional 메소드이다. 
BluetoothSocket이 끝나면 clean up을 위해 언제나 close()를 호출해줘야 한다. 이 메소드를 호출해 줌으로서 곧바로 커넥션 된 소켓을 닫고 내부 리소스를 clean up 하게 된다. 

- 연결 관리

두 디바이스를 성공적으로 커넥션하게 되면 각 디바이스는 커넥션 된 BluetoothSocket을 가지게 된다. 이 소켓을 통해 디바이스간에 데이터를 교환할 수 있게 된다. BluetoothSocket을 사용해서 임의의 데이터를 전송하기 위한 일반적 절차는 매우 간단하다. 

1.각각 getInputStream()과 getOutputStream()을 사용해 소켓을 통한 전송을 처리할 InputStream과 OutputStream을 얻는다.
2.read(byte[])와 write(byte[])를 사용해서 데이터를 읽고 쓴다.

물론 implementation을 위해 고려해야  세부사항들이 있다. 먼저 무엇보다 모든 읽고 쓰기를 위한 별도의 스레드를 사용해야 한다. 이건 read(byte[])와 write(byte[])는 모두 블럭킹 호출이기 때문에 매우 중요하다.read(byte[])는 스트림에서 무언가 읽을게 있을때까지 블럭되어 있는다. write(byte[])는 일반적으로는 블럭되지 않지만 원격 디바이스가 충분히 빠르게 read(byte[])를 호출하지 않아 버퍼가 꽉 차는 경우 플로우 컨트롤을 위해 블럭될수도 있다. 그러므로 스레드의 메인 루프는 InputStream으로부터 읽기 전용으로 사용되어야 한다. 스레드의 분리된 public 메소드가 OutputStream으로 쓰기를 시작하도록 사용될  있다. 

예제) 
private class ConnectedThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final InputStream mmInStream; 
    private final OutputStream mmOutStream;

    public ConnectedThread(BluetoothSocket socket) { 
        mmSocket = socket;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;
        // Get the input and output streams, using temp objects because
        // member streams are final
        try {
            tmpIn = socket.getInputStream(); 
            tmpOut = socket.getOutputStream();
        } catch (IOException e) { }
        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }

    public void run() {
        byte[] buffer = new byte[1024];    // buffer store for the stream
        int bytes; // bytes returned from read()
        // Keep listening to the InputStream until an exception occurs
        while (true) {
            try { 
                // Read from the InputStream
                bytes = mmInStream.read(buffer); 
                // Send the obtained bytes to the UI Activity
                mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
                        .sendToTarget();
            } catch (IOException e) {
                break;
            }
        }
    }
    /* Call this from the main Activity to send data to the remote device */
    public void write(byte[] bytes) {
        try {
            mmOutStream.write(bytes);
        } catch (IOException e) { }
    }

    /* Call this from the main Activity to shutdown the connection */
    public void cancel() { 
        try {
            mmSocket.close(); 
        } catch (IOException e) { }
    } 
}

컨스트럭터가 필요한 스트림을 얻고 한번 실행되면 스레드는 InputStream을 통해 들어오는 데이터를 기다린다. read(byte[])가 스트림에서의 데이터를 리턴하면 그 데이터는 부모 클래스의 Handler 멤버를 사용해 메인 액티비티로 보내진다. 그리고 다시 스트림에서 데이터를 읽기 위해 기다리기 위해 돌아간다. Outgoing 데이터를 보내는건 단순히 메인 액티비티에서 스레드의 write() 메소드를 호출해 전송할 데이터를 전달해주면 된다.

스레드의 cancel() 메소드는 아무때나 BluetoothSocket을 닫아 connection을 멈출 수 있기 때문에 중요하다. 메소드는 블루투스 connection 사용이 끝나면 언제나 호출되어야 한다.

-------------------------------------------------------------------------------------

핸트폰과 PC 블루투스 연결

핸드폰과 PC 사이에 파일을 전송하기 위해서는 먼저 PC에 핸드폰을 블루투스 장치로 추가 해 주어야 합니다. 이를 위해,

  • 알림 영역에 있는 블루투스 아이콘을 클릭한 후 장치 추가를 클릭, 
     
  • 아래와 같은 장치 추가 창이 열리고 자동으로 핸드폰 장치를 찾아 줍니다. (핸드폰에서 블루투스 전원 설정을 ON 으로 해 두어야 PC에서 자동으로 찾음) 핸드폰 아이콘을 클릭한 후 다음 버튼 클릭, 

  • 아래와 같은 번호가 표시 되면, 핸드폰에 연결할 것인지를 묻는 메시지가 뜹니다. 핸드폰에서 확인에 해당하는 버튼을 클릭하면 번호를 입력하는 상자가 뜹니다. 번호를 입력한 후 핸드폰에서 확인에 해당하는 버튼을 클릭해 줍니다. 

  • 잠시 기다리면 아래와 같은 메시지가 뜨면서 핸드폰 장치 추가가 마무리 됩니다. 

핸드폰에서 PC로 전화 번호부 보내기

  • 컴퓨터 알림 영역에 있는 블루투스 아이콘을 클릭한 후 '파일 받기'를 클릭하면 아래와 같이 파일을 받을 수 있도록 연결 대기 화면이 뜹니다. 

  • 핸드폰에서 블루투스-데이터전송-전화번호부 전송을 차례로 클릭한 후 전화번호부 전체 선택 (또는 필요한 전화번호만 선택)을 하고 나면 전송 장치 선택 화면에 PC 이름이 뜹니다. 연결에 해당하는 버튼을 클릭하면, 컴퓨터 화면에 아래처럼 파일 수신 화면이 자동으로 표시됩니다. 

  • 파일을 다 받고 나면 아래 화면처럼 파일을 저장할 곳을 지정하는 화면이 뜹니다. 적당한 위치를 지정한 후 마침 버튼을 클릭하면 지정한 위치에 전화번호부가 저장됩니다.
     

만약, 휴대폰과 PC 연결이 잘 되지 않는다면, 제어판에서 블루투스 설정을 확인해 보시기 바랍니다.

제어판을 연후 제어판의 검색상자에 bluetooth 를 입력한 후 'Bluetooth 설정변경' 을 클릭하여 Bluetootht 설정 창을 연 후, 옵션탭에서  'Bluetooth 장치가 이 컴퓨터에 연결하도록 허용'에 체크가 되어 있는 지 확인해 보시기 바랍니다. 이를 체크 했음에도 연결이 잘 되지 않는다면, 'Bluetooth 장치가 이 컴퓨터를 찾을 수 있도록 허용'에도 체크를 한 후 연결해 보시기 바랍니다. 단,  'Bluetooth 장치가 이 컴퓨터를 찾을 수 있도록 허용'에 체크가 된 경우 보안에 문제가 생길 수도 있기 때문에 필요한 파일 전송을 마친 후 에는 체크를 해제하는 것이 안전합니다.

블루투스 설정변경

Note:

  • 블루투스 기능을 이용하여 전화번호부를 전송한 경우 그룹 설정등은 제대로 전송되지 않는 경향이 있습니다.
  • 사진 크기가 큰 경우 제대로 전송이 안 되는 경우도 있습니다.
  • 여러 핸드폰을 이용해 보았지만, 블루투스를 이용한 파일 전송이 품질이 아주 만족 스럽지는 않았습니다. 핸드폰 제조사에서 제공하는 매니저 프로그램을 다운 받아 이용하는 것이 가장 확실하긴 합니다.
  • 맥이나 리눅스용 드라이버나 매니저 프로그램을 제공해 주지 않는 국내 핸드폰 제조사의 특성상, 블루투스가 설치된 맥이나 리눅스 이용자는 블루투스 기능을 이용하여 기본적인 전화번호부, 파일 전송을 할 수 있습니다.

-------------------------------------------------------------------------------------

블루투스 장비와 연동해 데이터를 받아와야 한다.

통신 시간이 중요하다. 느리면 쓸 이유가 없다.

시리얼 통신 처럼 사용하고 싶다.

 

정보

지원가능 프로파일

시리얼

실제 블루투스 사용이 잘 안되는 경우가 많이 있단다. (블루투스 키보드를 이용하면..., 2010.04.17)

블루트스 에뮬에서는 안된다. (출처 : 안드로이드 블루투스 관련, 2010.03.02)

블루투스를 이용한 테더링 잘 된다 VS 안된다. (출처 : PDANet 휴대폰을 모뎀으로 2탄 Bluetooth 연결편, 2010.04.04, 안드로이드 모토로이 USB 테더링 후기, 2010.02.24)

 

개념 탑제 필요

  • 블루투스 버전간 차이
  • 각종 프로파일 지원 여부에 따른 영향
  • 페어링

---------------------------------------------------------------------------------------

안드로이드의 BlueTooth는 1.5, 1.6버젼에서는 A2DP, AVRCP(AV Remote Control), HSP(Headset), HFP(Hands Free) 정도만 지원했다. 안드로이드 2.0 버젼부터 OOP(Push Profile), PBAP(Phone Book Access Profile) 등을 지원한다고 한다.

 

안드로이드에서 BlueTooth를 사용하려면 Vendor에서 정의하는 BoardConfig.mk에서 BOARD_HAVE_BLUETOOTH를 true로 설정해야 한다.

 

기본 구조에 대하여 참고할만한 곳은 다음과 같다.

 

http://sites.google.com/a/android.com/opensource/projects/bluetooth-faq

 

기본 구조

 

 

 

system server 와  BlueZ 와의 인터페이스를 담당하는 D-Bus는 다음을 참고한다.

 

http://www.freedesktop.org/wiki/Software/dbus

http://daeji.tistory.com/entry/D-BUS

http://bebop.emstone.com/research/tech/dbus/dbus_overview

 

아직 확실하지는 않지만

BT Power on/off 를 담당하는 소스는 다음 파일 같다.

system/bluetooth/bluedroid/bluetooth.c

 

실제 하드웨어를 컨트롤하는 부분은 보이지 않으며 함수 Call에 따라 내부 설정 등을 변경해 놓는다.

하드웨어 컨트롤 관련된 부부은 2.01에서는 별도로 추가된 것으로 보이며 이는 1.6 버젼까지는 이 쪽에 대충 떄려 넣어야 할 것 같다.

 

Make파일을 보면 공유 라이브러리 libbluedroid.so 파일로 만든다.

이 라이브러리는 Java에서 사용 가능하도록 다음에서 라이브러리를 정의한다.

frameworks/base/core/jni/Android.mk

 

이를 보면 결론적으로 BlueTooth와 관련된 JNI 관련 파일은 다음 세 파일이다.

android_server_BlueToothA2dpService.cpp

android_server_BlueToothDeviceService.cpp

android_server_BlueToothEventLoop.cpp

 

그 외 파일들은

 android_bluetooth_Database.cpp
 android_bluetooth_HeadsetBase.cpp
 android_bluetooth_common.cpp

dbus 관련 함수


 android_bluetooth_BluetoothAudioGateway.cpp
 * android_bluetooth_RfcommSocket.cpp

 * android_bluetooth_BluetoothSocket.cpp 

socket 통신 관련 (write, read, ...)


 android_bluetooth_ScoSocket.cpp

Sco socket 통신 관련 (init, connect, accept, close ...)

 

당연한 얘기지만 BlueTooth의 A2DP, HSP, HFP 등을 사용하면 오디오 출력에 영향을 미치므로

framework/base/libs/audioflinger 쪽도 영향을 받는다.

 

BlueZ에 대한 소스는 external/bluez 에 있다. 

 

참고할만한 기사

http://ko.broadcom.com/press/release.php?id=s363853

출처 : http://goldenking.tistory.com/10



Bluetooth Permissions


In order to use Bluetooth features in your application, you need to declare at least one of two Bluetooth permissions: BLUETOOTH and BLUETOOTH_ADMIN.

You must request the BLUETOOTH permission in order to perform any Bluetooth communication, such as requesting a connection, accepting a connection, and transferring data.

You must request the BLUETOOTH_ADMIN permission in order to initiate device discovery or manipulate Bluetooth settings. Most applications need this permission solely for the ability to discover local Bluetooth devices. The other abilities granted by this permission should not be used, unless the application is a "power manager" that will modify Bluetooth settings upon user request. Note: If you use BLUETOOTH_ADMIN permission, then must also have the BLUETOOTH permission.

Declare the Bluetooth permission(s) in your application manifest file. For example:

 
<manifest ... >
 
<uses-permission android:name="android.permission.BLUETOOTH" />
  ...
</manifest>

See the <uses-permission> reference for more information about declaring application permissions.

Setting Up Bluetooth


Figure 1: The enabling Bluetooth dialog.

Before your application can communicate over Bluetooth, you need to verify that Bluetooth is supported on the device, and if so, ensure that it is enabled.

If Bluetooth is not supported, then you should gracefully disable any Bluetooth features. If Bluetooth is supported, but disabled, then you can request that the user enable Bluetooth without leaving your application. This setup is accomplished in two steps, using the BluetoothAdapter.

  1. Get the BluetoothAdapter

    The BluetoothAdapter is required for any and all Bluetooth activity. To get the BluetoothAdapter, call the static getDefaultAdapter() method. This returns a BluetoothAdapter that represents the device's own Bluetooth adapter (the Bluetooth radio). There's one Bluetooth adapter for the entire system, and your application can interact with it using this object. If getDefaultAdapter() returns null, then the device does not support Bluetooth and your story ends here. For example:

     
    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (mBluetoothAdapter == null) {
       
    // Device does not support Bluetooth
    }
  2. Enable Bluetooth

    Next, you need to ensure that Bluetooth is enabled. Call isEnabled() to check whether Bluetooth is currently enable. If this method returns false, then Bluetooth is disabled. To request that Bluetooth be enabled, callstartActivityForResult() with the ACTION_REQUEST_ENABLE action Intent. This will issue a request to enable Bluetooth through the system settings (without stopping your application). For example:

     
    if (!mBluetoothAdapter.isEnabled()) {
       
    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult
    (enableBtIntent, REQUEST_ENABLE_BT);
    }

    A dialog will appear requesting user permission to enable Bluetooth, as shown in Figure 1. If the user responds "Yes," the system will begin to enable Bluetooth and focus will return to your application once the process completes (or fails).

    The REQUEST_ENABLE_BT constant passed to startActivityForResult() is a locally defined integer (which must be greater than 0), that the system passes back to you in your onActivityResult() implementation as the requestCode parameter.

    If enabling Bluetooth succeeds, your activity receives the RESULT_OK result code in the onActivityResult()callback. If Bluetooth was not enabled due to an error (or the user responded "No") then the result code isRESULT_CANCELED.

Optionally, your application can also listen for the ACTION_STATE_CHANGED broadcast Intent, which the system will broadcast whenever the Bluetooth state has changed. This broadcast contains the extra fields EXTRA_STATEand EXTRA_PREVIOUS_STATE, containing the new and old Bluetooth states, respectively. Possible values for these extra fields are STATE_TURNING_ONSTATE_ONSTATE_TURNING_OFF, and STATE_OFF. Listening for this broadcast can be useful to detect changes made to the Bluetooth state while your app is running.

Tip: Enabling discoverability will automatically enable Bluetooth. If you plan to consistently enable device discoverability before performing Bluetooth activity, you can skip step 2 above. Read about enabling discoverability, below.




안드로이드 프로그래밍을 하다보면 설정 액티비티를 만들어야 할때가 있습니다.
설정 액티비티들은 리스트로 구성되어있죠.
리스트를 컨버팅하면서 만든다고 해도, 
텍스트만 나오는 row가 있고, 체크박스고 혼재된 row, 입력창이 들어가야하는  row가 있을 수 있습니다.
이럴때 편하게 사용할 수 있는 방법이 있습니다.

바로 PreferenceActivity 를 상속받아서 만드는것이지요.





보통은 아래의 화면처럼 나옵니다.
분류별 항목별로 묶어 분류바를 기준으로 여러 설정들이 보여지죠.
기본적으로는 텍스트, 큰텍스트와 그 밑의 작은 텍스트, 거기에 더해진 체크박스 입니다.

 
 
 
 


사실 직접 이런 화면을 구성해도 되지만, 
특별히 월등한 UI를 제공하고자 하는 목적이 아니라면 쓰라고 있는 기능을 쓰는것이 빠르고 편리합니다.


PreferenceActivity를 사용하기 위해서는 두가지 단계를 거쳐야합니다. 
 1. 레이아웃 작성
 2. 액티비티 작성

사실 일반적인 액티비티들도 모두 레이아웃을 작성하고 액티비티를 작성하기 때문에 그렇게 어렵게 느껴지진 않습니다.
다만, 화면에 어떻게 보여질지, 어떻게 배치할지에 대한 부분을 배제하고 xml레이아웃을 작성할 수 있기때문에 이 방법은 직접 설정 xml레이아웃을 작성하는것보다 빠르고 월등합니다.


 1. 레이아웃 작성

PreferenceActivity에 사용되는 Layout xml은 일반 Activity에 사용하는 xml 과 작성법이 조금 다릅니다.
일반 액티비티에 사용하는 default layout이 LinearLayout 이라면, 
Preference 액티비티에 사용하는 default layout은 PreferenceScreen 입니다.

PreferenceScreen을 기본으로 하는 Layout XML 파일의 작성은 아래와 같이 할 수 있습니다.


PreferenceActivity에 사용할 xml 파일 생성
 
 
 
 


파일을 생성했으면 이제 작성할 차례입니다.

1
2
3
4
5
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
     
</PreferenceScreen>

위와같은 코드가 작성되어있습니다.
이제 여기에 필요한 기능들을 추가로 작성합니다.

PreferenceScreen 태그 안에는,
복수의 PreferenceCategory가 들어갈 수 있습니다.
또 PreferenceCategory 안에는 복수의 Preference들이 들어갈 수 있습니다.




이 Preference의 태그의 속성들은 간단하게는, 
"키(KEY)"와 "타이틀(TITLE)" / "키(KEY)"와 "타이틀(TITLE)", 그리고 "값(VALUE)"로 이루어져있습니다.
다른 속성들이 많이 있지만, 이것들만 사용해도 어렵지 않게 설정의 기능들을 구현해 낼 수 있습니다.

저는 간단하게 텍스트로 이루어진 카테고리와, 체크박스로 이루어진 카테고리를 추가해 설정 화면을 만들어보려고 합니다.
결과적으로는 아래와 같은 화면을 만들 수 있습니다.

 
 

안드로이드에서 제공해주는 것만으로도 이렇게 그럴듯한 설정화면을 만들었습니다.

이 설정 화면의 XML 코드는 아래와 같습니다.

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
38
39
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
    android:key="setting_activity_top_title"
    android:title="설정  - http://croute.me/340">
     
    <!-- 설정를 구성하는 Layout XML -->
    <!-- @author croute -->
    <!-- @since 2011.02.25 -->
     
    <PreferenceCategory
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:key="setting_activity_account"
        android:title="어플리케이션 정보">
        <Preference
            android:key="setting_activity_id"
            android:title="어플케이션 이름"
            android:selectable="true" />
        <Preference
            android:key="setting_activity_app_version"
            android:title="어플리케이션 버전"      
            android:selectable="true" />
    </PreferenceCategory>
     
    <PreferenceCategory
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:key="setting_activity_pushalarm"
        android:title="알림 설정">
        <CheckBoxPreference
            android:key="setting_activity_autoalarm"
            android:title="자동알림"
            android:summary="어플리케이션 알림이 종료된 경우 자동으로 재실행"
            android:defaultValue="true"/>
        <CheckBoxPreference
            android:key="setting_activity_alarm_reiceive"
            android:title="알림설정" android:defaultValue="true"/>
    </PreferenceCategory>
     
</PreferenceScreen>

눈여겨 볼점은 Preference를 두가지 사용했다는 것.
키와 타이틀을 지정했다는 것입니다.

여기서는 간단한 화면을 구성하기 위해 Preference와 CheckBoxPreference만을 사용했지만, 
(실제로는 EdittextPreference, ListPreference 등 많은 Preference가 있습니다.)





 2. 액티비티 작성

이제 액티비티로 가봅니다.

PreferenceActivity를 처음작성할 때 달라진 부분은 하나뿐입니다.

보통의 Activity에서 레이아웃을 설정할 때 setContentView(R.layout.파일이름)으로 설정한다면,
PreferenceActivity는 레이아웃을 설정할 때 addPreferencesFromResource(R.layout.파일이름)과 같이 합니다.

setContentView -> addPreferenceFromResource

이렇게 바뀐 것 빼고는 액티비티의 기본 설정에서 크게 달라진것은 없습니다.

화면만 보여주기 위해서 액티비티는 아래와 같이 작성하면 됩니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package me.croute.preferenceactivity;
 
import android.os.Bundle;
import android.preference.PreferenceActivity;
 
 
public class PreferenceActivityExample extends PreferenceActivity
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.layout.preference_activity_example);
    }
}

하지만 화면만 보여주는 어플리케이션은 없기때문에 이제부터 체크박스 체크/해제에 따른 이벤트 처리,
어플리케이션 이름등을 클릭했을때의 이벤트 처리에 대해서 알아보도록 하겠습니다.


일반적인 Activity라면 클릭이벤트를 OnClickListener로 받습니다.
하지만 PreferenceActivity는 클릭이벤트를 OnPreferenceClickListener로 받아야 합니다.
일반적인 클릭이 아닌, Preference에 대한 클릭이기 때문입니다.


클릭이벤트는 아래와 같이 구현할 수 있습니다.

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
38
39
40
41
42
43
44
45
46
47
48
49
package me.croute.preferenceactivity;
 
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
 
public class PreferenceActivityExample extends PreferenceActivity implements OnPreferenceClickListener
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.layout.preference_activity_example);
         
        Preference pAppName = (Preference)findPreference("setting_activity_id");
        Preference pAppVersion = (Preference)findPreference("setting_activity_app_version");
        CheckBoxPreference cbpAutoAlarm = (CheckBoxPreference)findPreference("setting_activity_autoalarm");
        CheckBoxPreference cbpAlarmReceive = (CheckBoxPreference)findPreference("setting_activity_alarm_reiceive");
         
        pAppName.setOnPreferenceClickListener(this);
        pAppVersion.setOnPreferenceClickListener(this);
        cbpAutoAlarm.setOnPreferenceClickListener(this);
        cbpAlarmReceive.setOnPreferenceClickListener(this);
    }
 
    @Override
    public boolean onPreferenceClick(Preference preference)
    {
        // 어플리케이션 이름
        if(preference.getKey().equals("setting_activity_id"))
        {
        }
        // 어플리케이션 버전
        else if(preference.getKey().equals("setting_activity_app_version"))
        {
        }
        // 자동알림
        else if(preference.getKey().equals("setting_activity_autoalarm"))
        {
        }
        // 알림 받기
        else if(preference.getKey().equals("setting_activity_alarm_reiceive"))
        {
        }
        return false;
    }
}

여기서 한가지 주의할점은 Preference의 CheckBoxPreference는 자동으로 체크됨을 잡아내서 자신의 상태를 변경합니다.
(기존의 Activity에서 체크박스를 사용하듯이 하면, 체크 되있던걸 돌리고, 체크 안되야 하는걸 체크하는 사태가 일어납니다.)

구현은 여기까지면 충분히 기본적인 설정의 기능들을 사용할 수 있습니다.

이제 클릭이벤트에 각자에 맞는 기능들을 추가해주면됩니다.



구글 플레이스토어 개발자 등록 후, apk를 업로드 할때 이런 메세지가 뜬다면

> zipalign [-f] [-v] <alignment> infile.apk outfile.apk 

> zipalign -f -v 4 c:/test.apk c:/test.apk
 -f:  파일이 존재 하면 갈아엎어버려 
 -v: 자세한 정보 출력 (zipalign 되는 과정을 출력한다.)
 -c: 주어진 파일 정렬 확인 
alignment - 바이트 정렬 경계를 정의하는 정수 (4이면 4byte 32bit 정렬의미)


과정이 주욱~뜨면서 

이 메세지가 뜨면 끝


출처 : http://jyounggoon.tistory.com/34

7. Creating Android Application

Create a new project in your Eclipse IDE by filling the required details.

1. Create new project in Eclipse IDE by going to File ⇒ New ⇒ Android Project and name the Activity class name as MainScreenActivity.

2. Open your AndroidManifest.xml file and add following code. First i am adding all the classes i am creating to manifest file. Also i am adding INTERNET Connect permission.

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
    package="com.example.androidhive"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk android:minSdkVersion="8" />
 
    <application
        android:configChanges="keyboardHidden|orientation"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
 
        <activity
            android:name=".MainScreenActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
 
        <!-- All Product Activity -->
        <activity
            android:name=".AllProductsActivity"
            android:label="All Products" >
        </activity>
 
        <!-- Add Product Activity -->
        <activity
            android:name=".NewProductActivity"
            android:label="Add New Product" >
        </activity>
 
        <!-- Edit Product Activity -->
        <activity
            android:name=".EditProductActivity"
            android:label="Edit Product" >
        </activity>
    </application>
 
    <!--  Internet Permissions -->
    <uses-permission android:name="android.permission.INTERNET" />
 
</manifest>

3. Now create a new xml file under res ⇒ layout folder and name it as main_screen.xmlThis layout file contains two simple buttons to view all products and add a new product.

main_screen.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:gravity="center_horizontal">
 
    <!--  Sample Dashboard screen with Two buttons -->
    <!--  Button to view all products screen -->
    <Button android:id="@+id/btnViewProducts"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="View Products"
        android:layout_marginTop="25dip"/>
 
    <!--  Button to create a new product screen -->
    <Button android:id="@+id/btnCreateProduct"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Add New Products"
        android:layout_marginTop="25dip"/>
 
</LinearLayout>
main screen

4. Open you main activity class which is MainScreenActivity.java and write click events for two button which are mentioned in main_screen.xml layout.

MainScreenActivity.java
package com.example.androidhive;
 
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
 
public class MainScreenActivity extends Activity{
 
    Button btnViewProducts;
    Button btnNewProduct;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_screen);
 
        // Buttons
        btnViewProducts = (Button) findViewById(R.id.btnViewProducts);
        btnNewProduct = (Button) findViewById(R.id.btnCreateProduct);
 
        // view products click event
        btnViewProducts.setOnClickListener(new View.OnClickListener() {
 
            @Override
            public void onClick(View view) {
                // Launching All products Activity
                Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
                startActivity(i);
 
            }
        });
 
        // view products click event
        btnNewProduct.setOnClickListener(new View.OnClickListener() {
 
            @Override
            public void onClick(View view) {
                // Launching create new product activity
                Intent i = new Intent(getApplicationContext(), NewProductActivity.class);
                startActivity(i);
 
            }
        });
    }
}

Displaying All Products in ListView (Read)

5. Now we need an Activity display all the products in list view format. As we know list view needs two xml files, one for listview and other is for single list row. Create two xml files under res ⇒ layout folder and name it as all_products.xml and list_item.xml

all_products.xml

all_products.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
    <!-- Main ListView
         Always give id value as list(@android:id/list)
    -->
    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>
 
</LinearLayout>

list_item.xml

list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >
 
    <!-- Product id (pid) - will be HIDDEN - used to pass to other activity -->
    <TextView
        android:id="@+id/pid"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:visibility="gone" />
 
    <!-- Name Label -->
    <TextView
        android:id="@+id/name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingTop="6dip"
        android:paddingLeft="6dip"
        android:textSize="17dip"
        android:textStyle="bold" />
 
</LinearLayout>

6. Create a new class file and name it as AllProductsActivity.java. In the following code

-> First a request is send to get_all_products.php file using a Background Async task thread.
-> After getting JSON from get_all_products.php, i parsed it and displayed in a listview.
-> If there are no products found AddNewProductAcivity is launched.

AllProductsActivity.java
package com.example.androidhive;
 
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
 
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
 
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
 
public class AllProductsActivity extends ListActivity {
 
    // Progress Dialog
    private ProgressDialog pDialog;
 
    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();
 
    ArrayList<HashMap<String, String>> productsList;
 
    // url to get all products list
    private static String url_all_products = "http://api.androidhive.info/android_connect/get_all_products.php";
 
    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_PRODUCTS = "products";
    private static final String TAG_PID = "pid";
    private static final String TAG_NAME = "name";
 
    // products JSONArray
    JSONArray products = null;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.all_products);
 
        // Hashmap for ListView
        productsList = new ArrayList<HashMap<String, String>>();
 
        // Loading products in Background Thread
        new LoadAllProducts().execute();
 
        // Get listview
        ListView lv = getListView();
 
        // on seleting single product
        // launching Edit Product Screen
        lv.setOnItemClickListener(new OnItemClickListener() {
 
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // getting values from selected ListItem
                String pid = ((TextView) view.findViewById(R.id.pid)).getText()
                        .toString();
 
                // Starting new intent
                Intent in = new Intent(getApplicationContext(),
                        EditProductActivity.class);
                // sending pid to next activity
                in.putExtra(TAG_PID, pid);
 
                // starting new activity and expecting some response back
                startActivityForResult(in, 100);
            }
        });
 
    }
 
    // Response from Edit Product Activity
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // if result code 100
        if (resultCode == 100) {
            // if result code 100 is received
            // means user edited/deleted product
            // reload this screen again
            Intent intent = getIntent();
            finish();
            startActivity(intent);
        }
 
    }
 
    /**
     * Background Async Task to Load all product by making HTTP Request
     * */
    class LoadAllProducts extends AsyncTask<String, String, String> {
 
        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(AllProductsActivity.this);
            pDialog.setMessage("Loading products. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }
 
        /**
         * getting All products from url
         * */
        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
 
            // Check your log cat for JSON reponse
            Log.d("All Products: ", json.toString());
 
            try {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);
 
                if (success == 1) {
                    // products found
                    // Getting Array of Products
                    products = json.getJSONArray(TAG_PRODUCTS);
 
                    // looping through All Products
                    for (int i = 0; i < products.length(); i++) {
                        JSONObject c = products.getJSONObject(i);
 
                        // Storing each json item in variable
                        String id = c.getString(TAG_PID);
                        String name = c.getString(TAG_NAME);
 
                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();
 
                        // adding each child node to HashMap key => value
                        map.put(TAG_PID, id);
                        map.put(TAG_NAME, name);
 
                        // adding HashList to ArrayList
                        productsList.add(map);
                    }
                } else {
                    // no products found
                    // Launch Add New product Activity
                    Intent i = new Intent(getApplicationContext(),
                            NewProductActivity.class);
                    // Closing all previous activities
                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(i);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
 
            return null;
        }
 
        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                    ListAdapter adapter = new SimpleAdapter(
                            AllProductsActivity.this, productsList,
                            R.layout.list_item, new String[] { TAG_PID,
                                    TAG_NAME},
                            new int[] { R.id.pid, R.id.name });
                    // updating listview
                    setListAdapter(adapter);
                }
            });
 
        }
 
    }
}
android list products

Adding a New Product (Write)

7. Create a new view and acivity to add a new product into mysql database. Create a simple form which contains EditText for product name, price and description.

Create a new xml file and name it as add_product.xml and paste the following code to create a simple form.

add_product.xml

add_product.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
 
    <!-- Name Label -->
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Product Name"
        android:paddingLeft="10dip"
        android:paddingRight="10dip"
        android:paddingTop="10dip"
        android:textSize="17dip"/>
 
    <!-- Input Name -->
    <EditText android:id="@+id/inputName"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dip"
        android:layout_marginBottom="15dip"
        android:singleLine="true"/>
 
    <!-- Price Label -->
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Price"
        android:paddingLeft="10dip"
        android:paddingRight="10dip"
        android:paddingTop="10dip"
        android:textSize="17dip"/>
 
    <!-- Input Price -->
    <EditText android:id="@+id/inputPrice"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dip"
        android:layout_marginBottom="15dip"
        android:singleLine="true"
        android:inputType="numberDecimal"/>
 
    <!-- Description Label -->
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Description"
        android:paddingLeft="10dip"
        android:paddingRight="10dip"
        android:paddingTop="10dip"
        android:textSize="17dip"/>
 
    <!-- Input description -->
    <EditText android:id="@+id/inputDesc"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dip"
        android:layout_marginBottom="15dip"
        android:lines="4"
        android:gravity="top"/>
 
    <!-- Button Create Product -->
    <Button android:id="@+id/btnCreateProduct"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Create Product"/>
 
</LinearLayout>
android adding new product

8. Now create new Activity to insert a new product into mysql database. Create a class file and name it as NewProductActivity.java and type the following code. In the following code

-> First new product data is read from the EditText form and formatted into a basic params.
-> A request is made to create_product.php to create a new product through HTTP post.
-> After getting json response from create_product.php, If success bit is 1 then list view is refreshed with newly added product.

NewProductActivity.java
package com.example.androidhive;
 
import java.util.ArrayList;
import java.util.List;
 
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
 
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
 
public class NewProductActivity extends Activity {
 
    // Progress Dialog
    private ProgressDialog pDialog;
 
    JSONParser jsonParser = new JSONParser();
    EditText inputName;
    EditText inputPrice;
    EditText inputDesc;
 
    // url to create new product
    private static String url_create_product = "http://api.androidhive.info/android_connect/create_product.php";
 
    // JSON Node names
    private static final String TAG_SUCCESS = "success";
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_product);
 
        // Edit Text
        inputName = (EditText) findViewById(R.id.inputName);
        inputPrice = (EditText) findViewById(R.id.inputPrice);
        inputDesc = (EditText) findViewById(R.id.inputDesc);
 
        // Create button
        Button btnCreateProduct = (Button) findViewById(R.id.btnCreateProduct);
 
        // button click event
        btnCreateProduct.setOnClickListener(new View.OnClickListener() {
 
            @Override
            public void onClick(View view) {
                // creating new product in background thread
                new CreateNewProduct().execute();
            }
        });
    }
 
    /**
     * Background Async Task to Create new product
     * */
    class CreateNewProduct extends AsyncTask<String, String, String> {
 
        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(NewProductActivity.this);
            pDialog.setMessage("Creating Product..");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }
 
        /**
         * Creating product
         * */
        protected String doInBackground(String... args) {
            String name = inputName.getText().toString();
            String price = inputPrice.getText().toString();
            String description = inputDesc.getText().toString();
 
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("name", name));
            params.add(new BasicNameValuePair("price", price));
            params.add(new BasicNameValuePair("description", description));
 
            // getting JSON Object
            // Note that create product url accepts POST method
            JSONObject json = jsonParser.makeHttpRequest(url_create_product,
                    "POST", params);
 
            // check log cat fro response
            Log.d("Create Response", json.toString());
 
            // check for success tag
            try {
                int success = json.getInt(TAG_SUCCESS);
 
                if (success == 1) {
                    // successfully created product
                    Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
                    startActivity(i);
 
                    // closing this screen
                    finish();
                } else {
                    // failed to create product
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
 
            return null;
        }
 
        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once done
            pDialog.dismiss();
        }
 
    }
}

Reading, Updating and Deleting a Single Product

9. If you notice the AllProductsActivity.java, In listview i am launching EditProductAcivity.java once a single list item is selected. So create xml file called edit_product.xml and create a form which is same as create_product.xml.

edit_product.xml

edit_product.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
 
    <!-- Name Label -->
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Product Name"
        android:paddingLeft="10dip"
        android:paddingRight="10dip"
        android:paddingTop="10dip"
        android:textSize="17dip"/>
 
    <!-- Input Name -->
    <EditText android:id="@+id/inputName"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dip"
        android:layout_marginBottom="15dip"
        android:singleLine="true"/>
 
    <!-- Price Label -->
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Price"
        android:paddingLeft="10dip"
        android:paddingRight="10dip"
        android:paddingTop="10dip"
        android:textSize="17dip"/>
 
    <!-- Input Price -->
    <EditText android:id="@+id/inputPrice"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dip"
        android:layout_marginBottom="15dip"
        android:singleLine="true"
        android:inputType="numberDecimal"/>
 
    <!-- Description Label -->
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Description"
        android:paddingLeft="10dip"
        android:paddingRight="10dip"
        android:paddingTop="10dip"
        android:textSize="17dip"/>
 
    <!-- Input description -->
    <EditText android:id="@+id/inputDesc"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dip"
        android:layout_marginBottom="15dip"
        android:lines="4"
        android:gravity="top"/>
 
    <LinearLayout android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <!-- Button Create Product -->
    <Button android:id="@+id/btnSave"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Save Changes"
        android:layout_weight="1"/>
 
    <!-- Button Create Product -->
    <Button android:id="@+id/btnDelete"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Delete"
        android:layout_weight="1"/>
    </LinearLayout>
 
</LinearLayout>

10. Create a class file for edit_product.xml and name it as EditProductActivity.java and fill it with following code. In the following code

-> First product id (pid) is read from the intent which is sent from listview.
-> A request is made to get_product_details.php and after getting product details in json format, I parsed the json and displayed in EditText.
-> After displaying product data in the form if user clicks on Save Changes Button, another HTTP request is made to update_product.php to store updated product data.
-> If the user selected Delete Product Button, HTTP request is made to delete_product.phpand product is deleted from mysql database, and listview is refreshed with new product list.

EditProductActivity.java
package com.example.androidhive;
 
import java.util.ArrayList;
import java.util.List;
 
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
 
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
 
public class EditProductActivity extends Activity {
 
    EditText txtName;
    EditText txtPrice;
    EditText txtDesc;
    EditText txtCreatedAt;
    Button btnSave;
    Button btnDelete;
 
    String pid;
 
    // Progress Dialog
    private ProgressDialog pDialog;
 
    // JSON parser class
    JSONParser jsonParser = new JSONParser();
 
    // single product url
    private static final String url_product_detials = "http://api.androidhive.info/android_connect/get_product_details.php";
 
    // url to update product
    private static final String url_update_product = "http://api.androidhive.info/android_connect/update_product.php";
 
    // url to delete product
    private static final String url_delete_product = "http://api.androidhive.info/android_connect/delete_product.php";
 
    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_PRODUCT = "product";
    private static final String TAG_PID = "pid";
    private static final String TAG_NAME = "name";
    private static final String TAG_PRICE = "price";
    private static final String TAG_DESCRIPTION = "description";
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.edit_product);
 
        // save button
        btnSave = (Button) findViewById(R.id.btnSave);
        btnDelete = (Button) findViewById(R.id.btnDelete);
 
        // getting product details from intent
        Intent i = getIntent();
 
        // getting product id (pid) from intent
        pid = i.getStringExtra(TAG_PID);
 
        // Getting complete product details in background thread
        new GetProductDetails().execute();
 
        // save button click event
        btnSave.setOnClickListener(new View.OnClickListener() {
 
            @Override
            public void onClick(View arg0) {
                // starting background task to update product
                new SaveProductDetails().execute();
            }
        });
 
        // Delete button click event
        btnDelete.setOnClickListener(new View.OnClickListener() {
 
            @Override
            public void onClick(View arg0) {
                // deleting product in background thread
                new DeleteProduct().execute();
            }
        });
 
    }
 
    /**
     * Background Async Task to Get complete product details
     * */
    class GetProductDetails extends AsyncTask<String, String, String> {
 
        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(EditProductActivity.this);
            pDialog.setMessage("Loading product details. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }
 
        /**
         * Getting product details in background thread
         * */
        protected String doInBackground(String... params) {
 
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    // Check for success tag
                    int success;
                    try {
                        // Building Parameters
                        List<NameValuePair> params = new ArrayList<NameValuePair>();
                        params.add(new BasicNameValuePair("pid", pid));
 
                        // getting product details by making HTTP request
                        // Note that product details url will use GET request
                        JSONObject json = jsonParser.makeHttpRequest(
                                url_product_detials, "GET", params);
 
                        // check your log for json response
                        Log.d("Single Product Details", json.toString());
 
                        // json success tag
                        success = json.getInt(TAG_SUCCESS);
                        if (success == 1) {
                            // successfully received product details
                            JSONArray productObj = json
                                    .getJSONArray(TAG_PRODUCT); // JSON Array
 
                            // get first product object from JSON Array
                            JSONObject product = productObj.getJSONObject(0);
 
                            // product with this pid found
                            // Edit Text
                            txtName = (EditText) findViewById(R.id.inputName);
                            txtPrice = (EditText) findViewById(R.id.inputPrice);
                            txtDesc = (EditText) findViewById(R.id.inputDesc);
 
                            // display product data in EditText
                            txtName.setText(product.getString(TAG_NAME));
                            txtPrice.setText(product.getString(TAG_PRICE));
                            txtDesc.setText(product.getString(TAG_DESCRIPTION));
 
                        }else{
                            // product with pid not found
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
 
            return null;
        }
 
        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once got all details
            pDialog.dismiss();
        }
    }
 
    /**
     * Background Async Task to  Save product Details
     * */
    class SaveProductDetails extends AsyncTask<String, String, String> {
 
        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(EditProductActivity.this);
            pDialog.setMessage("Saving product ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }
 
        /**
         * Saving product
         * */
        protected String doInBackground(String... args) {
 
            // getting updated data from EditTexts
            String name = txtName.getText().toString();
            String price = txtPrice.getText().toString();
            String description = txtDesc.getText().toString();
 
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair(TAG_PID, pid));
            params.add(new BasicNameValuePair(TAG_NAME, name));
            params.add(new BasicNameValuePair(TAG_PRICE, price));
            params.add(new BasicNameValuePair(TAG_DESCRIPTION, description));
 
            // sending modified data through http request
            // Notice that update product url accepts POST method
            JSONObject json = jsonParser.makeHttpRequest(url_update_product,
                    "POST", params);
 
            // check json success tag
            try {
                int success = json.getInt(TAG_SUCCESS);
 
                if (success == 1) {
                    // successfully updated
                    Intent i = getIntent();
                    // send result code 100 to notify about product update
                    setResult(100, i);
                    finish();
                } else {
                    // failed to update product
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
 
            return null;
        }
 
        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once product uupdated
            pDialog.dismiss();
        }
    }
 
    /*****************************************************************
     * Background Async Task to Delete Product
     * */
    class DeleteProduct extends AsyncTask<String, String, String> {
 
        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(EditProductActivity.this);
            pDialog.setMessage("Deleting Product...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }
 
        /**
         * Deleting product
         * */
        protected String doInBackground(String... args) {
 
            // Check for success tag
            int success;
            try {
                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("pid", pid));
 
                // getting product details by making HTTP request
                JSONObject json = jsonParser.makeHttpRequest(
                        url_delete_product, "POST", params);
 
                // check your log for json response
                Log.d("Delete Product", json.toString());
 
                // json success tag
                success = json.getInt(TAG_SUCCESS);
                if (success == 1) {
                    // product successfully deleted
                    // notify previous activity by sending code 100
                    Intent i = getIntent();
                    // send result code 100 to notify about product deletion
                    setResult(100, i);
                    finish();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
 
            return null;
        }
 
        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once product deleted
            pDialog.dismiss();
 
        }
 
    }
}
android edit product
android delete product

JSON Parser Class

I used a JSON Parser class to get JSON from URL. This class supports two http request methods GET and POST to get json from url.

JSONParser.java
package com.example.androidhive;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
 
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
 
import android.util.Log;
 
public class JSONParser {
 
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";
 
    // constructor
    public JSONParser() {
 
    }
 
    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {
 
        // Making HTTP request
        try {
 
            // check for request method
            if(method == "POST"){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));
 
                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
 
            }else if(method == "GET"){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);
 
                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }          
 
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
 
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
 
        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }
 
        // return JSON String
        return jObj;
 
    }
}

Run your project and test the application. You might get lot of errors. Always use Log Cat to debug your application, and if you couldn’t solve your errors please do comment here.


출처 : http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/

+ Recent posts