국내 광고는 카울리를 적용시켰지만, 해외 판매 앱에 한글 광고를 달 수 없어 애드몹을 적용 시켰다.

Admob 가입 : http://www.admob.com

가입은 생각보다 어렵지 않다. 주소는 녹색창에 'xx시 영문 주소'를 쳤더니 다 나온다.

언어선택 : 홈페이지언어. 한국어가 추가된지 얼마 안된것 같음.

가입 후 MarketPlace -> Add Site/App -> SDK 다운로드(PDF) -> Go to Sites/Apps
원하는 앱의 Manage Settings을 보면 Publisher ID: xxxxxxxxxxxxxxx 15자리의 고유 ID가 생성


먼저 프로젝트 우 클릭 후 Properties -> Java Build Path -> Libraries -> Add External JARs -> 다운받은 SDK, Jar 파일 등록


다운받은 PDF 파일을 보고 보이는 소스만 적당한 위치에 모두 넣어준다.

에뮬 테스트 소스 전까지만. 정상 작동 확인.

영어라 왜 넣는지 모르는 부분이 있는데 나중에 봐야겠다....

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

카울리 적용방법 1.1.5  (1) 2011.03.07

카울리 가입하기 : http://www.cauly.net

APP관리 -> APP등록

APP등록을 완료하면 SDK다운로드와 해당 앱에 특정 코드가 발급됨.


가이드를 보면, lib 폴더를 생성 후 CaulySDK-V1.1.5.jar 파일을 넣으라고 되어있는데
그냥 프로젝트 우클릭 -> Properties -> 다운받은 CaulySDK-V1.1.5.jar 파일을 Libraries로 추가



그 다음은 매니페스트에 퍼미션을 추가해 주어야하는데 가이드에 있는 그대로 복사를 하고 확인을 안했다가
오류가 생겨서 한참을 해매버렸다..
LogCat에 나오는 오류는
Caused by: android.view.InflateException: Binary XML file line #19: Error inflating class com.cauly.android.ad.AdView
증상은 앱을 실행시 바로 종료가 되는 현상.





위 구문이 가이드 그대로.. 잘보면 4번째와 5번째 퍼미션 " 앞에 공백이 들어가있다.

위 부분때문에 위 에러가 생겼는데 한참을 찾았다.


그 다음은 values 폴더에attrs.xml 파일을 추가시켜 <resources></resources> 사이에 가이드 내용을 넣어준다.


마지막으로 원하는 레이아웃 위치에 가이드에 있는 [CPC Sample Code] 부분을 추가시킨다.
xmlns:app=http://schemas.android.com/apk/res/com.cauly.adtest
app:appcode="CAULY"


위 부분에서 res/해당APP의 패키지명으로 바꾸고
appcode 부분에 처음에 APP등록을 마치고 받았던 코드를 입력해주면 끝.

앱을 실행시켜보면 광고가 뜨는데, 가끔 안뜰 때도 있는것 같다.

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

애드몹(Admob) 적용방법  (0) 2011.03.08
		
		String dirPath = getFilesDir().getAbsolutePath(); 
		File file = new File(dirPath); 
		
		// 일치하는 폴더가 없으면 생성
		if( !file.exists() ) {
			file.mkdirs();
			Toast.makeText(this, "Success", Toast.LENGTH_SHORT).show();
		}
		
		// txt 파일 생성
		String testStr = "ABCDEFGHIJK...";
		File savefile = new File(dirPath+"/test.txt");
		try{
			FileOutputStream fos = new FileOutputStream(savefile);
			fos.write(testStr.getBytes());
			fos.close();
			Toast.makeText(this, "Save Success", Toast.LENGTH_SHORT).show();
		} catch(IOException e){}
		
		// 파일이 1개 이상이면 파일 이름 출력
		if ( file.listFiles().length > 0 )
    		for ( File f : file.listFiles() ) {
    			String str = f.getName();
    			Log.v(null,"fileName : "+str);
    			
    			// 파일 내용 읽어오기
    			String loadPath = dirPath+"/"+str;
    			try {
    				FileInputStream fis = new FileInputStream(loadPath);
    			    BufferedReader bufferReader = new BufferedReader(new InputStreamReader(fis));
    				
    			    String content="", temp="";
    				while( (temp = bufferReader.readLine()) != null ) {
    					content += temp;
    				}
    				Log.v(null,""+content);
    			} catch (Exception e) {}
    		}


