[현재 접속자 현황]
안드로이드 관련 팁 게시판입니다.
글수 27
[안드로이드개발환경 폴더]
1. D:\안드로이드개발환경_설치완료분_20110110\android-sdk-windows를 C:\java\android-sdk-
windows에 덮어 쓰기
-- > 설정확인: command창에서 c: > adb 입력
-- > adb (Android Debug Bridge)
1) 안드로이드 쉘에 로그인
2) 안드로이드 폰 또는 에뮬레이터에 apk(안드로이드 앱 설치파일 확장자) 설치
3) 안드로이드 폰 SD카드에 파일을 추가
2. ADT-8.0.1.zip은 C드라이브로 복사만
-- > 이클립스용 안드로이드 개발 플러그인
-- > https://dl-ssl.google.com/android/eclipse
===============================================
1) 구글맵 SDK (2.1) 설치: USB의 다음 폴더를 동일한 폴더로 복사
D:\안드로이드개발환경_설치완료분_20110110\android-sdk-windows\add-ons
2) Android 2.1 Sample 설치: USB의 다음 폴더를 동일한 폴더로 복사
D:\안드로이드개발환경_설치완료분_20110110\android-sdk-windows\samples
Android 1일차==============================
[Activity 주요 함수]
1) setContentView
예) setContentView(R.layout.xxx);
-- > res/layout/xxx.xml을 그 액티비티의 화면으로 설정
2) findViewById
예) Button btn = (Button)findViewById(R.id.Button01);
-- > xxx.xml의 Button중 id속성값이 Button01인 버튼 참조
3) setOnClickListener
btn.setOnClickListener(new View.OnClickListner....)
-- > 버튼을 클릭했을 때 이벤트 처리
[실습]
1. main.xml에 버튼을 하나 더 추가하고, id는 Button02로 지정
2. 버튼 선언 및 변수 참조
Button btn2 = (Button)findViewById(R.id.Button02);
3. Button02를 클릭리스너 설정
btn.setOnClickListener(new View.OnClickListner() {
public void onClick(View v) {
}
});
4. Button02를 클릭하면 다음의 코드가 실행되도록 함
new AlertDialog.Builder(HelloAndroid.this)
.setTitle("선택상자")
.setMessage("반갑습니다")
.setNeutralButton("닫기", null)
.show();
[실습] 각자의 프로젝트(예:프로젝트명 okgosu)
1. xml 레이아웃 생성
1) 파일명: hello_world2.xml
2) root element: LinearLayout 선택
2. xml 화면 디자인
1) EditText 2개를 화면에 추가하고 id는 ed1_hello, ed2_hello로 지정
2) Button을 화면에 추가하고 id는 btn1_hello로 지정
3. 다음의 정보로 액티비티 생성
Class 명 : HelloWorld2
Superclass 명: Activity(패키지 경로 android.app.Activity)
override할 함수명: onCreate
4. onCreate 오버라이딩 로직
1) setContentView 호출
setContentView(R.layout.hello_world2);
2) ed1_hello, ed2_hello, btn1_hello 로컬변수 선언 및 findViewById
EditText ed1_hello = (EditText)findViewById(R.id.ed1_hello);
EditText ed2_hello = (EditText)findViewById(R.id.ed2_hello);
Button btn1_hello = (Button)findViewById(R.id.btn1_hello);
5. btn1_hello를 클릭하면 ed1_hello에 입력된 내용을 Toast로 3초간 출력한다.
String msg = ed1_hello.getText().toString();
Toast.makeText(HelloWorld2.this, msg, 3000).show();
6. ed1_hello변수 선언을 final로 변경한다.
EditText ed1_hello = .....;
-- > final EditText ed1_hello = ......;
* 클래스 자동 임포트 단축키 : Ctrl + Shift + O
7. HelloWorld2가 메인액티비티가 되도록 설정 : AndroidManifest.xml
변경전 < activity android:name="HelloAndroid" android:label="@string/app_name" >
변경후 < activity android:name="HelloWorld2" android:label="@string/app_name" >
8. 로직수정
: 버튼을 클릭하면 두 EditText에 입력된 값의 합을 출력
1) hello_world2.xml의 EditText 2개에 android:inputType="number" 속성을 추가
2) btn1_hello 클릭리스너에서 EditText 2개의 값을 숫자로 변환 후 합 계산
int num1 = Integer.parseInt(ed1_hello.getText().toString());
int num2 = Integer.parseInt(ed2_hello.getText().toString());
String msg = "합은 : " + (num1 + num2);
2일차======================================
[GPS컨트롤]
1. 레이아웃 : my_gps.xml
- LinearLayout에 CheckBox 추가 (id는 cb_gps)
2. 액티비티: MyGPS.java
- onCreate에서 GPS의 설정을 읽어와 체크박스에 on/off로 표시함
String gs = android.provider.Settings.Secure.getString(getContentResolver(),
android.provider.Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if (gs.indexOf("gps", 0) < 0) {
cb_gps.setChecked(false);
cb_gps.setText("GPS꺼짐");
} else {
cb_gps.setChecked(true);
cb_gps.setText("GPS켜짐");
}
3. cb_gps 체크 상태가 변경 되면 GPS 설정화면으로 이동
(setOnCheckedChangeListener의 인터페이스에서 구현)
new AlertDialog.Builder(MyGPS.this)
.setTitle("GPS 설정")
.setMessage("GPS 설정변경")
.setPositiveButton("GPS 설정변경", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(android.provider.Settings.
ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
finish();
}
}).show();
[EditText 실습]
1. my_edit_text.xml 수정
1) TextView에 다음의 3개 속성 추가
android:textColor="#FFFF00"
android:textStyle="bold"
android:textSize="20px"
2) EditText에 다음의 2개 속성 추가
android:hint="글자를 입력하면 글자수를 체크합니다"
android:singleLine="true"
2. MyEditText.java를 수정 (클릭 리스너 처리)
1) OK버튼을 누르면 입력한 글자로 검색을 실행하게 한다.
Intent intent = new Intent(Intent.ACTION_SEARCH);
intent.putExtra(SearchManager.QUERY, ed.getText().toString());
startActivity(intent);
2) CANCEL 버튼을 누르면 에디트 텍스트에 입력된 글자를 지운다.
ed.setText("");
[MyScrollView 수정]
:createWidgets함수에 ImageView를 동적으로 생성해서 같이 추가되도록 한다.
ImageView img = new ImageView(this);
img.setImageResource(R.drawable.zzangu0); // zzangu0.png 이미지
[MyTab 수정]
1. createTabContent 함수 수정
WebView web = new WebView(MyTab.this);
web.loadUrl("http://okgosu.net");
return web;
2. spec.setIndicator("okgosu.net");
[RelativeLayout]
두 버튼을 포함한 LinearLayout(orientation은 horizontal)의 속성을 다음과 같이
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
[MySpinner 수정]
1. my_spinner.xml에 WebView 추가
: layout_width, layout_height를 fill_parent, id는 browser
2. MySpinner.java 수정
1) items 변수를 다음과 같이 수정
String[] items = {"http://okgosu.net", "http://d.android.com", "http://daum.net"};
2) 스피너의 아이템을 선택했을 때 browser가 선택한 주소의 웹사이트를 로드하도록 함
* MyWebView 소스 참조
* Activity의 서브 클래스
: ListActivity = Activity + ListView
[MyAppList] - 단계1
1. MyAppList.java 라는 ListActivity 작성
//멤버변수 선언
private ArrayList items = new ArrayList();
private List appList;
2. onCreate함수 오버라이딩
// 앱리스트는 뽑아오기
appList = getPackageManager().getInstalledApplications(0);
// 어댑터에 사용할 배열
Iterator itr = appList.iterator();
while (itr.hasNext()) {
ApplicationInfo info = (ApplicationInfo)itr.next();
items.add(info.packageName);
}
3. ListView 어댑터 설정
1) ArrayAdapter 생성
ArrayAdapter< String > adapter = new ArrayAdapter< String > (this, android.R.layout.simple_list_item_1,
items)
2) ArrayAdapter 설정 : setListAdapter(adapter);
4. 앱리스트를 클릭하면 AlertDialog로 패키지명 출력
ApplicationInfo app = appList.get(position);
String pname = app.packageName; // 패키지명
[MyAppList] - 단계2
ArrayAdapter에서 레이아웃을 android.R.layout.simple_list_item_1 대신에 커스텀 레이아웃을 사용하도록
한다.
1. ListView에서 사용할 행에 대한 레이아웃 생성: my_app_row.xml
1) LinearLayout에 ImageView와 TextView를 추가
2) 각각 id는 img, text1
3) ImageView의 src속성은 @drawable/icon으로 설정
2. ArrayAdapter를 다음과 같이 변경
ArrayAdapter< String > adapter2 = new ArrayAdapter< String > (this, R.layout.my_app_row, R.id.text1,
items);
setListAdapter(adapter2);
[MyAppList] - 단계3
1. inner 클래스로 MyAdapter 생성
class MyAdapter extends ArrayAdpater {
}
2. 생성자 함수 선언
3. getView 함수 오버라이딩
[포그라운드 액티비티 정보 출력]
[MyTaskList]
1. MyTaskList.java 라는 ListActivity 작성
//멤버변수 선언
private ArrayList items = new ArrayList();
private List taskList;
2. onCreate함수 오버라이딩
// 포그라운드 액티비티 정보들
ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
List taskList = activityManager.getRunningTasks(7);
Iterator itr = taskList.iterator();
while (itr.hasNext()) {
RunningTaskInfo info = (RunningTaskInfo)itr.next();
// 클래스 이름 runningTaskInfo.topActivity.getClassName()
items.add(info.topActivity.getClassName());
}
3. ArrayAdapter 생성 및 ListView에 설정
4. 아이템을 클릭하면 액티비티 이름과 패키지명을 토스트로 출력
5. 퍼미션 추가
< uses-permission android:name="android.permission.GET_TASKS"/ >
[MyTastList] -2
항목을 클릭하면 앱을 강제 종료
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
ActivityManager actMng = (ActivityManager)getSystemService(ACTIVITY_SERVICE);
RunningTaskInfo info =(RunningTaskInfo)taskList.get(position);
String pname = info.topActivity.getPackageName();
Toast.makeText(this, pname, 2000).show();
actMng.restartPackage(pname);// 2.1
//actMng.killBackgroundProcesses(pname);// 2.2
// 권한 < uses-permission android:name="android.permission.RESTART_PACKAGES"/ >
}
3일차=======================
[AutoComplete 예제]
p 124 layout: my_auto.xml
p 125 AutoCompleteDemo.java
* 주의) setContentView(R.layout.my_auto);
[실습] ListView 다중 선택 모드로 변경 (MyListView.java)
1. onCreate 함수에서
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
2. ArrayAdapter의 텍스트뷰리소스 변경
: android.R.layout.simple_list_item_multiple_choice
3. onListItemClick 함수에서 선택된 항목 캐치
SparseBooleanArray sba =l.getCheckedItemPositions();
String choices = "";
for (int i = 0; i < sba.size(); i++) {
if (sba.get(sba.keyAt(i))) choices += "체크한 인덱스:" + i + ", ";
}
Toast.makeText(this, choices, 1000).show();
[실습]
1. hello_world2.xml (my_cal.xml)
1) ed1_hello의 속성
imeOptions="actionNext"
android:nextFocusDown="@+id/ed2_hello"
2) ed2_hello의 속성
imeOptions="actionDone"
2. HelloWorld2.java (MyCal.java)
ed2_hello에 대해 setOnEditorActionListener설정
-- > 두 필드의 합을 바로 출력
[실습]
1. 버튼7을 누르면 MyWebView가 같이 호출되도록 AndroidManifest.xml에 인텐트필터를 하나 더 추가
< intent-filter >
< action android:name="android.intent.action.GET_CONTENT" / >
< category android:name="android.intent.category.DEFAULT" / >
< data android:mimeType="audio/*"/ >
< /intent-filter >
[실습] 인텐트 수신
1. 버튼 6을 누르면 MyEditText가 인텐트를 수신하도록 AndroidManifest.xml에 인텐트필터를 하나 더 추가
< intent-filter >
< action android:name="android.intent.action.VIEW" / >
< category android:name="android.intent.category.DEFAULT" / >
< data android:mimeType="audio/mp3"/ >
< /intent-filter >
2. MyEditText에서 Intent의 부가정보(URI)의 텍스트값을 출력함
: onCreate함수에 다음의 코드 추가
Intent intent = getIntent();
String uri = intent.getDataString().toString();
ed.setText(uri);
[MyIntentCaller 인텐트 송수신 수정]
1. my_intent_caller.xml 에 Spinner 추가 (id는 spn)
2. Spinner 에서 다음의 데이터를 표시하도록 함
String[] items = {"#FF0000", "#00FF00", "#0000FF" };
3. MyIntentCaller에서 "인텐트호출"버튼을 누르면
Spinner의 선택값을 "mycolor"라는 이름으로 MyIntentReceiver로 전송
intent.putExtra("mycolor", Color.parseColor(spn.getSelectedItem().toString()));
// 넘어가는 값은 색상코드의 int값임 ("#FF0000" -- > 0xFF0000)
4. my_intent_receiver.xml의 LinearLayout에 id 속성을 root로 지정
5. MyIntentReceiver에서 mycolor값을 수신 (onCreate에서)
int mycolor = getIntent().getIntExtra("mycolor");
6. root의 배경 색상을 변경함 (onCreate에서)
LinearLayout root = (LinearLayout)findViewById(R.id.root);
root.setBackgroundColor(mycolor);
[MyIntentRecevier 수신알림 : Notification적용]
int noticeCount = 0;
NotificationManager ntf = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification noti = new Notification(R.drawable.icon, "수신알림", System.currentTimeMillis());
PendingIntent pintent = PendingIntent.getActivity(this,0, new Intent("MyWebView"), 0);
noti.setLatestEventInfo(this, "[메시지제목:수신알림]", "내용은....어쩌구 저쩌구....", pintent);
noti.default = Notification.DEFAULT_VIBRATE;
ntf.notify(noticeCount++, noti);
//noti.default = Notification.DEFAULT_SOUND;
//noti.default = Notification.DEFAULT_ALL;
[홈 액티비티 설정하기]
< intent-filter >
< action android:name="android.intent.action.MAIN" / >
< category android:name="android.intent.category.DEFAULT" / >
< category android:name="android.intent.category.HOME" / >
< /intent-filter >
[액티비티 라이프사이클]
1) 처음시작: onCreate - onStart - onResume
2) 화면전환: onPause - onStop
3) 화면원복: onRestart - onStart - onResume
4) 일시정지: onPause
5) 다시 화면 원복: onResume
6) 화면종료: onPause - onStop - onDestroy
[MyXMLPrefView.java 수정]
1. my_pref.xml에 다음 2개 항목을 추가
< CheckBoxPreference android:key="my_pref_ori" android:title="항상 가로화면으로 봅니다." / >
< EditTextPreference android:key="my_pref_title" android:title="액티비티의 제목을 설정합니다." / >
2. MyXMLPrefView.java
1) onCreate에서 항목값을 읽어옴
String activity_title = sp.getString("my_pref_title", "액티비티 제목 없음");
boolean activity_ori = sp.getBoolean("my_pref_ori", false);
2) 액티비티에 적용
// 액티비티 타이틀 변경 :
setTitle(value);
// 화면 회전 처리 : 항상 가로로
if(activity_ori) setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
// 액티비티 상단 타이틀바 없애기 (setContentView 호출 전에 넣어야함)
requestWindowFeature(Window.FEATURE_NO_TITLE);
[HTTP 처리-오픈API] - 1
0. 웹주소 확인
http://okgosu.net/book/get_xml_data.php?kind=green
http://okgosu.net/book/get_xml_data.php?kind=yellow
1. 액티비티 작성 MyHttpDemo - ListActivity
// import 문 추가:
import org.w3c.dom.Element;
// 멤버변수 선언
ArrayList< String > items = new ArrayList< String > ();
2. onCreate 오버라이딩
HttpClient hc = new DefaultHttpClient();
HttpGet req = new HttpGet("http://okgosu.net/book/get_xml_data.php?kind=green");
try {
ResponseHandler< String > res = new BasicResponseHandler();
String resStr = hc.execute(req, res); // XML결과값
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(new InputSource( new StringReader(resStr)));
NodeList nl = doc.getElementsByTagName("item");
items.clear();
for(int i=0; i< nl.getLength(); i++){
Element el = (Element)nl.item(i);
String data = (String)el.getFirstChild().getNodeValue(); // Node값
items.add(data);
}
setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, items));
} catch (Exception e) {
e.printStackTrace();
}
[HTTP 처리-오픈API] - 2
1. 레이아웃 생성 - my_http_demo.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" >
< LinearLayout android:orientation="horizontal"
android:layout_width="fill_parent" android:layout_height="wrap_content" >
< Spinner android:id="@+id/sp" android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_weight="1"/ >
< Button android:id="@+id/go_button" android:layout_height="wrap_content"
android:layout_width="wrap_content" android:text="검색" / >
< /LinearLayout >
< ListView android:id="@android:id/list"
android:drawSelectorOnTop="false" android:layout_width="fill_parent"
android:layout_height="fill_parent" / >
< /LinearLayout >
2. MyHttpDemo와 my_http_demo.xml 연동
setContentView(R.layout.my_http_demo);
3. Spinner에 다음의 데이터가 보이도록 어댑터 설정: green, red, blue, yellow
final Spinner sp = (Spinner)findViewById(R.id.sp);
String[] arr = {"red", "green", "yellow", "blue"};
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, arr);
sp.setAdapter(adapter);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
4. 버튼을 클릭하면 스피너에서 선택한 아이템의 데이터를 뽑아오도록 리스너 설정
: HttpClient 부터 try~catch 다시 로직 수행
Button go_button = (Button)findViewById(R.id.go_button);
go_button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
HttpClient hc = new DefaultHttpClient();
HttpGet req = new HttpGet("http://okgosu.net/book/get_xml_data.php?kind=" +
sp.getSelectedItem().toString());
try {
................................상동.............................
}
}
});
[SD카드로 입출력] MyReadBin.java
1. 권한 추가 (AndroidManifest.xml)
< uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/ >
2. onResume함수 수정
File f = new File("/sdcard/okgosu.txt");
InputStream in = new FileInputStream(f);
3. onPause함수 수정
File f = new File("/sdcard/okgosu.txt");
if(!f.exists()) f.createNewFile();
OutputStream os = new FileOutputStream(f);
OutputStreamWriter out = new OutputStreamWriter(os);
------------------------------------------------
상품조회 테이블 (prod)
-----------------------------------------
아이디 상품코드 상품명
_id prod_code prod_name
1 snk01 새우깡
2 snk02 맛동산
[실습]
MyProdDBList.java의 데이터 정렬 순서를 상품이름이 아니라 상품 아이디 순으로 변경
onResume함수에서 다음과 같이 수정
1) 변경전
String order_by = MyProdDBCons.PROD_NAME;
2) 변경후
String order_by = MyProdDBCons.PROD_ID;
[실습] 상품ID로 검색
// 상품id로 검색
String qWhere = MyProdDBCons.PROD_ID+ " = ? " ;
String qLike = searchCode;
Cursor c = sdb.query(MyProdDBCons.TABLE_NAME, columns, qWhere, new String[] {qLike}, null,
null, order_by, null);
[과제] my_prod_db_col.xml
1. 상품목록의 id값을 글자색을 노란색(#FFFFFF00)으로 변경
android:textColor="#FFFFFF00"
2. 상품코드/상품명의 글자크기를 조금 크게 나오도록함
android:textSize="15sp"
3. 상품명 옆에 아이콘 표시
< ImageView android:src="@drawable/icon"
android:id="@+id/my_prod_img"
android:layout_width="wrap_content"
android:layout_height="wrap_content" / >
4. my_prod_name은 다음과 같이 변경
1) 속성 추가: android:layout_weight="1"
2) 속성 변경: android:layout_width="wrap_content"
[EditText 입력필터]
InputFilter myfilter = new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
String format = "[a-z]*[A-Z]*[0-9]*";
try{
Pattern pattern = Pattern.compile(format);
Matcher matcher = pattern.matcher(source);
if(!matcher.matches()) return "";
}catch(PatternSyntaxException e){
return null;
}
return null;
}
};
[연락처 DB쿼리]
1. 매니페스트에 권한 추가
< uses-permission android:name="android.permission.READ_CONTACTS"/ >
2. MyContactManager (ListActivity)의 onCreate에서
final Cursor cursor = getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
// 가져올 컬럼의 이름값 배열
String[] cols = {ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME};
// 컬럼을 매치시킬 View의 ID 배열
int[] view_ids = {android.R.id.text2, android.R.id.text1};
// Cursor 객체를 화면에 연결시켜주기 위한 Adapter생성
SimpleCursorAdapter adapter
= new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_2, cursor, cols, view_ids);
// Adapter를 ListView에 연결
setListAdapter(adapter);
[안드로이드 컨텐트프로바이더 URI]
주소록: content://contacts/people
사진앨범: content://media/internal/images
음악앨범: content://media/external/audio/media
상품관리자실습 : content://okgosu.net.provider.MyProd/myprods
[MyCPDemo] 컨텐트프로바이더 활용 - 데이터 입력
1. my_cp_demo.xml에 버튼 추가 (id는 btn_insert)
2. MyCPDemo.java
btn_insert를 클릭하면 컨텐트프로바이더로 데이터를 한건 입력
ContentValues values= new ContentValues();
values.put(MyProdDBCons.PROD_CODE, "snk99");
values.put(MyProdDBCons.PROD_NAME, "짱구");
Uri uri = getContentResolver().insert(MyProdDBCons.CONTENT_URI, values);
// uri값을 출력
Toast.makeText(MyCPDemo.this, "1건 입력: uri=": +uri.toString(), 1000).show();
[MyCPDemo] 컨텐트프로바이더 활용 - 데이터 수정, 삭제
: onListItemClick 오버라이딩, 아이템을 클릭하면 클릭한 아이템을 수정, 삭제함
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Cursor c = (Cursor)l.getItemAtPosition(position);
String prod_code = c.getString(1);
String prod_name = c.getString(2);
ContentValues values= new ContentValues();
values.put(MyProdDBCons.PROD_CODE, prod_code + "#");
values.put(MyProdDBCons.PROD_NAME, prod_name + "#");
Uri uri = ContentUris.withAppendedId(MyProdDBCons.CONTENT_URI, id);
// 수정
//int cnt = getContentResolver().update(uri, values, null, null);
//Toast.makeText(MyCPDemo.this, cnt + "건 수정완료", 1000).show();
// 삭제
int cnt2 = getContentResolver().delete(uri, null, null);
Toast.makeText(MyCPDemo.this, cnt2 + "건 삭제 완료", 1000).show();
}
[MyAlbum ListActivity]
Cursor c = getContentResolver().query(Images.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
// 가져올 컬럼의 이름값 배열
String[] cols = {Images.Media.TITLE};
// 컬럼을 매치시킬 View의 ID 배열
int[] view_ids = {android.R.id.text1};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1, c, cols, view_ids);
setListAdapter(adapter);
public void bindView(View view, Context context, Cursor cursor) {
ImageView img = (ImageView)view;
long id = cursor.getLong(cursor
.getColumnIndexOrThrow(Images.Media._ID));
Uri uri = ContentUris.withAppendedId(Images
.Media.EXTERNAL_CONTENT_URI, id);
try {
Bitmap bm = Images.Media
.getBitmap(getContentResolver(), uri);
img.setImageBitmap(bm);
} catch(Exception e) {}
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
ImageView v = new ImageView(context);
return v;
}
[Map키 확인]
1. MyMapTest extends MapActivity
2. onCreate 오버라이딩
String apiKey = "각자의 apiKey";
MapView map = new MapView(this, apiKey);
setContentView(map);
[MP3 플레이어] MyMp3Player extends Activity
1. 레이아웃: my_mp3_player.xml (LinearLayout)에 다음 위젯들 추가
1)TextView (txt_song, 노래제목) 2) Button (btn_play, 재생 ), 3) Button (btn_stop, 정지 )
2. MyMp3Player onCreate
: Intent로 넘어온 URI값을 txt_song에 표시
Uri uri = getIntent().getData();
String uriString = uri.toString();
3. MyMp3Player onCreate: btn_play를 클릭하면 음악 재생
MediaPlayer player = new MediaPlayer ();
player.setDataSource(MyMp3Player.this, uri);
player.prepare();
player.start();
4. MyMp3Player가 다음의 음악재생 인텐트를 수신하도록 매니페스트 추가
< intent-filter >
< action android:name="android.intent.action.VIEW" / >
< category android:name="android.intent.category.DEFAULT" / >
< data android:mimeType="audio/mp3" / >
< /intent-filter >
[SMS수신]
1. 퍼미션 추가: < uses-permission android:name="android.permission.RECEIVE_SMS" / >
2. MySMSReceiver 클래스 작성: MySMSReceiver extends BroadcastReceiver
3. 매니페스트에 MySMSReceiver 추가
< receiver android:name="MySMSReceiver " >
< intent-filter >
< action android:name="android.provider.Telephony.SMS_RECEIVED" / >
< /intent-filter >
< /receiver >
4. MySMSReceiver onReceive(Context context, Intent intent) 오버라이딩
if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")){
StringBuilder ab = new StringBuilder();
Bundle bundle = intent.getExtras();
if(bundle != null) {
Toast.makeText(context, "문자 왔음", 1000).show();
}
}
5. bundle객체로부터 문자내용 파싱
1) import android.telephony.SmsMessage; 추가
2) SmsMessage 파싱
Object[] pdusObj = (Object[]) bundle.get("pdus");
StringBuilder sb = new StringBuilder();
SmsMessage[] messages = new SmsMessage[pdusObj.length];
for (int i = 0; i< pdusObj.length; i++) {
messages[i] = SmsMessage.createFromPdu ((byte[])pdusObj[i]);
sb.append("보낸사람:");
sb.append(messages[i].getDisplayOriginatingAddress());
sb.append("메시지내용:");
sb.append(messages[i].getDisplayMessageBody());
}
6. SMS전송
1) 퍼미션 추가
< uses-permission android:name="android.permission.SEND_SMS"/ >
2) 문자 전송
import android.telephony.SmsManager;
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage("010xxxxxxx", null, "테스트:" + sb.toString(), null, null);
[과제] GPS에서 현재 위치를 받아와 MapView에 표시하기
: MyLocationView의 GPS현재 위치확인 + MyMapView의 위치표시
1. 레이아웃: my_position_view.xml
1) LinearLayout : orientation은 vertical로
2) "내위치표시" 버튼(id=btn_mypos)을 추가
3) MapView추가 : my_map_view.xml 참조
2. 액티비티 생성
1) MyPositionView extends MapActivity implements LocationListener
2) onCreate 오버라이딩
3. btn_mypos 버튼을 누르면 다음의 코드 실행
locationMgr.requestLocationUpdates(best, 1000, 0, MyMapView.this);
4. LocationListener의 onLocationChanged에서 현재 위치를 맵뷰에 표시
GeoPoint newPoint
= new GeoPoint((int) (location.getLatitude()* 1E6),
(int) (location.getLongitude() * 1E6));
mapControl.animateTo(newPoint);
[과제] MyLocationView 로직 추가
1. GPS 설정 상태 확인 (onCreate)
String gs = android.provider.Settings.Secure.getString(getContentResolver(),
android.provider.Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if (gs.indexOf("gps", 0) < 0) {
Toast.makeText(MyLocationView.this, "GPS 설정안됨", 1000).show();
//GPS가 안켜져있으면 켜는 설정으로 이동
new AlertDialog.Builder(MyLocationView.this)
.setTitle("GPS 설정")
.setMessage("GPS가 꺼져 있습니다. GPS를 켜시겠습니까?")
.setNegativeButton("취소", null)
.setPositiveButton("GPS켜기", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(android.provider.Settings.
ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
}).show();
} else {
Toast.makeText(MyLocationView.this, "GPS 설정됨", 1000).show();
}
[과제] : MyLocationView의 onCreate에서 LocationManager에 근접 알림 설정
- 송파구 가락동 반경 500m에 근접시 알림발생하도록 설정
- 알림이 발생하면 Intent가 실행되고, okgosu.net 사이트로 이동함
// 목표지점 좌표
double latitude = 37.493835;
double longitude = 127.121314;
PendingIntent pintent = PendingIntent.getActivity(MyLocationView.this, 0,
new Intent(Intent.ACTION_VIEW, Uri.parse("http://okgosu.net")), 0);
locationMgr.addProximityAlert(latitude, longitude, 500, -1, pintent);
// 반경 500미터에 들어오면 근접 경보 발생
// -1 : 근접경보 만료시한은 없음
// pintent: 해당 지점에 접근하면 실행될 인텐트
* 에뮬레이터에서는
좌표를 127.121314, 47.493835 로 보냈다가
다시 좌표를 127.121314, 37.493835 로 수정해서 보낸다.
[과제: MyMapView]: 주소 검색결과를 다이얼로그로 띄워 표시
1. 멤버변수 추가:
int choice;
ArrayList< String > addrs =new ArrayList< String > ();
2. geocodeResults 변수를 final로 선언
3. while (locations.hasNext()) 들어가기 전에 배열 지우기: addrs.clear();
4. while (locations.hasNext()) 블록 안에서 검색결과를 addrs배열에 추가
addrs.add(loc.getFeatureName());
5. results.setText(locInfo); 밑에 다이얼로그가 표시되도록 코드 추가
final String[] addresses = addrs.toArray(new String[addrs.size()]);
new AlertDialog.Builder(MyMapView.this)
.setTitle(placeName + " 검색 결과")
.setSingleChoiceItems(addresses, 0, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// 선택한 내용을 토스트로 표시
}
})
.setPositiveButton("확인", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// 항목을 선택했을 때 그 위치로 지도가 이동하도록
}
}).setNegativeButton("취소", null)
.show();
6. 다이얼로그에서 각 아이템을 클릭하면 Toast 표시후 아이템 인덱스값 저장 (setSingleChoiceItems 클릭
리스너)
Toast.makeText(MyMapView.this, addresses[whichButton], 1000).show();
choice = whichButton;
7. 확인을 누르면 선택한 아이템으로 이동 (setPositiveButton 클릭리스너)
Address where = geocodeResults.get(choice);
lat = where.getLatitude();
lon = where.getLongitude();
mapControl.animateTo(new GeoPoint((int) (lat * 1E6), (int) (lon * 1E6)));
mapControl.setZoom(15);






okgosu
최근 답변 댓글