LogCat 결과
		if ( Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			String path = Environment.getExternalStorageDirectory()+"/android/data/pe.berabue.maptools/.image";

			File file = new File(path);
			String str;
			int num = 0;
			
			int imgCount = file.listFiles().length;	// 파일 총 갯수 얻어오기
			map = new Bitmap[imgCount];
				
			if ( file.listFiles().length > 0 )
				for ( File f : file.listFiles() ) {
					str = f.getName();				// 파일 이름 얻어오기
					map[num] = BitmapFactory.decodeFile(path+"/"+str);
					num++;
				}
		}
		FileInputStream fis = new FileInputStream(loadPath); // loadPath는 txt파일의 경로
		BufferedReader bufferReader = new BufferedReader(new InputStreamReader(fis));
				
		String str, str1="";
		String map[];

		while( (str = bufferReader.readLine()) != null )	// str에 txt파일의 한 라인을 읽어온다
			str1 += str;									// 읽어온 라인을 str1에 추가한다

		map = str1.split(",");								// 콤마(,)를 기준으로 map String 배열에 추가

		// 만약 0, 100, 123, 111, 122, 5 라면 map={0,100,123,111,122,5}
/* map log 저장 */
public void Save() {
  File file;
  String path = Environment.getExternalStorageDirectory()+"/android/data/pe.berabue.maptools/map";
  file = new File(path); 
  if( !file.exists() ) // 원하는 경로에 폴더가 있는지 확인
    file.mkdirs();
    
  file = new File(path+"/myTest11.txt");
  try{
    FileOutputStream fos = new FileOutputStream(file);
    fos.write(mMapManager.PrintLog().getBytes());
    fos.close();
    Toast.makeText(context, "Save Success", Toast.LENGTH_SHORT).show();
  } catch(IOException e){}
} 

맵툴 제작에 사용중인 소스.

경로를 얻어와 폴더가 없으면 폴더를 생성하고 내용을 받아와 파일을 생성한다.

구현중 : 텍스트 파일 이름 입력받기, 저장된 파일 리스트뷰로 나타내기

먼저 SD Card에 사용을 위해 퍼미션을 줘야한다.

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


import java.io.*;
import android.app.*;
import android.os.*;
import android.widget.*;

public class SDTest extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        String str = Environment.getExternalStorageState();
        if str.equals(Environment.MEDIA_MOUNTED)) {
        
          String dirPath = "/sdcard/android/data/pe.berabue.sdtest/temp"
          File file = new File(dirPath)
          if!file.exists() )  // 원하는 경로에 폴더가 있는지 확인
            file.mkdirs();
        }
        else
          Toast.makeText(SDTest.this, "SD Card 인식 실패", Toast.LENGTH_SHORT).show();
    }
}



file.mkdirs()와 file.mkdir()의 차이점

mkdirs()는 원하는 경로의 상위 폴더가 없으면 상위 폴더까지 생성.
ex ) sdcard/android/data/aaa/bbb
bbb 폴더를 만드려는데 aaa폴더가 없다면 aaa 폴더까지 생성 한다.

mkdir()은 지정 폴더만 생성.



구글에서 권장하는 폴더명은

android/data/패키지명/폴더명 


Constants
String ACCESS_CHECKIN_PROPERTIES Allows read/write access to the "properties" table in the checkin database, to change values that get uploaded.
String ACCESS_COARSE_LOCATION Allows an application to access coarse (e.g., Cell-ID, WiFi) location
String ACCESS_FINE_LOCATION Allows an application to access fine (e.g., GPS) location
String ACCESS_LOCATION_EXTRA_COMMANDS Allows an application to access extra location provider commands
String ACCESS_MOCK_LOCATION Allows an application to create mock location providers for testing
String ACCESS_NETWORK_STATE Allows applications to access information about networks
String ACCESS_SURFACE_FLINGER Allows an application to use SurfaceFlinger's low level features
String ACCESS_WIFI_STATE Allows applications to access information about Wi-Fi networks
String ACCOUNT_MANAGER Allows applications to call into AccountAuthenticators.
String AUTHENTICATE_ACCOUNTS Allows an application to act as an AccountAuthenticator for the AccountManager
String BATTERY_STATS Allows an application to collect battery statistics
String BIND_APPWIDGET Allows an application to tell the AppWidget service which application can access AppWidget's data.
String BIND_DEVICE_ADMIN Must be required by device administration receiver, to ensure that only the system can interact with it.
String BIND_INPUT_METHOD Must be required by an InputMethodService, to ensure that only the system can bind to it.
String BIND_REMOTEVIEWS Must be required by a RemoteViewsService, to ensure that only the system can bind to it.
String BIND_WALLPAPER Must be required by a WallpaperService, to ensure that only the system can bind to it.
String BLUETOOTH Allows applications to connect to paired bluetooth devices
String BLUETOOTH_ADMIN Allows applications to discover and pair bluetooth devices
String BRICK Required to be able to disable the device (very dangerous!).
String BROADCAST_PACKAGE_REMOVED Allows an application to broadcast a notification that an application package has been removed.
String BROADCAST_SMS Allows an application to broadcast an SMS receipt notification
String BROADCAST_STICKY Allows an application to broadcast sticky intents.
String BROADCAST_WAP_PUSH Allows an application to broadcast a WAP PUSH receipt notification
String CALL_PHONE Allows an application to initiate a phone call without going through the Dialer user interface for the user to confirm the call being placed.
String CALL_PRIVILEGED Allows an application to call any phone number, including emergency numbers, without going through the Dialer user interface for the user to confirm the call being placed.
String CAMERA Required to be able to access the camera device.
String CHANGE_COMPONENT_ENABLED_STATE Allows an application to change whether an application component (other than its own) is enabled or not.
String CHANGE_CONFIGURATION Allows an application to modify the current configuration, such as locale.
String CHANGE_NETWORK_STATE Allows applications to change network connectivity state
String CHANGE_WIFI_MULTICAST_STATE Allows applications to enter Wi-Fi Multicast mode
String CHANGE_WIFI_STATE Allows applications to change Wi-Fi connectivity state
String CLEAR_APP_CACHE Allows an application to clear the caches of all installed applications on the device.
String CLEAR_APP_USER_DATA Allows an application to clear user data
String CONTROL_LOCATION_UPDATES Allows enabling/disabling location update notifications from the radio.
String DELETE_CACHE_FILES Allows an application to delete cache files.
String DELETE_PACKAGES Allows an application to delete packages.
String DEVICE_POWER Allows low-level access to power management
String DIAGNOSTIC Allows applications to RW to diagnostic resources.
String DISABLE_KEYGUARD Allows applications to disable the keyguard
String DUMP Allows an application to retrieve state dump information from system services.
String EXPAND_STATUS_BAR Allows an application to expand or collapse the status bar.
String FACTORY_TEST Run as a manufacturer test application, running as the root user.
String FLASHLIGHT Allows access to the flashlight
String FORCE_BACK Allows an application to force a BACK operation on whatever is the top activity.
String GET_ACCOUNTS Allows access to the list of accounts in the Accounts Service
String GET_PACKAGE_SIZE Allows an application to find out the space used by any package.
String GET_TASKS Allows an application to get information about the currently or recently running tasks: a thumbnail representation of the tasks, what activities are running in it, etc.
String GLOBAL_SEARCH This permission can be used on content providers to allow the global search system to access their data.
String HARDWARE_TEST Allows access to hardware peripherals.
String INJECT_EVENTS Allows an application to inject user events (keys, touch, trackball) into the event stream and deliver them to ANY window.
String INSTALL_LOCATION_PROVIDER Allows an application to install a location provider into the Location Manager
String INSTALL_PACKAGES Allows an application to install packages.
String INTERNAL_SYSTEM_WINDOW Allows an application to open windows that are for use by parts of the system user interface.
String INTERNET Allows applications to open network sockets.
String KILL_BACKGROUND_PROCESSES Allows an application to call killBackgroundProcesses(String).
String MANAGE_ACCOUNTS Allows an application to manage the list of accounts in the AccountManager
String MANAGE_APP_TOKENS Allows an application to manage (create, destroy, Z-order) application tokens in the window manager.
String MASTER_CLEAR
String MODIFY_AUDIO_SETTINGS Allows an application to modify global audio settings
String MODIFY_PHONE_STATE Allows modification of the telephony state - power on, mmi, etc.
String MOUNT_FORMAT_FILESYSTEMS Allows formatting file systems for removable storage.
String MOUNT_UNMOUNT_FILESYSTEMS Allows mounting and unmounting file systems for removable storage.
String NFC Allows applications to perform I/O operations over NFC
String PERSISTENT_ACTIVITY This constant is deprecated. This functionality will be removed in the future; please do not use. Allow an application to make its activities persistent.
String PROCESS_OUTGOING_CALLS Allows an application to monitor, modify, or abort outgoing calls.
String READ_CALENDAR Allows an application to read the user's calendar data.
String READ_CONTACTS Allows an application to read the user's contacts data.
String READ_FRAME_BUFFER Allows an application to take screen shots and more generally get access to the frame buffer data
String READ_HISTORY_BOOKMARKS Allows an application to read (but not write) the user's browsing history and bookmarks.
String READ_INPUT_STATE Allows an application to retrieve the current state of keys and switches.
String READ_LOGS Allows an application to read the low-level system log files.
String READ_PHONE_STATE Allows read only access to phone state.
String READ_SMS Allows an application to read SMS messages.
String READ_SYNC_SETTINGS Allows applications to read the sync settings
String READ_SYNC_STATS Allows applications to read the sync stats
String REBOOT Required to be able to reboot the device.
String RECEIVE_BOOT_COMPLETED Allows an application to receive the ACTION_BOOT_COMPLETED that is broadcast after the system finishes booting.
String RECEIVE_MMS Allows an application to monitor incoming MMS messages, to record or perform processing on them.
String RECEIVE_SMS Allows an application to monitor incoming SMS messages, to record or perform processing on them.
String RECEIVE_WAP_PUSH Allows an application to monitor incoming WAP push messages.
String RECORD_AUDIO Allows an application to record audio
String REORDER_TASKS Allows an application to change the Z-order of tasks
String RESTART_PACKAGES This constant is deprecated. The restartPackage(String) API is no longer supported.
String SEND_SMS Allows an application to send SMS messages.
String SET_ACTIVITY_WATCHER Allows an application to watch and control how activities are started globally in the system.
String SET_ALARM Allows an application to broadcast an Intent to set an alarm for the user.
String SET_ALWAYS_FINISH Allows an application to control whether activities are immediately finished when put in the background.
String SET_ANIMATION_SCALE Modify the global animation scaling factor.
String SET_DEBUG_APP Configure an application for debugging.
String SET_ORIENTATION Allows low-level access to setting the orientation (actually rotation) of the screen.
String SET_PREFERRED_APPLICATIONS This constant is deprecated. No longer useful, seeaddPackageToPreferred(String) for details.
String SET_PROCESS_LIMIT Allows an application to set the maximum number of (not needed) application processes that can be running.
String SET_TIME Allows applications to set the system time
String SET_TIME_ZONE Allows applications to set the system time zone
String SET_WALLPAPER Allows applications to set the wallpaper
String SET_WALLPAPER_HINTS Allows applications to set the wallpaper hints
String SIGNAL_PERSISTENT_PROCESSES Allow an application to request that a signal be sent to all persistent processes
String STATUS_BAR Allows an application to open, close, or disable the status bar and its icons.
String SUBSCRIBED_FEEDS_READ Allows an application to allow access the subscribed feeds ContentProvider.
String SUBSCRIBED_FEEDS_WRITE
String SYSTEM_ALERT_WINDOW Allows an application to open windows using the type TYPE_SYSTEM_ALERT, shown on top of all other applications.
String UPDATE_DEVICE_STATS Allows an application to update device statistics.
String USE_CREDENTIALS Allows an application to request authtokens from the AccountManager
String USE_SIP Allows an application to use SIP service
String VIBRATE Allows access to the vibrator
String WAKE_LOCK Allows using PowerManager WakeLocks to keep processor from sleeping or screen from dimming
String WRITE_APN_SETTINGS Allows applications to write the apn settings
String WRITE_CALENDAR Allows an application to write (but not read) the user's calendar data.
String WRITE_CONTACTS Allows an application to write (but not read) the user's contacts data.
String WRITE_EXTERNAL_STORAGE Allows an application to write to external storage
String WRITE_GSERVICES Allows an application to modify the Google service map.
String WRITE_HISTORY_BOOKMARKS Allows an application to write (but not read) the user's browsing history and bookmarks.
String WRITE_SECURE_SETTINGS Allows an application to read or write the secure system settings.
String WRITE_SETTINGS Allows an application to read or write the system settings.
String WRITE_SMS Allows an application to write SMS messages.
String WRITE_SYNC_SETTINGS Allows applications to write the sync settings

'Android > Etc.' 카테고리의 다른 글

Max OS에서 NDK 개발하기  (1) 2012.07.04
넥서스S USB 드라이버 다운  (0) 2011.04.18
Orientation 고정, 키보드 숨기기  (0) 2011.04.17
멀티터치 구현하기  (0) 2011.03.16
데이터 저장 (SharedPreferences)  (0) 2011.01.25
앞으로 구글맵을 공부하면서 넣을 기능.

1. 내 위치 찾기
2. 내 위치 저장하기
3. 저장된 위치 삭제하기
4. 저장된 위치와 내 위치 비교(선 긋기)
5. 나침반

일단 구글맵을 띄우고 메뉴버튼을 눌렀을때 옵션을 넣었습니다.


public abstract MenuItem add (int groupId, int itemId, int order, CharSequence titleRes)
메뉴의 그룹과 정렬 방식은 필요하지 않으니 0으로 두고 고유번호와 이름만 넣었습니다.

MyGps.java

  /* 옵션 추가 */
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    menu.add(010"내 위치");
        menu.add(020"위치 저장");
        menu.add(030"저장된 위치");
        menu.add(040"종료");
        return true;
  }

  /* 옵션 기능 */
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case 1:    // 내 위치
        break;
      case 2:    // 위치 저장
        break;
      case 3:    // 저장된 위치
        break;
      case 4:    // 종료
        finish();
    }
    return true;
  }

아무런 문제가 없지만 프로젝트폴더에만 x 표시가 뜨고 아래와 같은 에러메시지가 나온다면

your project contains error(s), please fix them before running your application

메뉴바 -> project -> clean 

에뮬 실행시 emulator: ERROR: the user data image is used by another emulator. aborting 라는 문구가 뜨면

특정 폴더를 지우거나 뭘 하거나 방법이 있지만..

가끔 그래도 계속 안될때가 생긴다면.. 그냥 그게 귀찮다면..

에뮬을 껏다 키기 귀찮아서 안꺼도 되는 방법으로

윈도우키+R -> cmd 입력. (명령프로프트 실행)

안드로이드가 설치된 폴더에 tools로 이동

adb kill-server 입력

adb start-server 입력

이제 에뮬이 잘 작동한다! 




ERROR/MapActivity(8037): Couldn't get connection factory client

구글맵을 띄우려고 했는데 단말기에서 테스트를 해봤더니 에러가뜬다...



구글맵을 띄우려면 API KEY가 있어야합니다

에뮬상에서는 디버그용키만 있어도 사용이 가능하지만 실제 단말기에서는 릴리즈용키가 없다면 바둑판모양 배경만 보입니다.

하루종일 찾아봤지만 릴리즈용키에대한 정보는 그리 많은것 같지않아 정리해둬야겠다는 생각이..

릴리즈용키로 API KEY를 얻게되면 APK가 서명되지 않았다면 맵이 정상적으로 작동하지 않아요.


일단, 릴리즈용키를 만들려면 서명된 keystore가 있어야하구요.

keystore 생성 참고
http://www.androidpub.com/?mid=android_dev_info&sort_index=voted_count&order_type=desc&document_srl=56913



jdk\bin 폴더안에 keytool이 있는데, 이를 편하게 사용하기 위해 환경변수 설정이 안되어있다면

bin폴더를 환경변수에 추가시켜줍니다.





환경변수 설정이 끝났으면 윈도우키 + R을 누르고 cmd를 입력하여 명령프롬프트창을 열고

서명이 완료된 keystore가 있는곳으로 이동.

keytool -list -v -keystore androidkeystore 라고 입력을하고 keystore에 설정했던 비밀번호를 입력.



keystore를 만들때 입력했던 정보가 뜨는데, 이중에서 MD5라고 쓰여있는 FE:5D:...........82:8E 모두 복사.


 

위 페이지로 이동해 복사한 값을 빈칸에 적어주고 Generate API Key 클릭!

빨간색 사각형안에 있는 Key값을 잘 저장해 놓으면 됩니다.



처음에 이 키값을 넣고 맵으 띄웠는데 바둑판 모양만 나와서 왜그런가 했는데..

크롬으로 돌려보니 서명이 된 응용프로그램에서 사용 할 수 있다고 쓰여있군요...


키값을 넣어주고 APK에 서명을 해준뒤 실행해 보았더니 잘되네요!



Manifest


    

    
        
            
                
                
            
        
	
    
    
	

퍼미션과 라이브러리 추가.
 

 

main.xml


	

위에서 얻어온 Key 값을 대입해 준다.
 

 

MainActivity.java
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;

import android.os.Bundle;

public class MyGps extends MapActivity {
    /** Called when the activity is first created. */

	public static MapView mMapView;
	public static MapController mMapController;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

		mMapView = (MapView)findViewById(R.id.mapView);
		mMapController = mMapView.getController();
		mMapController.setZoom(18);						// 기본줌 18
		mMapView.setBuiltInZoomControls(true);			// 확대 축소 기능

	//	mMapView.setSatellite(true);					// 위성모드
		mMapView.setStreetView(true);					// 지도모드
    }

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}
}
지도 출력시 줌을 18로 설정.
setZoom(); 1 ~ 21 까지 사용 가능. 위성지도 사용시 한국에서는 보안상 최대 16까지 사용가능. (15였나?)



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

[MyGps_04] 주소 가져오기  (0) 2011.04.18
[MyGps_03] 내 위치 찾기  (0) 2011.04.17
[MyGps_02] 구글맵 메뉴 옵션 넣기  (0) 2011.01.26

private SharedPreferences pref;
  
    // 데이터 가져오기
    pref = context.getSharedPreferences("score"0)
    high_Score = pref .getInt("key_Score"0);
 
         ---------------------------------------------------------------
         context.getSharedPreferences("score"0)
     "score"는 단말기내의 공간에 score.xml을 참조한다.
     0은 권한을 뜻하는데 어떻게 score.xml이 생기는지 어떤 권한인지는 아직 모르겠다.
 
         high_Score 변수에 키 값이 "key_Score"라고 저장된 Int형 값을 가져온다.
         key_Score라는 키 값이 없으면 디폴트로 0을 가져온다.
 
      // 데이터 저장
      SharedPreferences.Editor ed = pref.edit()
      ed.putInt("key_Score", score)
      ed.commit();

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

             key_Score 라는 키 값을 갖는 Int형 저장소에 score를 저장한다.

             commit(); 을 완료해 주어야 값이 저장된다.

'Android > Etc.' 카테고리의 다른 글

Max OS에서 NDK 개발하기  (1) 2012.07.04
넥서스S USB 드라이버 다운  (0) 2011.04.18
Orientation 고정, 키보드 숨기기  (0) 2011.04.17
멀티터치 구현하기  (0) 2011.03.16
Permission  (0) 2011.01.26
</style>

ListView를 사용할때는 어댑터를 이용한다.

// 어댑터 준비

arrAdapter = new ArrayAdapter<String>(this, R.layout.list_text_style, arrData);

위와 같이 어댑터를 생성할때 두 번째 값에 자신이 만든 *.xml 파일을 지정하면된다.

R.layout.list_text_style.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:paddingTop="10dp"
 android:textSize="25dp"
 android:textColor="#FFF000"
 />

 

안드로이드 메뉴얼을 보면 총 8가지의 센서가 있습니다.

가속, 회전, 밝기, 자기, 방향, 압력, 근접, 온도

단말기에 따라 들어있는 센서의 수 는 다르며, 갤럭시S의 경우에는 5가지센서가 있습니다.


1. 설치하기

SensorSimulator 다운받으신 다음 압축을 풀어주세요.

sensorsimulator\bin 폴더를 보면

SensorSimulatorSettings.apk

sensorsimulator.jar  두개의 파일이 있습니다.

우선 설치를 하기전에 AVD(가상기기)를 실행시켜 주세요.

윈도우키 + R -> cmd 입력.

SensorSimulatorSettings.apk 파일을 안드로이드 sdk가 깔려있는 폴더안의 tools안에 넣습니다.

그리고, adb install SensorSimulatorSettings.apk 라고 입력합니다.

설치가 완료되면 sensorsimulator.jar 파일이 있는 곳으로 이동하여

java -jar sensorsimulator.jar를 입력하여 시뮬레이터를 실행시켜줍니다.

명령프롬프트 창을 닫으면 시뮬레이터가 꺼지니 주의하세요.



이제 AVD에 설치한 센서앱을 실행하여 줍니다.

시뮬레이터에 보이는 IP주소소켓을 앱에 똑같이 입력해주세요



앱에 IP주소와 소켓입력을 끝냈으면 Testing으로 이동하여 connect를 눌러주세요.

시뮬레이터상에 incoming connection opened 라는 메시지가 나오면 연결 성공.

앱에 orientation, accelerometer, magnetic filed 를 체크 한 후 시뮬레이터의 폰모양을 움직이면

시뮬레이터와 앱상의 좌표가 모두 변화하는 것을 볼 수 있습니다.



Yaw - 화면의 세로축을 기준으로 단말기 회전

Pitch - 단말기의 가로축을 기준으로 단말기 회전

Roll - 단말기의 세로축을 기준으로 단말기 회전

Yaw & Pitch - 화면의 세로축과 단말기의 가로축을 기준으로 단말기 회전

Roll & Pitch - 단말기의 세로축과 단말기의 가로축을 기준으로 단말기 회전

Move - 화면의 가로 세로축을 기준으로 단말기를 평면 이동

 

2. 데모 소스 실행

sensorsimulator\samples 폴더안에 데모파일이 있습니다.

import시켜 프로젝트를 가져옵니다.

프로젝트에 빨간 느낌표가 뜰텐데 프로젝트를 클릭하고 Alt + Enter키를 눌러 Android로 가면

타겟이 지정되어 있지 않는데요 타겟을 적절하게 지정해주세요.

그리고 Java Build Path로 넘어가서 Source를 보면 gen폴더가없으니 추가 시켜줍니다.



Ctrl + F11 키를 눌러서 AVD에 설치하고 실행을한뒤 시뮬레이터를 움직이면 센서 값이 바뀌는것을 볼 수 있습니다.

+ Recent posts