Top 20 Free Windows Mobile Applications

20 Free Applications for Windows Mobile

1. Facebook – Facebook has now become the most famous social network, connecting millions of people around the World. So, Microsoft has developed the official Facebook client for Windows Mobile. Now, keep updated with the latest news and posts with Facebook on your phone.

windowsmobile facebook

2. TwitTodayTwitter is one of the most popular micro blogging client.With TwitToday, you can control all your twitter activities and tweet from your windows mobile easily. Once installed, it adds a textbox to the Today screen of a Windows Mobile phone.

3. NET Compact Framework 3.5 – Most of the applications require .net framework to run. It’s an official pack which contains the common language runtime and class libraries built for the .NET Compact Framework.

4. ViigoViigo is a free, fast and easy to use RSS reader which provides the best way to read anything on your Blackberry and Windows Mobile. Viigo provides Instant access to favorite blogs, breaking news, entertainment, sports, finance, weather, flight schedules, restaurant reviews, games, local attractions, and much more.

5. Google Maps Mobile – Google Maps is a free app which lets you determine your current location with or without GPS using Maps. Just visit m.google.com/maps on your mobile.

6. TreeSize Mobile – TreeSize Mobile helps to easily locate the big files on your Smartphone when it runs out of disk space. The file system is represented in a tree view and it shows you the size of folders, including their subfolders.

7. CleanRAM – CleanRAM is an useful utility which can clean up the wasted RAM memory without having to restart the device. It offers various functionalities unlike other tools. There are 3 levels (Basic purge, Quality purge, Fundamental purge) to perform RAM cleanup.

clean ram clean-ram-settings

You can choose custom processes to clean and schedule the clean up at a specific time. This is surely an amazing tool for Windows mobile users. Give it a try!

8. Pocket RAR – Pocket RAR is the WinRAR version for PocketPC, the popular and successful file compressor for windows. It allows you to compress and decompress any file using your PocketPC without the need of PC. It has a very intuitive interface.

9. iFonz 2 – iFonz is a perfect theme which provides a complete iphone interface to your windows mobile. It includes a lots of customization and a fully graphical design and animations for Windows Mobile 5/6 completely written in .NET.

10. Nitrogen 1.0 – Nitrogen is a powerful audio player to enjoy your music on your phone. It allows you to play MP3/OGG songs stored on your Pocket PC device. It features a file browser, full skin support, smart shuffle and repeat modes, a 10-band equalizer, built-in sleep mode.

windowsmobile-nitrogen

11. DivX Mobile Player – DivX Mobile Player is the official DivX player for smartphones and any other Windows Mobile devices. It supports a wide range of formats, so you can play DivX videos with no problems. You can view the videos in full screen, forward or rewind, rotate the video, synchronize, etc.

12. S2P (Slide 2 Play) – S2P is a stylus-free MP3/WMA player application. It simply lets you browse your music files & play. It fully integrates with S2U2 & supports A2DP & AVRCP as well. It also features a very cool and intuitive interface.

13. Opera Mobile – Opera Mobile is the most popular browser to access Internet on smartphones. Though it’s not free like Opera Mini but its beta version is absolutely free to use. Its advanced features include: Opera Turbo, Widgets, tabbed browsing, Pan and zoom, Save pages and/or images, History and bookmarks and much more.. It truly delivers an ultimate web experience.

14. Skyfire – Skyfire is a free mobile web browser which runs on Windows Mobile (smartphones and PPC) and Nokia N and E Series (Symbian S60, 3rd Edition) phones. It provides a PC like browsing experience with speedy page loads, full video, images and audio. It supports video and audio streaming along with full Flash and Windows Media videos.

15. w0lf’s Translator – WOlf’s Translator uses the Google Translate engine to provide translations. It’s a small program to translate from/to many languages at any time. It has Auto-detect feature to know the input language. It requires .Net Compact Framework 3.5 has to be installed on the device.

wolfs translator

16. EverNote – Evernote is an application and web service that lets you capture, store and synchronize all information on your PDA, PC and online. Now, you can Create text notes and quickly access and search them whenever you like. It allows you to send snapshots, capture web clippings, store voice notes, images and files. You’ll need to sign up for a free Evernote account to use it.

17. HD Tweak & Diamond Tweak – Diamond Tweak and HD Tweak have been specifically designed forHTC devices. This free programs lets you tweak, customize and optimize your windows mobile as you want. Read the installation and Useinstructions before trying out this app. It also includes the AppToDate support.

18. Adobe Reader 7.0 – Adobe Acrobat Reader is the tiny version of Adobe reader specially designed for Pocket PC and Windows mobile. It allows viewing PDF files in high quality even on smaller screens, while preserving their rich content. You can easily share or submit your data formsover theInternet. PDF can be viewed in portrait or landscape mode on your handheld device.

19. Macromedia Flash Player 7 – Nowadays, most of the websites includes flash content which require a flash addon. Flash Player 7 is an official app from Adobe, which allows viewing Flash content embedded in web pages. Developers can also start developing and experiencing rich Flash content, enterprise applications and mobile services right from their Pocket PC.

20. Pocket Uno Uno is one of the world’s most popular family card games to play on WM. Just play cards from your hand by matching color, number, or word. Try to rid yourself of cards before opponents do.

windowsmobile-uno

Check the game rules and instructions on their site. Have Fun!

Lars Vogel

Version 1.7

13.01.2009

Revision History
Revision 0.104.07.2009Lars Vogel
Created
Revision 0.208.07.2009Lars Vogel
First working example
Revision 0.330.08.2009Lars Vogel
Improved description
Revision 0.430.10.2009Lars Vogel
Updated to use Android 2.0
Revision 0.501.11.2009Lars Vogel
Started XML support
Revision 0.602.11.2009Lars Vogel
Added the android log view
Revision 0.703.11.2009Lars Vogel
Access to the shell access, uninstall android application
Revision 0.804.11.2009Lars Vogel
Networking
Revision 0.905.11.2009Lars Vogel
Added the usage of SharedPreferences
Revision 1.006.11.2009Lars Vogel
Usage of ContentProvider
Revision 1.110.11.2009Lars Vogel
Assign handler to button via XML (thanks to Jason Arora for the tip)
Revision 1.221.11.2009Lars Vogel
Emulator console added
Revision 1.322.11.2009Lars Vogel
Authorization mentioned
Revision 1.425.11.2009Lars Vogel
Google API, location API, MapView
Revision 1.513.12.2009Lars Vogel
Fixed text for button assignment
Revision 1.630.12.2009Lars Vogel
Fixed typo
Revision 1.713.01.2009Lars Vogel
Updated screenshot

Programming with Google Android and Eclipse

This article describes how to create Android applications with Eclipse.

The article is based on Eclipse 3.5 and Android 2.0.


1.Overview

1.1.Android

Android is an operating system based on Linux with a Java programming interface. It provides tools, e.g. a compiler, debugger and a device emulator as well as its own Java Virtual machine (Dalvik).

Android is created by the Open Handset Alliance which is lead by Google.

Android uses a special Java virtual machine (Dalvik) which is based on the Apache Harmony Java implementation. Dalvik uses a special Bytecode so that you have to use the Android compiler to create this special byte-code.

Android supports 2-D and 3-D graphics using the OpenGL libraries and supports data storage in a SQLLite database.

For development Google provides the Android Development Tools (ADT) for Eclipse to develop Android applications.

1.2.Android Application

An Android application consists out of the following parts:

  • Activity - A screen in the Android application

  • Intent / Broadcast Receiver - allow the application to request and / or provide services from other application. For example the application call ask via an intent for a contact application. Application register themself via an IntentFilter

  • Services - Background activities without UI

  • Content Provider - provides data to applications, Android contains a SQLLite DB which can serve as data provider

An Android application is described the file "AndroidManifest.xml". This files contains all classes of the application and the required permissions for the application, e.g. if the application requires network access. "AndroidManifest.xml" can be thought as the deployment descriptor for an Android application.

2.Installation

The following assume that you have already Eclipse install. For installing and using Eclipse please see Eclipse Tutorial

To use Android you need to install the Eclipse Android Plugin and the base Android SDK. Afterwards you can install different Android versions via the Eclipse Android plugin . You will also need to configure a device which will be used to emulate your real device.

2.1.Eclipse

Use the update manager of Eclipse to install all available plugins for the Android Development Tools (ADT) from the URL https://dl-ssl.google.com/android/eclipse/ . See Using the Eclipse update manager for details on how to use the update manager and how to install new plugins.

Tip

Ehe Eclipse Android SDK does not seem to have an option to install the Android (Java) source code to make it available in Eclipse. Please join me in starring at bug Make Android Source available in Eclipse - Bug report .

2.2.Android

Download the Android SDK from the Android homepage under Android Homepage .

The download contains a zip file which you can extract to any place in your file system, e.g. I placed it under "c:\android-sdk-windows" .

2.3.Configuration

In Eclipse open the Preferences dialog via Windows -> Preferences. Select Android and maintain the installation path of the Android SDK.

Tip

If you maintain the location the Android plugin will remind you frequently (and for every workspace). Join me in starring at Bug 3210 to get this improved.

Select now Window -> Android SDK and AVD Manager from the menu.

Select available packages and select everything expect the older version of the SDK.

Press "Install selected" and confirm the license for all package.

After the installation restart Eclipse.

2.4.Device

You need to define a device which can be used for emulation. Press the device manager button, press "New" and maintain the following.

Press "Create AVD".

To test if you setup is correct, eelect your device and press "Start".

After (a long time) your device should be started.

Tip

You can use the perspective "DDMS" to monitor your device.

3.Your first Android project

3.1.Create Project

. Select File -> New -> Other -> Android -> Android Project and create the Android project "de.vogella.android.first" Maintain the following.

Tip

I think this wizard should have the option to add the project to an existing working set. Please stare at Issue 4523 to get this functionality.

Press "Finish".

This should create the following directory structure.

R.java is a generated class which contains the text and the UI elements. Please do not try to modify this class manually.

3.2.Add UI Elements

Select main.xml and open the editor via double-click. The result should look like the following.

From the "Views" bar, drag in an "EditText" and three "Buttons". The result should look like the following.

Tip

Check R.javait will contain your new elements.

3.3.Create and use attributes

Select "string.xml" and press "Add".

Select color and maintain "white" as the name and "#FFFFFF" as the value.

Go back to "main.xml", select the complete widget and use the Properties view to set the background to this attribute.

3.4.Code your applicatioin

Change your code in "Hello.java" to the following.

				package de.vogella.android.first;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.widget.EditText;public class Hello extends Activity {	private EditText text;	/** Called when the activity is first created. */	@Override	public void onCreate(Bundle savedInstanceState) {		super.onCreate(savedInstanceState);		setContentView(R.layout.main); // bind the layout to the activity		text = (EditText) findViewById(R.id.EditText01);		text.setText("No button pressed");	}	// Will be connected with the buttons via XML	public void myClickHandler(View view) {		switch (view.getId()) {		case R.id.Button01:			text.setText("Button 1 was clicked");			break;		case R.id.Button02:			text.setText("Button 2 was clicked");			break;		case R.id.Button03:			text.setText("Button 3 was clicked");			break;		}	}}			

Tip

The next chapter will connect the handler methods with the buttons via XML.

3.5.Define the button handler

Open again main.xml and select your first button. Via the property view assign the method "myClickHandlerButton" to the "on Click" property of the first button.

Assign "myClickHandlerButton" to the other buttons.

The resulting main.xml should look like the following.

				<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:background="@color/white"><TextView      android:layout_width="fill_parent"     android:layout_height="wrap_content"     android:text="@string/hello"    /><EditText android:text="@+id/EditText01" android:id="@+id/EditText01" android:layout_width="wrap_content" android:layout_height="wrap_content"></EditText><Button android:text="@+id/Button01" android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="myClickHandler"></Button><Button android:text="@+id/Button02" android:id="@+id/Button02" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="myClickHandler"></Button><Button android:text="@+id/Button03" android:id="@+id/Button03" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="myClickHandler"></Button></LinearLayout>			

3.6.Start Project

To start the Android Application, select your project, right click on it, Run-As-> Android Application

Tip

Be patient, the emulator is sometimes very slow.

You should get the following result.

3.7.Using the phone menue

If you press the Home button you can also select your application.

4.Important views

4.1.Log

You can see the log (including System.out.print() statements) via the LogCat view.

4.2.File explorer

The file explorer allows to see the files on the android simulator.

5.Networking

5.1.Networking

Android allows to access the network via the the java.net.URL class.

Tip

You can also read XML, e.g. RSS feeds. Unfortunately Android does not have a Stax parser included in it SDK. Vote for Android should have a Stax parser to get support. Currently you have to use the android specific class XmlPullParser.

5.2.Proxy

To set the proxy you can use the class Settings. For example you could add the following line to your onCreate method in your activity.

				Settings.System.putString(getContentResolver(), Settings.System.HTTP_PROXY, "myproxy:8080");			

Tip

It seems that DNS resolving doesn't work behind a proxy. See Bug 2764

5.3.Permissions

You also have to give your application the right to change the settings "android.permission.WRITE_SETTINGS" in "AndroidManifest.xml".

5.4.Example

Create the project "de.vogella.android.network.html". Add the following elements to your activity:

  • EditText with the ID "address"

  • TextView with the ID "pagetext"

  • Button with the ID "ReadWebPage"

Create the following code to read a webpage and show the HTML code in the TextView.

This example also demonstrate the usage of Android preferences to store user data. The URL which the user has typed is stored in the preferences in the method onPause(). This method is called whenever the Activity is send into the background.

				package de.vogella.android.network.html;import java.io.BufferedReader;import java.io.InputStreamReader;import java.net.URL;import android.app.Activity;import android.content.SharedPreferences;import android.content.SharedPreferences.Editor;import android.os.Bundle;import android.view.View;import android.widget.EditText;import android.widget.TextView;public class ReadWebpage extends Activity {	private static final String PREFERENCES = "PREFERENCES";	private static final String URL = "url";	private String lastUrl;	private EditText urlText;	private TextView textView;	/** Called when the activity is first created. */	@Override	public void onCreate(Bundle savedInstanceState) {		super.onCreate(savedInstanceState);		setContentView(R.layout.main);		urlText = (EditText) findViewById(R.id.address);		textView = (TextView) findViewById(R.id.pagetext);		loadPreferences();		urlText.setText(lastUrl);	}		/**	 * Demonstrates loading of preferences The last value in the URL string will	 * be loaded	 */	private void loadPreferences() {		SharedPreferences preferences = getSharedPreferences(PREFERENCES,				Activity.MODE_PRIVATE);		// Set this to the Google Homepage		lastUrl = preferences.getString(URL, "http://209.85.229.147");	}	@Override	protected void onPause() {		super.onPause();		SharedPreferences preferences = getSharedPreferences(PREFERENCES,				Activity.MODE_PRIVATE);		Editor preferenceEditor = preferences.edit();		preferenceEditor.putString(URL, urlText.getText().toString());		// You have to commit otherwise the changes will not be remembered		preferenceEditor.commit();	}		// Will be connected with the buttons via XML	public void myClickHandler(View view) {		switch (view.getId()) {		case R.id.ReadWebPage:			try {				textView.setText("");				// Perform action on click				URL url = new URL(urlText.getText().toString());				// Get the response				BufferedReader rd = new BufferedReader(						new InputStreamReader(url.openStream()));				String line = "";				while ((line = rd.readLine()) != null) {					textView.append(line);				}			}			catch (Exception e) {				System.out.println("Nay, did not work");				textView.setText(e.getMessage());			}			break;		}	}}			

Assign the handler "buttonHandler" to the button in the property "on Click". via your XML.

6.ContentProvider

6.1.Overview

ContentProvider are used to provide data from an application to another. ContentProvider do not store the data but provide the interface for other applications to access the data.

The following example will use an existing context provider from "Contacts".

6.2.Create Contacts

Start the contacts application and create a few contacts.

6.3.Example

Create a new Android project "de.vogella.android.contentprovider" with the activity "ContactsView".

Rename the id of the the existing TextView from the example wizard to "contactview". Delete the default text. Also change the layout_height to "fill_parent".

The resulting main.xml should look like the following.

				<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"	android:orientation="vertical" android:layout_width="fill_parent"	android:layout_height="fill_parent">	<TextView android:layout_width="fill_parent"		android:layout_height="fill_parent" android:id="@+id/contactview" /></LinearLayout>			

In Application.xml add the Permission that the application can use "android.permission.READ_CONTACTS".

Change now your coding of your activity.

				package de.vogella.android.contentprovider;import android.app.Activity;import android.database.Cursor;import android.os.Bundle;import android.provider.ContactsContract.Contacts;import android.widget.TextView;public class ContactsView extends Activity {	/** Called when the activity is first created. */	@Override	public void onCreate(Bundle savedInstanceState) {		super.onCreate(savedInstanceState);		setContentView(R.layout.main);		TextView contactView = (TextView) findViewById(R.id.contactview);		Cursor cursor = getContentResolver().query(Contacts.CONTENT_URI, null, null, null, null);		while(cursor.moveToNext()){			String displayName = cursor.getString(cursor.getColumnIndex(Contacts.DISPLAY_NAME));			contactView.append("Name: ");			contactView.append(displayName);			contactView.append("\n");		}	}}			

Tip

Currently the contentProvider does not return any data. Looks like the content provider has been changed but the content provider d0cumentation still refers to the People class. If you find a solution please email me.

7.Shell

7.1.Opening the Shell

You can access your Android emulator also via the console. Open a shell, switch to your "android-sdk" installation directory into the folder "tools".

Start the shell via the command "adb shell".

7.2.Emulator Console

The emulator console lets you dynamically access your simulated device. Use "telnet localhost 5554" to conntect to your simulated device. To exit the console session, use the command "quit" or "exit".

For example you can set your geolocation in the emulator via "geo fix -121.45356 46.51119 4392"

For more information on the emulator console please see Emulator Console manual

7.3.Uninstall an application

You can uninstall an android application via the shell. Switch the the data/app directory (cd /data/app) and simply delete your android application.

8.Location API

The location API allow you to determine your current location.

The following requires that you have installed the Googles API (see installation) and a valid Google map API key. Go to Obtaining a Maps API Key to get one.

8.1.Device with Google API

Create a new device which supports the Google API's.

8.2.Project and Permissions

Create a new project "de.vogella.android.locationapi". Make sure to select the Google API

Add the following permissions to your application in Android.xml.

  • INTERNET

  • ACCESS_FINE_LOCATION

  • ACCESS_COARSE_LOCATION

Tip

The maintenance of "Uses permissions" should be enhanced. Please stare at Bug: Permissions should support field assists to get this improved.

8.3.Google Map library

You need to add the Google maps library to your application. Open Android.xml, tab Application and add a "Uses library".

8.4.Layout

Define your view layout like the following.

				<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:id="@+id/mainlayout"    android:orientation="vertical"    android:layout_width="fill_parent"    android:layout_height="fill_parent" >    <com.google.android.maps.MapView        android:id="@+id/mapview"        android:layout_width="fill_parent"        android:layout_height="fill_parent"        android:clickable="true"        android:apiKey="Your Maps API Key"    /></RelativeLayout>			

Tip

Replace "Your Maps API Key" with your Google API key.

8.5.Activity

Create the following activity. This activity use an LocationListner to update the map with the current location.

				package de.vogella.android.locationapi;import android.content.Context;import android.location.Location;import android.location.LocationListener;import android.location.LocationManager;import android.os.Bundle;import android.widget.RelativeLayout;import android.widget.ZoomControls;import com.google.android.maps.GeoPoint;import com.google.android.maps.MapActivity;import com.google.android.maps.MapController;import com.google.android.maps.MapView;public class CurrentLocation extends MapActivity {	private MapController mapController;	private MapView mapView;	private LocationManager locationManager;	public void onCreate(Bundle bundle) {		super.onCreate(bundle);		setContentView(R.layout.main); // bind the layout to the activity		// create a map view		RelativeLayout linearLayout = (RelativeLayout) findViewById(R.id.mainlayout);		mapView = (MapView) findViewById(R.id.mapview);		ZoomControls mZoom = (ZoomControls) mapView.getZoomControls();		linearLayout.addView(mZoom);		mapController = mapView.getController();		// Zoon 1 is world view				mapController.setZoom(14);		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,				0, new GeoUpdateHandler());	}	@Override	protected boolean isRouteDisplayed() {		return false;	}	public class GeoUpdateHandler implements LocationListener {		@Override		public void onLocationChanged(Location location) {			int lat = (int) (location.getLatitude() * 1E6);			int lng = (int) (location.getLongitude() * 1E6);			GeoPoint point = new GeoPoint(lat, lng);			mapController.setCenter(point);//			setContentView(mapView);		}		@Override		public void onProviderDisabled(String provider) {		}		@Override		public void onProviderEnabled(String provider) {		}		@Override		public void onStatusChanged(String provider, int status, Bundle extras) {		}	}}			

8.6.Run and Test

Run and test your application. You should be able to zoon in and out. Use Emulator console to send geo-coordinates to your device for example

				geo fix 13.24 52.31			

Tip

See also Hello, MapView for an example how to put graphics on the map.

9.Thank you

Thank you for practicing with this tutorial.

Please note that I maintain this website in my private time. If you like the information I'm providing please help me by donating.

10.Questions and Discussion

For questions and discussion around this article please use the www.vogella.de Google Group. Also if you note an error in this article please post the error and if possible the correction to the Group.

I believe the following is a very good guideline for asking questions in general and also for the Google group How To Ask Questions The Smart Way.

Eclipse Java IDE - Tutorial

Lars Vogel

Version 1.6

30.12.2009

Revision History
Revision 0.118.07.2007Lars Vogel
Created.
Revision 0.2 - 0.718.05.2008Lars Vogel
Several reworks.
Revision 0.7.113.04.2009Lars Vogel
Added Shortcut
Revision 0.825.05.2009Lars Vogel
Update to Eclipse 3.5 (Galileo)
Revision 0.921.06.2009Lars Vogel
Moved Shortcuts to own article under http://www.vogella.de/articles/EclipseShortcuts/article.html
Revision 1.022.06.2009Lars Vogel
Moved Debugging to own article under http://www.vogella.de/articles/EclipseDebugging/article.html
Revision 1.128.06.2009Lars Vogel
Re-org article, own chapter for update manager, simplified views / editor description
Revision 1.212.07.2009Lars Vogel
Screenshot for link with editor
Revision 1.318.07.2009Lars Vogel
Added link to example with jars, changed from XML templates to Java template
Revision 1.402.08.2009Lars Vogel
more details on first Java program
Revision 1.501.11.2009Lars Vogel
Renamed first project, added details for jar handling
Revision 1.630.12.2009Lars Vogel
fixed package name in Java program outside Eclipse

Eclipse Java IDE

This article describes the usage of Eclipse as a Java IDE. It describes the installation of Eclipse, the creation of Java programs, the usage of external jars, quick fix and content assist and the usage of the Eclipse update manager.

This article is based on Eclipse 3.5 (Eclipse Galileo).


1.Eclipse Overview

Eclipse an open source community whose projects building tools and frameworks for creating general purpose application.

The most popular usage of Eclipse is as a Java development environment which will be described in this article.

2.Getting started

2.1.Installation

Download "Eclipse IDE for Java Developers" from the website Eclipse Downloads and unpack it to a directory. This is sufficient for Eclipse to be used; no additional installation procedure is required.

Tip

Use a directory path which does not contain spaces in its name.

Tip

Eclipse requires an installed Java Runtime. I recommended to use Java 6 (also known as Java 1.6).

2.2.Start Eclipse

To start Eclipse double-click on the file eclipse.exe in your installation directory.

The system will prompt you for a workspace. The workspace is the place there you store your Java projects (more on workspaces later). Select a suitable (empty) directory and press Ok.

Eclipse will start and show the Welcome page.

Close the welcome page by press in little x besides the Welcome.

3.Eclipse UI Overview

Eclipse provides perspectives, views and editors. Views and editors are grouped into perspectives. All projects are located in a workspace.

3.1.Workspace

The workspace is the physical location (file path) you are working in. You can choose the workspace during startup of eclipse or via the menu (File-> Switch Workspace-> Others).

All your projects, sources files, images and other artifacts will be stored and saved in your workspace.

Tip

To predefine the workspace you can use the startup parameter -data path_to_workspace, e.g. c:\eclipse.exe -data "c:\temp" Please note that you have to put the path name into brackets.

Tip

To see the current workspace directory in the title of Eclipse use -showLocation as additional parameter.

3.2.Perspective

A perspective is a visual container for a set of views and editors.

You can change the layout within a perspective (close / open views, editors, change the size, change the position, etc.)

Tip

A common problem is that you closed a view and don't know how to re-open this view. You can reset a perpective it to it original state via the menu "Window" -> "Reset Perspective".

Eclipse allow you to switch to another perspective via the menu Window->Open Perspective -> Other.

For Java development you usually use the "Java Perspective".

3.3.Views and Editors

A view is typically used to navigate a hierarchy of information or to open an editor. Changes in a view are directly applied.

Editors are used to modify elements. Editors can have code completion, undo / redo, etc. To apply the changes in an editor to the underlying resources, e.g. Java source file, you usually have to save.

4.Create your first Java program

The following will describe how to create a minimal Java program using Eclipse. It will be the classical "Hello World" program. Our program will write "Hello Eclipse!" to the console.

4.1.Create project

Select from the menu File -> New-> Java project. Maintain "de.vogella.eclipse.ide.first" as the project name. Select "Create separate source and output folders".

Press finish to create the project. A new project is created and displayed as a folder. Open the folder "de.vogella.eclipse.ide.first"

4.2.Create package

Create now a package. A good convention is to use the same name for the top package as the project. Create therefore the package "de.vogella.eclipse.ide.first".

Select the folder src, right mouse click on it and select New -> Package.

4.3.Create Java class

Right click on your package and select New -> Class

Create MyFirstClass, select the flag "public static void main (String[] args)"

Maintain the following code.

				package de.vogella.eclipse.ide.first;public class MyFirstClass {	public static void main(String[] args) {		System.out.println("Hello Eclipse!");	}}			

4.4.Run your project in Eclipse

Now run your code. Right click on your Java class and select Run-as-> Java application

Finished! You should see the output in the console.

4.5.Run your Java program outside Eclipse (create jar file)

To run your Java program outside of Eclipse you need to export it as a jar file. Select your project, right click on it and select "Export".

Select JAR file, select next. Select your project and maintain the export destination and a name for the jar file. I named it "myprogram.jar".

Press finish. This will create a jar file in your select output directory.

4.6.Run your program outside Eclipse

Open a command shell, e.g. under Microsoft Windows select Start -> Run and type in cmd. This should open a consle.

Switch to your output directory, e.g. by typing cd path, e.g. if you jar is located in "c:\temp" type "cd c:\temp".

To run this program you need to include the jar file into your classpath. See Classpath and Java JAR Files for details.

				java -classpath myprogram.jar de.vogella.eclipse.ide.first.MyFirstClass			

Congratulations! You created your first Java project, a package a tiny Java program and you ran this program inside Eclipse and outside

5.Content Assists and Quick Fix

Tip

For a list of the most important Eclipse shortcuts please see Eclipse Shortcuts

5.1.Content assist

The content assistant allows you to get input help in an editor. It can be invoked by CTRL + Space.

For example type syso and then press [Ctrl + Space] and it will be replaced by System.out.println(""). Or if you have an object, e.g. Person P and need to see the methods of this object you can type p. (or press CTRL + Space) which activates also the content assist.

5.2.Quick Fix

Whenever there is a problem Eclipse will underline the problematic place in the coding. Select this and press (Ctrl+1)

For example type "myBoolean = true;" If myBoolean is not yet defined, Eclipse will highlight it as an error. Select the variable and press "Ctrn+1", then Eclipse will suggest to create a field or local variable.

Quick Fix is extremely powerful, it allows you to create new local / field variables, new methods, classes, put try and catch around your exceptions, assign a statement to a variable etc.

6.Using jars (libraries)

6.1.Adding external library (.jar ) to the Java classpath

The following describes how to add external jars to your project.

The following assumes you have a jar available.

Tip

If you need an example for working with jars you can use JFreeChart Tutorial

Create a new Java project "de.vogella.eclipse.ide.jars". Create a new folder called "lib" (or use your existing folder) by right click on your project and selecting New -> Folder

From the menu select File -> Import -> File system. Select your jar and select the folder lib as target.

Select your project, right mouse click and select properties. Under libraries select "Add JARs".

The following example shows how the result would look like if junit-4.4.jar would be added to a project.

6.2.Show source code for jar

To browse the source of a type contained in library you can attach a source archive or source folder to this library. The editor will then show the source instead of a the decompiled code. Setting the source attachment also allows source level stepping with the debugger.

The Source Attachment dialog can be reached via:

Open the Java Build Path page of a project (Projects > Properties > Java Build Path). On the Libraries page expand the library's node and select the Source attachment attribute and press Edit

Maintain the location to the source attachement.

In the Location path field, enter the path of an archive or a folder containing the source.

6.3.Add the Javadoc for a jar

Download the javadoc of the jar and put it somewhere in your filesystem.

Open the Java Build Path page of a project (Projects > Properties > Java Build Path). On the Libraries page expand the library's node and select the Javadoc location attribute and press Edit

Maintain the location to the api.

7.Updates and Installation of Plugins

7.1.Eclipse Update Manager

Eclipse provides functionality via so-called features (which contain plugins). Eclipse 3.5 contains a Software Update Manager which allows you to update existing plugins and to install new plugins.

To update your existing installation select the menu Help -> Check for Updates. The system will verify if for the installed plugins updates are available or not.

To install new functionality, select Help-> Install New Software.

Select from the list a update site from which you would like to install new software. For example if you want to install new plugins from Galileo select the Galileo Update Site.

Tip

Sometimes you have to uncheck "Group items by category" – not all available Plugins are categorized. If they are not categorized they will not be displayed. See Eclipse bug .

To add a new update site select, press the button "Add" and input the URL. This will then make this update site available and will allow you to install software from this site.

7.2.Manual installation of plugins (dropins folder)

If you’re using Plugins where no Software Site is available, then you can use the Dropins folder in your Eclipse installation directory.

To do this put the plugin into Eclipse "dropins" folder and restart Eclipse. Eclipse should detect the new plugin and install it for you.

8.More Tips

8.1.Problems view

The problems view displays problems in your projects. You can open it via Windows -> Show View -> Problems

You can configure the problems view, e.g. if you only want to display the problems from the current selected project, select "Configure Contents".

8.2.Important Preference Settings

Eclipse allows to set semicolons (and other elements) automatically.

Eclipse allows to format the source code and to organize the imports at save.

Tip

You can export your Preferences settings from one workspace via File -> Export -> General -> Preferences. Similar you can import them again into your workspace.

8.3.Task Management

If you use // TODO in the coding this indicates a task for eclipse and you find it in the task view of Eclipse.

For more advanced tasks you can use Eclipse Mylyn Tutorial .

8.4.Working Sets

A common problem in Eclipse is that your data in your workspace grows and therefore your workspace is not well structured anymore. You can use working sets to organize your displayed projects / data. To setup your working set select in the Package Explorer -> Show -> Working Sets.

Press new on the following dialog to create a working set.

On the following dialog select java, select the source folder you would like to see and give it a name. You can now easily display only the files you want to see.

8.5.Synchronize package explorer with code display

The package explorer allows to display the associated file from the current selected editor. Example: if you working on foo.java and you change in the editor to bar.java then the display in the package explorer will change.

To activate this press "Link with Editor".

8.6.Code Templates

If you have to type frequently the same code / part of the d0cument you can maintain templates which can be activate via autocomplete (Ctrl + Space).

For example lets assume you are frequently creating "public void name(){}" methods. You could define a template which creates the method body for you.

To create a template for this select the menu Window->Preferences and Open Java -> Editor -> Templates

Press New. Create the following template. ${cursor} indicates that the cursor should be placed at this position after applying the template.

This this example the name "npm" is your keyword.

Now every time you type the keyword in the Java editor and press Ctrl+Space the system will replace your text with your template.

9.Next steps

To learn how to debug Eclipse Java programs you can use Eclipse Debugging

To learn Java Web development you can use with Servlet and JSP development with Eclipse Web Tool Platform (WTP) - Tutorial . If you want to develop rich stand-alone Java clients you can use Eclipse RCP - Tutorial

. Check out Eclipse Plugin Development - Tutorial to learn how to develop your own plugins.

Good luck in your journey of learning Java!

10.Thank you

Thank you for practicing with this tutorial.

Please note that I maintain this website in my private time. If you like the information I'm providing please help me by donating.

11.Questions and Discussion

For questions and discussion around this article please use the www.vogella.de Google Group. Also if you note an error in this article please post the error and if possible the correction to the Group.

I believe the following is a very good guideline for asking questions in general and also for the Google group How To Ask Questions The Smart Way.

12.Links and Literature

Developing open source Java applications with java.net and Eclipse

Part 1 - Creating a new project in Eclipse


Martin Pllu
martinpllu-AT-dev.java.net

Introduction


This series of tutorials show how Eclipse can be used to develop open source Java applications hosted on java.net. The target audience is developers who have a working knowledge of Java, but are new to Eclipse.


If you have any questions or feedback, please use the tutorial's discussion forums.


Today we'll see how to create a new project in Eclipse. Even if you don't need to do this (for example, if you plan to contribute to an existing project), I'd recommend that you follow along. The tutorial introduces some important Eclipse concepts.

In Part 2 we'll cover Team development with Eclipse and CVS.

Before we start the tutorial, let's look at some of the key features of Eclipse and java.net.

Key features of Eclipse


Eclipse provides a powerful and feature rich integrated development environment (IDE) for Java. To get an idea of what it can do, skim through the links below (from the online Eclipse help).
If you haven't used an IDE before, or last used one a few years ago, please check Eclipse out. You'll be amazed by its ease of use and advanced development features. I switched to Eclipse after years of developing in Emacs, and it's made me much more productive. It's worth using for the automated refactoring support alone!

Eclipse runs on Windows, Linux, Mac OSX, Solaris, AIX and HP-UX. It's written in Java, but uses a graphical toolkit called SWT. This toolkit is a Java wrapper for native platform widgets, and it produces a very slick look and feel.

Eclipse is actually a generic application platform with a sophisticated plugin architecture - the Java IDE is just one set of plugins. You can develop your own plugins, or use Eclipse as a basis for "rich client" applications, e.g. a web browser or a money manager. See the Platform Plug-in Developer Guide for more.

Eclipse is free open source software developed by the independent Eclipse Foundation, which is backed by industry heavy hitters such as IBM Rational, Borland, Red Hat, and SuSE. Its open source pedigree has made it ideal for open source development. For example, its built-in CVS client GUI (covered in Part 2) makes it a snap to work with CVS hosting sites like java.net.

The Eclipse d0cumentation is excellent - see the main website and the online help.

There's an active community of third party Eclipse plugin developers, both open source and commercial. Good plugin directories are available here and here. As an Eclipse user, you're regularly rewarded with great new features from official Eclipse releases and from the plugin development community.

Key features of java.net


java.net is a thriving online Java community featuring news, articles, forums, wikis, and hosting for many open source projects. It was founded in 2003 by Sun Microsystems to help encourage open source Java development, however (like the Eclipse Foundation) java.net is completely independent. A number of communities have been formed on java.net to cater for different technologies and interests, for example Java Tools, Java Enterprise, Jini, and Java Linux. Some communities such as Javapedia and Global Education and Learning are great places to learn about Java and to share knowledge. It's the communites that really set java.net apart from other development hosting websites (like sourceforge).

It's easy to set up a new project - all you need is a good idea and the Project Request Forms. You can browse the online project directory which includes both projects hosted at java.net and linked projects (which are hosted elsewhere but affiliated with java.net). Before starting a new project, please look at the existing projects to make sure that you're not reinventing the wheel. If your idea can be used to enhance an existing project, the end result is often better than several similar, but incompatible, projects. If you want to contribute to an existing project, speak to the owners listed on the project's website.

java.net uses CVS for version control of source code. If you haven't used CVS before, don't worry, Part 2 will give you a step-by-step guide. There's a Web interface for viewing the contents of files checked into CVS, for example see here. This is handy for linking to code or d0cumentation in CVS.

A number of useful tools are provided to help you work as part of a team, for example issue trackers, announcement boards, discussion forums, and mailing lists. Project owners can easily administer project memberships and roles. As a project member, you can choose to be notified by email whenever a project change is made, for example CVS checkins, new discussion forum entries, etc. RSS feeds are also available so that anyone can keep an eye on your project. Project webpages are easy to set up - you just check HTML into CVS. A good search engine is also provided for project-specific or site-wide searches.




Tutorial Part 1 - Setting up a new project in Eclipse


The instructions in this tutorial are based on Eclipse 3.0. Later versions of Eclipse 3.x may vary slightly.



In today's tutorial, we'll be working with Eclipse to create and configure a new Java project. We won't be working with java.net until the next instalment.

Prerequisites

  • Download Eclipse 3.0 or later from here.
  • Java 1.3 or later is required. If you don't already have a suitable Java installation, download one from http://java.sun.com.

If you have problems downloading or starting Eclipse, see the Eclipse FAQ.

Starting Eclipse


For the purposes of the tutorial, I'm going to set up a project called javatools-demo.

First start up Eclipse and supply a path to a new folder which will serve as your workspace. The workspace is a folder which Eclipse uses to store your source code.



Avoid checking the "Use this as the default..." box, which will always start up Eclipse with the same workspace. You'll probably find it useful to be able to switch between different workspaces on startup.

When Eclipse starts, you'll see the Welcome page:



Getting help


Note that you can access Eclipse help at any time via Help->Help Contents. This is the same as the help on the eclipse.org website.

Creating a project


Close the Welcome page. Right-click in the Navigator panel, and select New->Project:





Select "Java Project" and then "Next". Enter the name of your project:



Click "Finish". If you get prompted about switching to the Java perspective, select "Yes".

Perspectives

Eclipse provides a number of perspectives for different types of development task. You can see all of the available perspectives by selecting Window->Open Perspective->Other...



The "Java" perspective (which we're currently in) provides editors, views, and menu items which are useful for developing Java applications. The "Resource" perspective (which we started off from) provides a more basic set of tools, for example a Windows Explorer style file navigator.

You can quickly switch between perspectives using the buttons to the top right of the Eclipse window:




Note that projects are simply directories stored under the directory that you selected as your workspace. Look on the file system and see for yourself.

Use an alternative JRE


In the Package Explorer panel of the Java perspective, right-click on your newly created project and select "Properties". The Properties dialog opens on Java Build Path, which controls the project's classpath.



For now, the only entry is the JRE System Library shown in the "Libraries" tab. This defaults to the same JRE that was used to run Eclipse. In my case, a Java 5.0 installation was used. Depending on what versions of Java you have installed, you may see a different JRE here.

You might want to use a different JRE, for example the default may be Java 5.0 but you want your project to be compatible with Java 1.4 or 1.3 (your application will be useful to more people if it's backwards compatible with older JREs).


If you're happy with the default JRE, skip to the next section.


Ensure that you have the appropriate JDK or JRE version installed on your machine. If not, download and install from http://java.sun.com.

First click on "Add Library":




Click "Next" and then "Installed JREs..."



Click "Add".

In the next dialog, browse to the JRE or JDK that you want to use, and enter a name:



Click "OK" and then choose the new JRE:



Click "OK" and then "Finish". Your project will now be compiled against the new JRE.



Create source folders


Switch to the "Source" tab in the Properties dialog.



Eclipse projects can contain one or more source folders which contain Java source files. By default, the project directory itself is the only source folder.

Using multiple source folders is a good way to separate different types of code. This can make your project easier to work with and simplifies the Ant build scripts which we'll write later. We're going to set up separate source folders for application code and unit test code.

Click on "Add Folder" and type "src":



Click "Yes" when prompted.



Click on "Add Folder..." again and then "Create New Folder...". This time, call the folder "test". Click "OK" twice.

You'll see that we now have two source folders:



Clicking on "Order and Export" shows you the complete classpath used for compiling any Java source files in the project (we haven't created any source code yet!).

The classpath currently contains the two source folders plus the JRE:

.

Output folder

When you use custom source folders, the compiler stores the generated class files in a separate folder called the "output folder". As you can see from the dialog above, the output folder is set to a "bin" subdirectory under the project. Leave this setting alone unless you have a good reason.

Note that you won't see the bin subdirectory or class files in the Package Navigator by default. Switch to the Resource perspective to see an unfiltered view of all project files and directories.

Import third party JARs


If your application has a dependency on a third party library, you can import it into your project as a JAR file and add it to your project's classpath.

Say that the demo application needs to process dates, and we want to use the excellent Joda Time API.

First download a binary distribution of the library and extract it somewhere on your file system. Then create a new folder in your project as shown below:





When prompted, call the folder "lib". Right click on your new folder and select "Import..."




In the resulting dialog, select "File System" and then "Next". Browse to the location that you extracted the library to and select the JAR file.

Note that when you click "Browse" you must navigate to the directory containing the JAR file, otherwise you'll end up importing some unwanted folders as well as your JAR file.



Click "Finish". You should end up with something like:



Now to add the JAR to the project classpath. Right-click on the project and select "Properties". Go to the "Libraries" tab in "Java Build Path":



Click on "Add JARs..." and navigate to the freshly imported JAR. Click "OK"



Import source code


If you don't have any existing source code to import into Eclipse, skip to the next section.


Import code by right clicking on your project selecting "Import".



If your code is stored in a JAR or ZIP file, choose "Zip file". Otherwise, choose "File System". The rest of the process is pretty self explanatory.

Create a class


If you want to create some new Java code, right-click on the "src" source folder and select "New->Class"



First enter the package that your class belongs to.


Although reversing the domain name is common practise for package names, please DON'T use net.java as a project prefix. See this wiki entry for an explanation..



I've gone for org.jtdemo.

The rest of the dialog is pretty self explanatory. Feel free to experiment...



You should now see your newly created class in an editor window.




Views and editors

Eclipse makes a distinction between views and editors. An editor is a window which directly displays editable content, such as the Java editor above. When you make a change in an editor, the change doesn't take effect until you save the editor. You can tile and layer editors in various ways by dragging their title bars. To see a list of all open editors, press Ctrl-E.

A view is a window which displays a more abstract representation of content, for example the Package Explorer, Problems, and Outline views above. Changes made in a view take effect immediately. You can dock, layer, and tile views is various positions by dragging their title bars. To open a new view, select Window->Show View->Other...

To toggle maximisation of the current view or editor, double-click its title bar or press Ctrl-M.


Now you can start writing code.

Eclipse has so many useful Java development features, I can't do justice to them here. I'll refer you back to Java Development Tooling Tips and Tricks and Base Eclipse Platform Tips and Tricks for a small taste of what's possible. Go ahead and experiment!

Sharing preferences


Almost all of Eclipse's features are in some way configurable via preferences. You may want to share your preferences with other people, for example to enforce a consistent coding style. You may also want to have several workspaces, and use consistent preferences across all of them.

You can export your preferences using the Export... button on the main Preferences dialog (Window->Preferences). This will export your preferences in XML format. Preferences exported in this way can be imported using the Import... button.

Multiple projects, and the Order and Export tab


If required, you can create multiple Java projects and introduce build dependencies between them. Create a new Java project called "other", then look at its build path (right-click, Properties, Java Build Path). You'll see an entry for your original project as show below. Check this to introduce a build dependency.



Now look at the build path of your original project. The "Order and Export" tab contains a list of all entries on the project's classpath. If any of them are checked, they are exported, which means they are automatically added to the classpath of any project which is dependent on this project. For example, if we were to check the joda-time-098.jar entry, it would be automatically added to the classpath of the "other" project.



Note that you can select any entry and use the "Up" and "Down" buttons to change its order in the classpath.

Use a single project for java.net applications

If you're creating an application which you're going to host at java.net, use a single project. This will make it easier to work with CVS.

If you want to keep different parts of your application code separate, use source folders. If want to use a third party Eclipse project ( for example another Eclipse-based project hosted on java.net), use a JAR file containing the project's classes rather than a project dependency.

Installing plugins


Eclipse has a GUI for finding and installing new plugins which can be accessed via Help->Software Updates->Find and install. However, I find it more convenient to install plugins manually as described below.

First, download the plugin that you want to install. As mentioned earlier, there are good online indexes available here and here.

If necessary, extract the plugin from its zipped/tarred form. Look for a directory containing a file "plugin.xml". Copy this directory to the "plugins" directory under your Eclipse installation, for example C:\eclipse\eclipse-SDK-3.0.1-win32\eclipse\plugins. Restart Eclipse and the plugin should be ready to use (sometimes the plugin will provide a new view, editor, or perspective that you'll have to activate manually).

If you're not sure if a plugin is loaded, select Help->About Eclipse Platform, and click "Plug-in Details".



This will show a list of all loaded plugins:



Summary


Hopefully you've now got a feel for what Eclipse is all about, and you know how to set up a project for open source development. In Part 2, we'll look at using Eclipse's CVS integration in conjunction with java.net's CVS repository.

About the author


Martin Pllu is a member of the Messaging & Java Infrastructure Team at the Standard Life Assurance Company in Edinburgh, Scotland. He is the author of a number of open source applications including leafcutter and tracetest, both hosted here at java.net.

게임 서버의 구조 #

참고> 이 글은 [http]한빛 네트워크 에서 퍼왔음을 알려드립니다.

남재욱
(주)지스퀘어 3D 캐주얼 게임 서버 프로그래머

온라인 게임에서 실질적인 게임을 진행시켜주는 것이 게임 서버이다. 우리는 게임 서버의 구조는 게임의 진행과 시스템의 효율성에 많은 영향을 미치는 부분이다. 물리적으로 한정적인 시스템 자원을 효율적으로 사용하기 위해서 다양한 분산 처리는 필수적인 요소이다. 분산 처리 구조를 익힘으로써 우리는 좀 더 세련되고 뛰어난 성능을 발휘할 수 있는 게임 서버를 만들 수 있다. 온라인 게임 서버 프로그래밍의 핵심인 게임 서버의 구조에 대해 알아 보도록 하자.


일반적인 게임 서버 구조 #


게임 서버는 실질적인 게임을 진행하는 역할을 담당한다. 게임 서버는 유저간의 동기화, NPC 의 인공지능, 아이템 시스템 등 게임 시스템의 총 집합이라 할 수 있다. 게임 진행에 필요한 모든 게임의 요소들을 총괄하여 진행시켜주는 작업을 하기 때문에 가장 많은 일을 담당한다. 게임을 진행하는 요소는 방대하기 때문에 하나의 서버에서 처리하는데는 많은 부담이 된다.

게임 서버를 제작하고 테스트를 하는 과정에서 수십명의 유저를 처리하는 것은 그리 문제가 되지 않는다. 더욱이 하드웨어의 눈부신 발전에 힘입어 게임에서도 고성능 서버를 사용하기 시작하면서 서버쪽의 부담이 덜어져 가는 것도 사실이다. 하지만 접속 유저가 늘어나면서 서버쪽에서 느끼는 부하는 그 수치가 급격하게 증가한다. 그렇기 때문에 서버를 제작하면서 게임 서버의 부하를 분산시키려는 노력이 필요하다.

NPC 서버의 분리 #


구성에 따라 게임 서버에 많은 부하를 줄 수 있는 것이 NPC 의 인공지능 부분이다. 보통 게임에서 NPC 의 인공지능은 상당히 단순하게 느껴진다. 하지만 수많은 NPC 의 인공지능을 구성하는 코드는 상당히 복잡하며 처리량도 만만치가 않다. 따라서 <그림 1> 과 같이 NPC 의 인공지능 부분을 따로 분리하여 게임 서버에서 부하를 줄이게 된다.

Article/NPC_Server.gif
<그림 1> NPC 서버의 분리

NPC 서버와 게임 서버가 분리되면 게임 서버에서는 NPC 오브젝트만 생성하게 된다. NPC 서버에서는 게임 서버에서 생성된 NPC 오브젝트의 인공지능을 처리한다. NPC 서버에서는 인공지능 부분만 처리하여 게임 서버에 있는 NPC 오브젝트에게 소켓 통신 등을 이용하여 명령한다. 게임 서버 입장에서는 소켓 통신을 하는 비용은 지불하게 되지만 많은 서버 리소스를 절약하는 효과를 볼 수 있다. 또한 NPC 서버에서는 인공지능 부분을 전담하기 때문에 더욱 복잡하고 똑똑한 인공지능을 만들어 낼 수도 있다. 사실 게임 서버에 인공지능 부분까지 처리하게 되고, 처리할 NPC 의 숫자도 많다면 복잡하고 세련된 인공지능은 서버에 많은 부담을 주게 될 것이다.

온라인 게임을 하다보면 서버가 다운되어 다시 접속을 하였는데 NPC 들이 필드에서 하나도 없는 경우를 몇몇 게임에서 발견할 수 있다. 이러한 상황은 NPC 서버와 게임 서버간의 동기화가 안된 상황에서 클라이언트가 게임 서버에 접속하였을 때 발생하는 현상이다. 이런 경우 잠시만 기다리면 갑자기 NPC 들이 생겨나는 것을 볼 수 있을 것이다.

NPC란? Non-Player Characters 의 약자이다. 게임에서 유저 캐릭터가 아닌 서버에 의해조종되는 캐릭터를 총칭하는 말이다. 온라인 게임에서는 보통 상점주인, 경비병, 몬스터등이 이에 속한다.

동기화 서버의 분리 #


게임 서버에서 제일 기초적인 동작은 캐릭터간의 동기화 작업이다. 동기화 작업은 게임 서버가 시작되고 유저들이 접속하면서 부터 처리하게 된다. 동기화 작업은 제한된 공간에서 유저들의 행동을 상호간에 인지시키게 하기 위한 작업이다. 유저들의 행동을 상호간에 인식시키기 위해서는 모든 캐릭터의 행동을 근처의 모든 캐릭터들에게 알려 주어야 하기 때문에 많은 부하를 발생시킨다. 따라서 동기화 작업만을 전담하는 서버를 분리하여 준다면 게임서버의 퍼포먼스를 향상시킬 수 있다. PC / NPC 간의 동기화 작업은 각각의 오브젝트 단위로 이루어지기 때문에 동기화 서버를 따로 두어 캐릭터들의 동기화 부분만 전담시켜 부하를 분산시키는 구조를 택할 수 있다.

Article/SYNC_Server.gif
<그림 2> 동기화 서버의 분리

동기화 서버는 NPC 와 PC 의 동기화 작업만 전담한다. 게임 서버에서 클라이언트의 움직임 등의 요청을 받는다면 동기화 서버로 명령을 전달하게 되고 동기화 서버에서는 명령에 따른 결과를 게임 서버에 전달하게 되어 게임 서버에서는 결과를 각색하여 클라이언트로 전달하게 된다. 동기화 서버가 분리되는 방식은 게임 서버가 해야할 일을 물리적으로 다른 서버와 분담하여 처리하는 방식이기 때문에 많은 유저가 접속하였더라도 서버의 성능을 일정하게 유지시켜줄 수 있는 구조이다.

채팅 서버의 분리 #


MMORPG 는 다른 측면에서 보았을 때 커뮤니티의 일종으로서 유저 상호간 액션에 의해 게임이 진행된다. 커뮤니티에서 빠질수 없는 것이 의사 소통이며, 게임에서는 채팅을 통해 상호간의 의사전달을 하게 된다. 따라서 게임 서버에서는 유저들의 많은 양의 채팅 메시지를 처리하게 된다. 또한 채팅 메시지는 유저간의 동기화 문제와도 연관되어 많은 부하를 발생시킬 수도 있기 때문에 채팅 서버만을 따로 두어 게임 서버의 부하를 분산시키기도 한다.

Article/Chatting_Server.gif
<그림 3> 채팅 서버의 분리

채팅 서버를 분리하게 되면 대부분 클라이언트와 채팅 서버간의 1:1 통신을 하게 된다. 즉, 클라이언트는 게임 서버와 채팅 서버에 각각의 연결을 만들어 통신을 하게 된다는 것이다. 따라서 게임 서버에서 클라이언트의 PC 가 동기화 영역을 움직인다면 채팅 서버에서도 마찬가지로 해당 채팅 동기화 영역으로 움직여 채팅 메세지 동기화를 하게 된다. 게임 서버에서 할 일이 분산되기 때문에 좀 더 안정적인 게임 서버를 만들수 있게 되지만 채팅 서버에서도 캐릭터의 이동에 따른 기본적인 동기화 작업이 필요하기 때문에 채팅 메세지를 게임 서버에서 처리 하는것보다 좀더 많은 작업량이 필요하게 된다.

참고> 서버 기능 분리시 주의사항서버를 분리하는데에는 많은 사항을 고려해야 한다. 서버의 기능을 나누어 부하를 분산시키는것은 좋지만 서버를 나누어서 새롭게 생겨날 수 있는 취약점이나 또 다른 부하를 고려해야 하기때문이다. 예를 들어 NPC 서버가 분리된다면 게임 서버와 NPC 서버간의 동기화, NPC 서버와게임 서버간의 통신으로 인한 네트워크 오버헤드를 고려해야 한다.동기화 서버가 분리되면 역시 동기화 서버와 게임 서버간의 통신으로 인한 네트워크 오버헤드와게임서버와 동기화 서버의 권한을 명확히 해야 한다. 채팅 서버가 분리 된다면 채팅 서버와 게임서버간의 동기화 문제를 고려해야 한다.


분산 게임 서버의 구조 #


서버 프로그래밍을 하다 보면 분산 서버 또는 클러스터링에 많은 관심을 갖게 된다. 그 이유는 온라인 게임 서버 프로그래머라면 누구라도 기술적 한계를 뛰어넘어 수만에서 수십만명이 하나의 월드에서 자유롭게 게임을 즐기는 환경을 만들어 주는 것을 바라기 때문이다.

현재 국내 온라인 게임을 살펴보면 월드에는 일정한, 내부에서 정하는 유저 제한치가 존재하게 되며 이러한 제한치가 넘어가게 되면 더이상의 유저를 수용하기 보다는 다른 서버군을 오픈하여 유저의 이동을 권하게 하는게 대부분이다.

일반적으로 서버군에 따라 각각 물리적으로 분리된 데이터베이스를 사용하게 된다. 때문에 서버군을 이동하게 되면 데이터베이스가 바뀌기 때문에 개발사에 따라 기존의 캐릭터를 그대로 옮겨 갈 수도 있거나 아니면 새로 만들어야 하는 문제가 생기곤 한다. 개발사에서는 새로 오픈하게 되는 서버군에서 캐릭터들의 형평성을 위해 특별한 이유가 없는한 이전에 사용하던 캐릭터를 다른 서버군으로 옮기지 못하게 한다. 대부분의 온라인 게임이 이러한 구조를 택하고 있고, 하나의 캐릭터가 서로 다른 서버군을 옮겨 다니며 게임을 할 수 있게 만든다는 것은 분명 쉬운 일이 아니다.



질문 : 통합된 월드의 게임 서버를 만드는데 가장 문제가 되는 것은 무엇인가?

: 첫번째는 통합된 월드내 수많은 유저의 정보를 실시간으로 저장할 수 있는 데이터베이스가 가장 문제가 된다. 서버군의 유저수를 통제하는 것도 데이터베이스의 문제가 주요인이다. 그 이유는 데이터베이스가 실시간으로 동시에 처리할 수 있는 능력은 시스템에 따라 한계치가 있기 때문이다. 두번째는 데이터베이스의 부하를 분산하기 위해 replication 기능을 생각해 볼 수도 있다. 하지만 replication 기능도 상황에 따라 한쪽 데이터베이스에서 오류가 발생할 경우 처리 문제는 상당히 까다롭다. 실시간으로 오류 발생 즉시 다른 한쪽으로 데이터베이스 커넥션을 바꾸어야 하는데 이또한 임시적인 방책이지 해결책은 될 수가 없다. 부하가 심해 오류가 발생되었다고 오류가 없는 데이터베이스로 커넥션을 옮긴다면 한쪽으로 부하가 집중되어 역시 오류가 발생할 문제가 다분해 지기 때문이다. 세번째는 실시간으로 부하를 분산해야 하는 문제가 있다. 갑자기 하나의 지역에 많은 유저가 몰리게 된다면 시스템의 한계에 의해 서버의 처리 속도가 현저하게 느려지거나 심할경우 OS 가 다운이 될 수 있기 때문이다. 부하를 실시간으로 분산시킬 수 있는 것은 상당히 까다로운 문제이다.



replication란? 데이터베이스의 복제 기능이다. 똑같은 정보를 가지고 있는데이터베이스들끼리 연결되어 한쪽 데이터베이스에 정보가 입력된다면 입력된 데이터를다른 데이터베이스에도 똑같이 입력되게 하는 데이터베이스 기능이다.

필자의 경우 같은 지역을 여러대의 맵서버가 관리하는 분산 구조를 간단하게 테스트 해본 적이 있다. 구조는 동기화 서버( 1대 ) + 게임 서버( 여러대 ) 의 구조이다.

Article/Dispersion_struct.gif
<그림 4> 게임 서버의 분산 구조

동기화 전문 서버를 한대 두고 그에 여러대의 동일한 맵서버가 연결되어 부하를 분산시켜주는 구조이다. 동기화 서버와 맵 서버간에는 UDP 를 이용하여 데이터를 송수신 한다. 예를 들어 동기화 서버에 2 대의 게임서버 1, 2 를 붙이게 된다면 유저들은 게임 서버 앞단에 있는 로드밸런싱 서버에 의해 적은수의 유저가 있는 게임 서버를 알게하여 게임 서버 1, 2 에 분산되어 접속하고 게임을 하게 되지만 같은 섹터에 있는 캐릭터는 동기화 서버에 의해 동기화가 되는 구조이다.

물리적으로는 분리되어 있는 게임서버 1, 2 이지만 동기화 서버에 의해 논리적으로는 같은 서버에 존재하게 되는 것이다. 동기화 서버는 오직 캐릭터들의 동기화 작업만 수행하기 때문에 디스크 I/O 가 없어 부하를 적게 차지하여 여러대의 동일한 공간의 게임 서버를 동기화 시킬수 있는 구조이기 때문에 많은 유저들을 수용할 수 있다.


서버간의 통신 #


이전에 필자가 구현 했던 MMORPG 의 서버군의 구성은 다음과 같다. <그림 5> 를 보면서 서버간의 통신에 대해 이야기 해보자.

Article/Server_Group.gif
<그림 5> 서버군

<그림 5> 의 서버군은 패치 + 로그인 + 로비 + 맵 + 관리 서버의 구조로 되어 있다. 서버간의 통신은 UDP 프로토콜을 이용하며 관리 서버를 중간에 두어 월드의 모든 접속자 리스트를 가지고 접속자 관리, 전체 메세지 전송, 타 서버에 있는 케릭터에 귀속말 전달 등의 일을 담당한다. 유저가 인증에 성공을 하게되면 최초 인증 서버에서 관리 서버로 유저의 기본 데이터를 송신하여 유저의 연결 리스트에 추가를 하게 된다. 유저가 월드를 선택하고 캐릭터를 선택하여 게임 서버에 접속을 하게 되면 게임 서버에서 관리 서버로 관련 정보를 송신한다. 관리 서버에서는 데이터를 수신하여 연결리스트의 해당 유저 노드를 잘라내어 월드 트리의 해당 서버 브렌치에 노드를 추가하게 된다.

각 게임 서버들은 2 개의 네트워크 인터페이스 ( 랜카드 ) 를 사용하여 각각 외부/내부 네트워크 전용으로 사용하였다. 특히 데이터베이스의 경우 외부 네트워크와 차단하여 혹시 있을 수 있는 해킹에 대비하였다. 내부 네트워크와 외부 네트워크로 구분하기 위해 각각의 네트워크 인터페이스 카드 ( 랜카드 ) 하나 ( 랜카드1 ) 에는 공인 IP 를 또 다른 하나 ( 랜카드2 ) 에는 사설 IP 를 부여 하였다. 사설 IP 는 B 클래스 172.16.0.0 - 172.31.255.255 영역을 사용하였다. B 클래스를 쓴 이유는 네트워크당 65000 개의 호스트를 수용하기 때문에 서버가 많이 늘어나도 아이피가 부족할 일이 없기 때문이다. <표 1> 는 내부 네트워크에서 사용하는 클래스의 IP 대역과 네트워크당 수용 가능한 호스트의 수이다.

클래스 IP 대역 네트워크당 수용 호스트 수
A Class10.0.0.0 ~ 10.255.255.255 16777214 개
B Class172.16.0.0 ~ 172.31.255.255 65534 개
C Class192.168.0.0 ~ 192.168.255.255254 개
<표 1> 클래스 대역폭 및 수용 호스트수

각 서버들의 정보는 데이터베이스에 저장되어 있기 때문에 처음 서버가 구동될 때에는 전체 서버군에 있는 서버들의 정보를 적재 ( load ) 시킨다. 적재된 서버의 정보는 서버 인덱스와 내부 아이피 정보인데, 각각의 서버들은 다른 서버와의 통신을 위해 서버 정보들을 사용한다. 통신이 필요한 서버에 메세지를 송신하고 수신받은 서버에서는 메세지에 따른 처리를 한 후에 다시 응답 메세지를 보내주면 하나의 통신이 완료되는 것이다.

서버간에 전송되는 메세지는 주로 캐릭터가 게임 서버를 이동할 때 사용되는 패킷과 귀속말 패킷이 주로 사용된다. 유저가 게임 서버를 이동할 때에는 캐릭터가 위치하고 있는 포탈 인덱스에서 이동하려는 서버의 인덱스를 알아내어 클라이언트에게는 이동하려는 서버의 아이피, 접속 포트 번호, 인증 키 등을 전송하고, 캐릭터가 현재 위치하고 있는 서버에서는 이동하려는 서버로 인증키 등을 전송한다. 클라이언트에서는 현재 서버로부터 받은 아이피와 포트로 새로운 서버로 접속을 하고 인증키를 통해 인증을 받게 된다. 서버간 통신은 랜카드2 를 통해서만 송/수신 ( 서버간의 패킷은 사설 아이피로 수신된 패킷만 인정하고 공인 아이피로 온 패킷은 무시 ) 하기 때문에 혹시 있을 수 있는 사용자의 해킹을 방지한다. <표 2> 은 IP address 별 사용 용도와 특징을 정리한 내용이다.

공인 IP 사설 IP
차이점클라이언트와의 통신서버간의 통신
서버간의 통신 사용불가클라이언트간 통신 사용불가
공통점서버간의 통신에서 네트워크 대역폭 확보 및 물리적인 보안
<표 2> IP address 사용

외부로 부터의 보안을 위해 서버는 TCPWRAPPER 를 사용하여 관리자 아이피 외의 접근을 막았다. 게임 산업이 발전함에 따라 게임 서버의 보안 문제가 이슈가 된지는 오래이며 유명 게임 서버들의 경우 해커의 공격 목표가 되기도 한다. 해킹에 의해 소스나 데이터베이스가 유출되기도 하기 때문에 개발사들은 보안에 만전을 기해야 한다. 시스템의 해킹은 자칫 큰 문제가 되어 게임의 흥망에도 큰 영향을 미칠수 있기 때문에 중요한 문제이다.

TCPWRAPPER란? Wietse Vanema 에 의해 제작된 TCPwapper 는 호스트 레벨에서 특정프로토콜과 포트, 네트워크 IP 에 따른 접속허가를 내줄 것인지 거부할 것인지 결정하는packet dropper 이라고 볼 수 있다.

스마트그리드 개념 : form 스마트그리드협회

http://www.k-smartgrid.org/


전력시스템과 IT 기술의 융합,

스마트 그리드 요약보고서....

전력시스템을 익히자!!!!!!

1264251649_스마트 그리드 - 요약보고서.pdf

Apple 타블렛은 “촉각 피드백 기능”이 추가?
KISTI 『글로벌동향브리핑(GTB)』 2010-01-14
美 Apple의 타블렛에 관한 소문이 12월 23일(미국 시간), 다양한 미디어에서 일제히 나오기 시작했다. 「New York Times」의 라이터인 Nick Bilton씨는 이번 소문에 대해 Apple 스탭의 발언을 소개해 주고 있다.

“신제품에 대해서는 아무것도 말할 수 없습니다만, Steve Jobs씨가 새로운 타블렛에 대해 상당히 마음에 드는 것 만 말할 수 있습니다”라고 Apple의 시니어 사원이 말했다고 한다. Bilton씨는 최근 同사를 떠난 사원이 “새로운 타블렛을 사용할 때 매우 놀랄 것이다”라고 말했다고 한다. 특히 두 번째의 발언에 관심이 집중된다. 사용할 때 인터페이스에서 놀란다고 하면 그건 무슨 말일까? Apple은 2008년 8월에 손 터치와 제스추어 등 2가지를 동시에 감지하는 장치에 대한 특허를 신청한 바 있다. 하지만, 이것은 “놀란다”라고 까지는 말할 수 없다.

흥미로운 것은 「AppleInsider는 美 특허 상표청이 이번 주 새로운 특허 출원이 공개되었다고 한다(http://www.appleinsider.com/articles/09/12/24/possible_apple_tablet_multi_touch_tactile_keyboard_detailed.html).
Apple이 신청한 이 특허 출원(http://appft1.uspto.gov/netacgi/nph-Parser?Sect1=PTO2&Sect2=HITOFF&u=%2Fnetahtml%2FPTO%2Fsearch-adv.html&r=1&f=G&l=50&d=PG01&p=1&S1=20070247429&OS=20070247429&RS=20070247429 )은 “Keystroke tactility arrangement on a smooth touch surface(매끄러운 터치 스크린상에 키스트로크(keystroke) 촉감의 설정)”이라는 제목이다. 기기 표면상의 키보드(터치 스크린상의 가상 키보드)의 촉각 피드백 기구에 대해 쓰여져 있다. 유저가 키의 감촉을 물리적으로 느낄 수 있도록 만들어 진다고 한다.

모두 또는 대부분의 키에 닷(Dots), 바, 또는 그 외의 촉각 피드백 기능을 만드는 것이다. 이의 형태에 대해서 스크린 표면이 입력 모드로 사용되고 있는 경우에는 확대되고, 스크린 표면이 포인팅 모드 등 다른 일부의 모드로 사용되고 있는 경우에는 분절형 프레임(articulating frame)이 설치될 가능성이 있다. 분절형 프레임은 키 범위의 경계가 정해져 키의 윤곽을 나타내거나, 키 범위내에 촉각 피드백 기능이 추가될 가능성이 있다. 게다가 물리적인 키의 표면을 구현하는 형태로 움푹한 곳이 스크린 표면에 나타나는 분절형 프레임이 구성될 가능성도 있다. 다른 형태를 생각해보면, 고정되어 분절적이지 않은 프레임이 스크린 표면 아래에 설치될 가능성이 있다. 이것으로 유저는 누른 곳이 키의 중심에서 떨어져 있으면 큰 저항을 느끼고 키의 중심에서는 작은 저항을 느끼게 된다.

이로써, 키보드를 응시하면서 입력할 필요가 없어진다면 환영해야 할 추가 기능이라고 말할 수 있을 것이다. 게다가, 화면이 큰 터치 스크린의 디바이스에서는 이것이 매우 중요한 기능인 것은 충분히 상상할 수 있다.

Apple은 2009년 7월에도 촉각 피드백 등의 특허를 신청하고 있다. 여기에서는 iPhone에 적용될 가능성이 있는 새로운 기능의 힌트가 있다. 그 중에서도 흥미로운 것은 촉감을 만들어 내는 촉각 피드백에 관한 특허다. 누르고 있는 터치 스크린상의 가상 키를 감지하는 것이 가능하다는 것이다. 촉각 피드백 아이디어는 다음과 같다. iPhone의 진동에 의해 물리 키보드에서 느끼는 진동을 시뮬레이트하는 것으로 타이핑중에 각 키의 진동을 느끼는 것이 가능하다는 것이다. 이것이 실현되면 입력중에 화면을 볼 필요가 없어진다.
출처 : http://www.wired.com/gadgetlab/2009/12/apple-tablet-surprise/
Introducing Calculon – a Java DSL for Android Activity testing PDF Print E-mail

I have been working on a new test library for Google Android lately, a project which I’m very excited about, and which I feel has loads of potential: Calculon, an Android testing library which lets you write functional tests for your Activities using a very concise and natural syntax.

I am a big fan of test-driven development, and I think there’s no arguing about the massive benefits you get from backing your software up with an automated test suite. The support for writing tests in Android, however, is lacking at best. Even though there has been a test runner since the 1.0 days, writing unit or functional tests in Android is far from being a pleasant experience. For me, the two most important things about tests are that they must be easy to write, and more importantly, easy to read.

That being said, here is a classic example of why Android testing sucks. Our test story is:

Assert that a click on ‘button’ launches a new BarActivity.

Without Calculon, what you do is this:

01public void whatInHeavensNameDoesThisEvenTest() {
02 final Button b = (Button) getActivity().findViewById(R.id.button);
03 ActivityMonitor monitor = getInstrumentation().addMonitor(
04 BarActivity.class.getCanonicalName(), null, false);
05 getInstrumentation().runOnMainSync(new Runnable() {
06 public void run() {
07 b.performClick();
08 }
09 });
10 getInstrumentation().waitForIdleSync();
11 assertTrue(getInstrumentation().checkMonitorHit(monitor, 1));
12}

So, I first have to retrieve a reference to the button that’s supposed to launch a new BarActivity. Then I have to create what Android calls an ActivityMonitor, that’s simply an object which just sits there and waits until an Activity is being launched that matches the description it was configured with. Then I have to perform the actual button click, but sorry, not allowed on the instrumentation thread, so I have to runOnMainSync(). We’re not yet there though: we have to sit and wait, because launching a new activity could take a while, so we also have to waitForIdleSync(). The assertion that follows also couldn’t be less expressive.

When I first wrote this test, my single thought was: Where the heck is my story? It’s buried under a heap of ugly boilerplate code.

I don’t care that the test runner cannot perform a view event on the instrumentation thread. I don’t care that it needs to sit and wait for the Activity to launch. I don’t care about ActivityMonitor and its crummy API. I just want to look at the test, and understand what it’s doing.

Let’s reiterate our test story:

Assert that a click on ‘button’ launches a new BarActivity.

With Calculon, this test is written as:

assertThat(R.id.button).click().starts(BarActivity.class);

Oh the beauty. Our test story was a single sentence, so is the test. That’s how it should be, really. There’s nothing worse than seeing someone else’s tests failing on the build server and having to dissect them line by line to figure out what it’s actually testing.

So let’s move on and look at some nifty Calculon tests. And remember: “Calculon never does two takes!”

Testing with Calculon

Calculon is in a very early stage of development, and currently it only supports writing functional Activity tests, using Android’s ActivityInstrumentationTestCase2. Here is what a Calculon test looks like:

1public class FooTest extends FunctionalTest<FooActivity> {
2 public FooTest() {
3 super("com.example", FooActivity.class);
4 }
5
6 public void testStuff() {
7 ...
8 }
9}

Nothing special here, really. You just inherit from a Calculon FunctionalTest.

Assertions

At the heart of a Calculon test are assertions. To create a new assertion, you use the assertThat() method:

01public void testStuff() {
02 // testing against activities
03 assertThat()...
04 assertThat(getActivity())...
05 assertThat(someOtherActivity)...
06
07 // testing against views
08 assertThat(R.id.some_button)...
09 assertThat(someButton)...
10
11 // of course all Junit assertions work as well
12 assertEquals(...)
13 assertNotNull(...)
14 ...
15}

For now, there are two basic kinds of assertions: ActivityAssertion and ViewAssertion. There is also a third kind, ActionAssertion, but it takes a somewhat special role and is discussed at the end.

Activity Assertions

An ActivityAssertion is an assertion on the state of an Activity and is used like this:

01public void testStuff() {
02 // testing for an orientation
03 assertThat().inPortraitMode();
04
05 // testing for views
06 assertThat().viewExists(R.id.some_button);
07
08 // testing for input actions
09 assertThat().keyDown(KeyEvent.KEYCODE_BACK)...
10
11 // testing for custom predicates
12 assertThat().satisfies(new Predicate<Activity>() {
13 public boolean check(Activity target) {
14 return target.isTaskRoot();
15 }
16 });
17}

View Assertions

A ViewAssertion is basically the same, just that it tests the state and behavior of a view:

01public void testStuff() {
02 // testing for view state
03 assertThat(R.id.button).isVisible();
04 assertThat(R.id.button).isGone();
05
06 // testing for input actions
07 assertThat(R.id.button).keyDown(KeyEvent.KEYCODE_BACK)...
08 assertThat(R.id.button).click()...
09 assertThat(R.id.button).longClick()...
10
11 // testing for custom predicates
12 assertThat(R.id.button).satisfies(new Predicate<View>() {
13 public boolean check(View target) {
14 return target.getVisibility() == View.VISIBLE;
15 }
16 });
17}

Action Assertions

This is a special kind of assertion. You always use it when you want to assert that some action (e.g. a click or a key press) does something. You can use it on both activity and view assertions, and it also allows you to delegate an assertion to another object:

01public void testStuff() {
02 // testing for actions that launch a new activity
03 assertThat(R.id.b1).click().starts(BarActivity.class);
04
05 // testing for actions that finish an activity
06 assertThat(R.id.b2).keyDown(KeyEvent.KEYCODE_Q).finishesActivity();
07
08 // testing for actions that change something
09 assertThat(R.id.b3).click().implies(R.id.b2).isGone();
10 assertThat(R.id.b4).click().implies(getActivity()).inLandscapeMode();
11 assertThat(R.id.b5).click().implies(new Predicate<Model>() {
12 public boolean check(Model target) {
13 return target.someAttribute() == 5;
14 }
15 });
16}

There’s more to come!

This is only a very early version. I intend to expand this library significantly over time. Of course it’s open source, so contributions are always welcome. You can fork the project on GitHub, add your changes, and send me a pull request.

Source: brainflush

Beginner iPhone SDK Hello World Tutorial [Example & Code]

Posted by Adeem Basraa On July - 3 - 2009
New in iPhone Development? You can now follow this blog on google readers or subscribe for email or Twitter!
If my tutorial help you then please donate, so that i continue writing free tutorials for every developer/programmer/freelancer

Introduction:

I am going to show you the simplest way to create hello world iPhone tutorial. I will write few more tutorials on the basic of iPhone Development. So this tutorial is an absolute beginner guide for iphone development. To get start with iPhone development you need to have iPhone SDK which you can get from here (http://developer.apple.com/iphone). To download it you need to have a apple developer account which is free for everyone. To test the code on device (iPhone) you need to buy a developer license which cost you 99$ or 299$ for enterprise.

Getting Started with iPhone Development:

To start with hello world iPhone tutorial, you should read the “getting started with iPhone” tutorial which covers the things you need to know before starting development for iPhone( You can also watch the video tutorial of “Getting Started with iPhone” ). I also write a tutorial for businessman and designer to know about the iPhone development cycle (”iPhone Development Guide” ). So if you are a beginner for iPhone, you should read my tutorial before starting iPhone development.

Idea of this tutorial:

There are already many tutorials on hello world in iPhone but I want to write a very basic tutorial on iPhone sdk which will cover xcode, iphone project files and interface builder. This is a basic hello world tutorial which will be extended to a big project later on. So before reading other tutorials on my blog I highly recommended you to read this beginner’s Guide to iPhone development. OR you can watch the video tutorial here if you have no time to follow easy steps :) .

Final output of hello world tutorial

customize UITableView using UITableViewCell
Hello world iPhone tutorial Output

Simple Steps to create hello world iPhone application

Step 1:If you have read the getting started tutorial, then you have a xcode installed on your mac machine. Open the Xcode and click on File > New Project. Select “View-Based Application” and click on “Choose..” button. Name this project “Hello World” and click “Save” button. Now you have a template for your hello world iphone project.

customize UITableView using UITableViewCell
Create a new Xcode Project for iPhone application

customize UITableView using UITableViewCell
Select the basic design for your first iPhone application

customize UITableView using UITableViewCell
Name your first iPhone applcation

customize UITableView using UITableViewCell
Xcode project template created

Step 2:Now click on Build and Go button to run this template application. It will start the iPhone simulator and you can see a gray screen on that. Click on Home button and it will show you a HelloWorld icon on the dash board of iPhone simulator. If you click on it again, it will open the application again. iPhone simulator is best tool to test your application before you deploy it on your device for testing or even before submitting to apple store.

customize UITableView using UITableViewCell
Build your First iPhone application

customize UITableView using UITableViewCell
Output of your first iPhone application
customize UITableView using UITableViewCell
Press this button to quit your first iPhone application

Step 3:Now open Xcode project and select HelloWorldViewController.h file and type the following code inside interface:

IBOutlet UITextField *txtUserName;
IBOutlet UILabel *lblUserTypedName;
Also write this method before end of this class
- (IBAction) submitYourName;


Step 4:So your HelloWorldViewController.h file will look like this:

#import <UIKit/UIKit.h>

@interface HelloWorldViewController : UIViewController {
IBOutlet UITextField *txtUserName;
IBOutlet UILabel *lblUserTypedName;
}

- (IBAction) submitYourName;
@end

Step 5:Now open HelloWorldViewController.m file and type this method before @end
- (IBAction) submitYourName;{
lblUserTypedName.text = txtUserName.text;
}

Step 6:Now lets start some design on interface builder. For that open your xcode project and in “Group & Files” looked at bottom, you will see “NIB Files”, expand it and you will see two design files for your classes. One is the MainWindow.xib which is the main window or entry point to your application. Other one is HelloWorldViewController.xib file which is mapped to your controller class “HelloWorldViewController.h. For now I just want to change in HelloWorldViewController.xib file. Double click on that file to open it inside interface builder.

customize UITableView using UITableViewCell
Structure of your iPhone application
customize UITableView using UITableViewCell
Interface builder Look

Step 7:Click on Tools and select Libaray (cmd + shift + L) and drag the text field to your view. As text field is already selected, click on Tools>Inspector (cmd + 1) and in Text field type “Your Name”.

customize UITableView using UITableViewCell
Add label to your First iPhone application
customize UITableView using UITableViewCell
Change text in your UILable

Step 8:Now drag the TextField from Library to your view (cmd+shift+L) and also drag another Label inside view. Make sure label is selected, Click on tools and select “Size Inspector” (cmd + 3) and change the width of this text field to 250. Also go to tools and select Inspector, change the layout to center.

customize UITableView using UITableViewCell
Add Text field to your first iPhone application
customize UITableView using UITableViewCell
Add another label to your First iPhone application
customize UITableView using UITableViewCell
Change Label Width
customize UITableView using UITableViewCell
Center UILabel from Interface Builder

Step 9:Last thing is to drag a button to the view (19) and then open Inspector again by selecting tools>Inspector. In Title type “Submit”.

customize UITableView using UITableViewCell
Add button to your First iPhone Application
customize UITableView using UITableViewCell
Change Text in your UIButton

Step 10:Now map the controller class variable function and methods with interface builder. Select File’s Owner in Interface builder and select connection inspector from Tools cmd + 2

customize UITableView using UITableViewCell
Map your controller with Interface Builder

Step 11:Now you can see that two new variables are added in connection inspector txtUserName and lblUserTypedName. Click on txtUserName radio button and drag it to text field in view (as you can see in the image)

customize UITableView using UITableViewCell
Map your text field with Interface builder

Step 12:Do the same with lblUserTypedName, select its radio and drag it to below label.

customize UITableView using UITableViewCell
Map your label field with Interface builder

Step 13:Now the last step is, click on submitYourName radio and drag it to the button and select touch down from the list.

customize UITableView using UITableViewCell
Map your button with Interface builder
customize UITableView using UITableViewCell
Set action type of Button

Step 14:Now close the interface and open xcode. Either press cmd + r or cmd + enter or simply press of “build and go” button to run this hello world application. It will open the simulator in iPhone.
Final output

customize UITableView using UITableViewCell
Your first iPhone application Running in simulator

iPhone hello world tutorial code

You can grab this code from here.

Now watch me doing it

Click on this link to view the video screen cast for hello world iPhone application tutorial

1 Introduction


구글은 안드로이드가 운영체제, 미들웨어 그리고 중요 프로그램을 포함하는 임베디드 디바이스를 위한 소프트웨어 스택이라고 설명합니다. 이 문서는 구글 안드로이드 아키텍처에 대해 설명하고 실제 하드웨어에 포팅하는 절차를 설명합니다. 설명은 안드로이드 에뮬레이터의 m3 SDK 버전에 기초해서 설명합니다.

여러분이 커널 패치, 패치의 거부 해결, 램디스크 이미지 만들기, 리눅스 커널 자체에 대한 충분한 지식을 가지고 있다면 이 아티클은 쉬울 것입니다.

2 Copyright and Acknowledgements


이 문서의 소유권은 Kwangwoo Lee <Kwangwoo.lee@gmailREMOVETHIS.com> 에게 있습니다. 이 문서에 대한 복사, 배포, 수정에 대한 권리는 GNU Free Documentation License 를 따릅니다.

번역은 양정석(dasomoli@gmailREMOVETHIS.com) 이 하였습니다만, 이상한 곳이 있다면 가차없이 수정해 주세요. :) 원문 : http://wiki.kldp.org/wiki.php/AndroidPortingOnRealTarget

3 안드로이드 아키텍처의 요약 분석


3.1 안드로이드 커널


안드로이드 커널의 가장 큰 차이점은 ARM EABI(Embedded Application Binary Interface)와 OpenBinder IPC(Inter Process Communication)를 사용한다는 것입니다. 여러분이 ARM EABI를 지원하는 커널을 컴파일하려면, ARM EABI를 지원하기 위한 툴체인(toolchains)을 새로 빌드하여야 합니다.

안드로이드 SDK는 Qemu를 사용하여 goldfish 아키텍처를 에뮬레이션합니다. alsa는 안드로이드의 오디오를 위해서 사용됩니다. goldfish 아키텍처 디렉토리의 audio.c 파일을 보고, 드라이버는 안드로이드 시스템 상의 오디오를 위한 /dev/eac를 사용합니다. 또한 RTC(Real Time Clock) 장치는 /dev/rtc0를 통해 사용됩니다.

다음 파트들은 주된 차이점을 설명합니다:

3.1.1 ARM EABI


EABI는 ARM사(ARM Ltd.)에 의한 새로운 "임베디드" ABI입니다. 그 차이는 데비안 위키에 정리되어 있습니다.

  • FPU를 쓰거나 쓰지 않는, 빠른 실수 연산(floating point) 성능
  • soft 와 hardfloat 코드의 혼용 가능
  • 이전에 사용되어지던 것과 같이 구조체 팩킹(packing)이 고통스럽지 않습니다.
  • 다른 툴들과의 더 나은 호환성(compatibility)
  • 더 효율적인 syscall 관례(convention). (http://www.arm.linux.org.uk/developer/patches/viewpatch.php?id=3105/4)

long ftruncate64(unsigned int fd, loff_t length); 의 예:기존 ABI:- put fd into r0 (fd를 r0로 넣음)- put length into r1-r2 (길이를 r1-r2로 넣음)- 커널 호출을 위해서 "swi #(0x900000 + 194)" 사용.새로운 ARM EABI:- put fd into r0 (fd를 r0로 넣음)- put length into r2-r3 (skipping over r1) (길이를 r2-r3로 넣음. r1은 무시)- put 194 into r7 (194를 r7로 넣음)- use "swi 0" to call the kernel (커널을 호출하기 위해서 "swi 0" 사용)

안드로이드는 EABI 커널 기능을 사용합니다. CONFIG_AEABI 와 CONFIG_OABI_COMPAT의 커널 옵션을 활성화 하세요. 여러분은 다음과 같은 실행 바이너리의 차이를 볼 수 있습니다:

  • 기존 ABI
$ arm-softfloat-linux-gnu-objdump -x t7-demo | grep privateprivate flags = 202: [APCS-32] [FPA float format] [software FP] [has entry point]$ file t7-demot7-demo: ELF 32-bit LSB executable, ARM, version 1 (ARM), for GNU/Linux 2.4.3, dynamically linked (uses shared libs), for GNU/Linux 2.4.3, stripped

  • ARM EABI
$ arm-softfloat-linux-gnueabi-objdump -x t7-demo  | grep privateprivate flags = 4000002: [Version4 EABI] [has entry point]$ file t7-demot7-demo: ELF 32-bit LSB executable, ARM, version 1 (SYSV), for GNU/Linux 2.6.14, dynamically linked (uses shared libs), for GNU/Linux 2.6.14, stripped


ARM 아키텍처를 위한 ABI가 무엇인가요? ARM EABI와 같은 건가요?

ARM 아키텍처의 ABI는 ARM와 (CodeSourcery를 포함하는) 그 파트너들에 의해 개발된 어떻게 컴파일러와 어셈블러와 링커와 다른 비슷한 툴들이 Object 파일과 실행 파일을 생성해야만 하는지를 설명하는 표준입니다. ARM 아키텍처의 ABI를 정확히 구현한 툴들은 상호 운용(interoperate)될 수 있습니다:예를 들면, 다른 툴체인에서 빌드된 Object 파일과 또 다른 툴체인에서 빌드된 Object파일이 양 쪽의 컴파일러가 ARM 아키텍처의 ABI를 사용한다면 함께 합쳐질 수 있습니다. "ARM EABI"는 ARM 아키텍처 ABI의 또다른 이름입니다.

3.1.2 OpenBinder


OpenBinder는 객체지향(object-oriented) 운영체제 환경을 제공합니다. 전통적인 커널에 호스팅(to be hosted)되어지도록 설계되었습니다. 이 프로젝트는 BeOS 다음번 생성의 일부로 Be. Inc에서 시작되었고, Cobalt 시스템의 코어 부분으로 PalmSource에 구현이 완료되었습니다. 그 것은 시스템이 Application에 지향보다는 컴포넌트 아키텍처에 지향적이고, 프로세스 간의 IPC, 스레드풀, 메모리 관리와 클린 업(clean up) 기능을 바인더 Obejct의 참조의 끝에서 제공합니다. 바닐라(vanilla) 커널은 OpenBinder IPC 메카니즘을 가지고 있지 않으므로, 여러분은 커널에 패치하여야 합니다. OpenBinder는 시스템의 스레드 관리를 /dev/binder를 통해서 제공합니다. 그 것이 안드로이드가 스레드 라이브러리를 제공하지 않는 이유입니다.

커널 패치 후에, 여러분은 /drivers/binder/에서 바인더를 위한 파일을 볼 수 있을 것입니다.

3.1.3 프레임 버퍼


기본적인 프레임 버퍼 드라이버는 이미 구현되어져 있어야만 합니다. 그 후에 여러분은 여러분의 아키텍처 드라이버와 goldfish 드라이버 간의 차이를 구현해야 할 것입니다.

goldfish 아키텍처의 프레임 버퍼 드라이버는 struct fp_ops의 fb_pan_display 함수를 지원합니다. 그 것은 실제 프레임 크기보다 두 배의 메모리가 할당되어야 함을 의미합니다.

  • 프레임 버퍼 정보 초기화
struct fb_info *fbinfo;...fbinfo->fix.ypanstep	= 1;fbinfo->var.yres_virtual    = gm->lcd.yres * 2;fbinfo->fix.smem_len        =	(gm->lcd.xres *                                gm->lcd.yres *                                gm->lcd.bpp / 8) * 2;

  • 프레임 버퍼 메모리 할당
struct mvfb_info *fbi;...fbi->map_size = PAGE_ALIGN(fbi->fb->fix.smem_len + PAGE_SIZE);fbi->map_cpu  = dma_alloc_writecombine(fbi->dev, fbi->map_size,                                       &fbi->map_dma, GFP_KERNEL);

  • fb_pan_display 함수 후킹 구현
static int mvfb_pan_display(struct fb_var_screeninfo *var, struct fb_info *fb){...}static struct fb_ops mvfb_ops = {        .owner		= THIS_MODULE,        .fb_check_var	= mvfb_check_var,        .fb_set_par	= mvfb_set_par,	        .fb_setcolreg	= mvfb_setcolreg,        .fb_blank	= mvfb_blank,        .fb_pan_display = mvfb_pan_display,        .fb_fillrect	= cfb_fillrect,        .fb_copyarea	= cfb_copyarea,        .fb_imageblit	= cfb_imageblit,        .fb_mmap	= mvfb_mmap,	};

그 디바이스 파일은 /dev/graphics/fb0에 위치해 있습니다.

3.1.4 입력 장치


안드로이드는 사용자 입력을 위한 이벤트 디바이스를 사용합니다. 거기에는 키패드와 쿼티2(qwerty2) 키보드와 마우스와 같은 세가지 디바이스가 있습니다. 쿼티2(qwerty2) 키보드와 마우스는 보통 디바이스입니다. 그래서 마우스 디바이스를 대체하는 키패드와 터치스크린을 설명하겠습니다.

안드로이드 쉘에서 /proc/bus/input/{devices,handlers}를 cat 하면, 안드로이드에서 사용되는 디바이스들을 볼 수 있습니다.
$ adb shell# cat /proc/bus/input/devicesI: Bus=0000 Vendor=0000 Product=0000 Version=0000N: Name="goldfish-events-keyboard"P: Phys=S: Sysfs=/class/inut/input0U: Uniq=H: Handlers=kbd mouse0 event0...## cat /proc/bus/input/handlersN: Number=0 Name=kbdN: Number=1 Name=mousedev Minor=32N: Number=2 Name=evdev Minor=64#

  • 키패드
Qemu는 goldfish-events-keyboard를 에뮬레이트합니다. 그 것은 이벤트 디바이스(/dev/input/event0)를 사용하는 키패드입니다. 그래서 여러분은 이벤트 디바이스로부터 실제 활성화된 안드로이드 프로그램으로 전달되어지는 키 이벤트의 종류와 값을 알 수 있습니다. 그렇게 하기 위해서 event0 디바이스를 cat으로 읽고 파일로 그 출력을 재지정(redirect)합니다. 만약 에뮬레이터 상의 키 버튼이 눌리고 떼어지면 그 출력 값이 저장될 것입니다.

그 출력 형식은 input_event 구조체 입니다. 그래서 각 event의 출력은 시간을 위한 8 바이트, 타입을 위한 2 바이트, 코드를 위한 2 바이트, 값을 위한 4바이트로 총 16 바이트입니다. 리눅스 커널 소스 코드의 Documentation/input 디렉토리의 입력 이벤트 디바이스(input event device)에 관한 input.txt를 읽고, input-programming.txt를 읽으세요.
struct input_event {        struct timeval time;        unsigned short type;        unsigned short code;        unsigned int value;};

Tiger7 개발 보드는 그 고유의 scancode 테이블을 가집니다. 다음은 개발보드의 키 레이아웃과 scancode 테이블과 안드로이드 키 코드를 보입니다:
/* *  Key Layout       Scancode Table * *   1  2  3        0x1  0x10  0x100 *   4  5  6        0x2  0x20  0x200 *   7  8  9        0x4  0x40  0x400 *   *  0  #        0x8  0x80  0x800 */static unsigned short android_keycode[] = {        /*         *  0x66 0x67 0x9e	Home  Up   Back         *  0x69 0xe8 0x6a	Left  Ok   Right         *  0xe7 0x6c 0x6b	Send  Down Hangup         *  0xe5		Menu       just_distinction_for_private         */        KEY_HOME,         KEY_UP,       KEY_BACK,        KEY_LEFT,         KEY_REPLY,    KEY_RIGHT,        KEY_SEND,         KEY_DOWN,     KEY_END,        KEY_KBDILLUMDOWN, KEY_RESERVED, KEY_PLAY};

에뮬레이터에는 전원(power) 버튼이 있습니다. 그러나 출력 값을 얻기 위해서 무시했습니다.

키패드의 인터럽트가 감지(caught)되면 위 테이블의 안드로이드의 키 코드로 scancode를 변환하고 사용자 공간(user space) 프로그램으로 이벤트를 보냅니다.
...keycode = translate_keycode(scancode);...input_event(keydev->input, EV_KEY, keycode, KEY_PRESSED);orinput_event(keydev->input, EV_KEY, keycode, KEY_RELEASED);...

고정밀도 타이머 - hrtimer는 키패드 debounce를 줄이기 위해서 사용되었습니다.

  • 터치 스크린

포인팅 디바이스를 위한 이벤트 인터페이스를 지원하는 터치스크린 드라이버를 갖고 있다면, 잘 동작할 것입니다. 그렇지 않다면, 다른 포인팅 디바이스를 사용하거나 구현해야 합니다. 다행스럽게도 개발보드는 이미 안드로이드 포팅을 시작하기 전에 만들어진 터치스크린 드라이버 - drivers/input/touchscreen/tsc2007.c -가 구현되어 있었습니다. 여러분 고유의 드라이버를 구현하기 위해서는 drivers/input/touchscreen/ 의 드라이버와 Documentation/input/의 텍스트 파일을 참고하세요.
여기 개발 보드 상의 /proc/bus/input/{devices,handlers}의 출력이 있습니다.
# cat /proc/bus/input/devicesI: Bus=0000 Vendor=0000 Product=0000 Version=0000N: Name="MVT7 KEYPAD"P: Phys=S: Sysfs=/class/input/input0U: Uniq=H: Handlers=kbd event0 evbugB: EV=f...I: Bus=0000 Vendor=0000 Product=0000 Version=0000N: Name="TSC2007 Touchscreen"P: Phys=0-0090/input0S: Sysfs=/class/input/input1U: Uniq=H: Handlers=event1 evbugB: EV=bB: KEY=400 0 0 0 0 0 0 0 0 0 0B: ABS=1000003# cat /proc/bus/input/handlersN: Number=0 Name=kbdN: Number=1 Name=evdev Minor=64N: Number=2 Name=evbug

결과에서 보는 것과 같이, 프로그램 계층(application layer)에서 키패드는 /dev/input/event0를 사용하고, 터치스크린 인터페이스는 /dev/input/event1를 사용합니다.

3.1.5 Low Memory Killer


리눅스 커널은 프로세스의 요청을 위한 할당을 위해서 남은 메모리가 없는 상황을 위한 OOM(Out of Memory) 킬러를 가지고 있습니다. 그 것은 모든 프로세스를 시험하고 어떤 제약으로 점수를 매깁니다. 최고 점수의 init을 제외한 프로세스는 죽여집니다.

안드로이드의 Low Memory Killer는 OOM 킬러와 약간 다릅니다. 그 것은 그룹의 중요성에 따라 프로세스를 분류하고 가장 낮은 그룹의 프로세스를 죽입니다. 그 것은 시스템을 최종 사용자(end user) 관점에서 안정적이게 만듭니다. 예를 들면, UI 프로세스 - foreground process -는 최종 사용자에게 가장 중요한 프로세스입니다. 그래서 프로세스를 지키는 것은 다른 background 프로세스의 삶을 지키는 것보다 더 안정적으로 보이는 것을 살립니다.

커널 패치 후에 CONFIG_LOW_MEMORY_KILLER 를 활성화하세요.

3.1.6 안드로이드 로거(Android Logger)


여러분이 이 기능을 활성화하면 /dev/log/main를 통해 안드로이드에 관한 유용한 정보를 볼 수 있습니다. main, events, radio 같은 /dev/log 상의 세가지 디바이스 파일이 있습니다. /dev/log/radio 파일은 안드로이드 시스템 상의 모뎀과 ril 데몬 - rild - 에 관련된 것을 보여줍니다.

이 로거를 활성화할때, 시스템 성능은 시스템 상에서 약간 느려집니다. 이 기능을 사용하기 위해서 CONFIG_ANDROID_LOGGER를 활성화하세요.

3.1.7 안드로이드 파워(Android power)


안드로이드 파워는 디바이스 상의 배터리 관리과 전원 관리에 관련된 파일 시스템 상의 inotify 기능과 같은 서브시스템을 위한 것입니다. 그 것은 안드로이드 시스템의 init 바이너리를 통해 안드로이드를 시작하기 위해서 필요합니다. 그러나 runtime 바이너리는 안드로이드의 수동 시작 상에서 안드로이드 파워에 따르는 어떤 파일 - /sys/android_power/acruire_partial_wake_lock - 을 찾고 시작에 실패합니다. 사용하기 위해서는 CONFIG_ANDROID_POWER 옵션을 활성화시키세요.

3.1.8 Panic Timeout


개발 보드 상의 안드로이드 시작을 위해서 필요없습니다. CONFIG_PANIC_TIMEOUT 를 원하는 값으로 설정하세요.

3.2 안드로이드 루트 파일 시스템


안드로이드 에뮬레이터는 tools/lib/images디렉토리 상에 3개의 기본 이미지를 가집니다.

  • ramdisk.img
  • system.img
  • userdata.img

ramdisk.img 은 gzip으로 압축된 cpio 파일입니다. 램디스크 이미지는 매우 작고, 설정 파일과 init과 recovery 같은 실행파일을 포함합니다. init 파일은 정식 System V init은 아닙니다. 그 것은 안드로이드를 위해 만들어졌고, 안드로이드 시스템을 시작하기 위한 특별한 것을 수행합니다.

system.img 와 userdata.img 는 VMS Alpha 실행파일입니다. system.img와 userdata.img 는 루트 파일 시스템 상의 /system 과 /data 디렉토리의 내용을 가집니다. 그들은 NAND 디바이스 상에 yaffs2 파일 시스템으로 맵핑되어 있습니다. /dev/block/mtdblock0 는 /system 이고, /dev/block/mtdblock1 은 /data 입니다.

/system 디렉토리는 라이브러리와 기본 시스템 패키지(*.apk)를 가지고 있습니다. /data 디렉토리는 타임존, 캐쉬, ApiDemos.apk 패키지를 가지고 있습니다.

주 서비스는 zygote(/system/bin/app_process), runtime(/system/bin/runtime), 그리고 dbus(/system/bin/dbus-daemon) 입니다. 여러분은 안드로이드 램디스크 상의 /etc/init.rc 파일을 볼 수 있습니다.

...zygote {    exec /system/bin/app_process    args {        0 -Xzygote        1 /system/bin        2 --zygote    }    autostart 1}runtime {    exec /system/bin/runtime    autostart 1}...dbus {    exec /system/bin/dbus-daemon    args.0 --system    args.1 --nofork    autostart 1}...

3.3 안드로이드 패키지의 라이센스


tools/lib/images/NOTICE 는 패키지 리스트와 각 라이브러리의 라이센스를 포함하고 있습니다. 라이센스 표는 2008 Korea Android Summit에서 임근식 씨의 발표로부터 게시되었습니다.

Open Source License
Linux Kernel GPL
NetBSD C Library BSD
DBUS GPL2
OpenBinder (core) GPL2
YAFFS2 GPL
SQLite GPL2
Webkit BSD (including LGPL)
WebCore LGPL
SDL LGPL
SGL Google(Skia)
OpenGL SGI OpenGL (BSD/MPL)


4 ARM EABI를 지원하는 툴체인


툴체인은 시스템 개발에 사용되어지는 툴들을 말합니다. C/C++ 컴파일러, 링커, 라이브러리, binutils와 기타 다른 것들을 포함합니다. 안드로이드 커널과 시스템은 EABI 지원을 필요로 합니다. 그래서 기존 툴체인은 안드로이드 시스템을 만드는데 호환되지 않습니다.

4.1 툴체인 빌드하기


더 쉽게 삶을 살기 위해서, Dan Kegel에 의한 crosstool-0.43 스크립트(http://www.kegel.com/crosstool/ )를 사용했습니다. 불행히도 그 것은 eabi 툴체인을 빌드하기 위한 지원을 하지 않습니다. 그래서 Khem Raj의 a glibc 2.5+ nptl build for arm softfloat eabi patch (http://sources.redhat.com/ml/crossgcc/2006-12/msg00076.html )를 적용했습니다.
$./arm-softfloat-eabi.sh

네트워크가 연결되어 있다면, 스크립트가 gcc 4.1.1 과 glibc 2.5을 사용해서 툴체인을 다운로드하고 빌드해 줄 겁니다.

4.2 다른 툴체인


Codesourcery 툴체인을 사용하지 않았습니다만, 그들은 그 것이 안드로이드 시스템 빌드를 위해서 잘 동작할 것이라고 말하고 있습니다.


5 커널


실제 하드웨어 상에 안드로이드를 포팅하는 것은 Benno (http://benno.id.au )에 의해서 시작되었습니다. 여러분은 그의 블로그에서 유용한 정보를 볼 수 있습니다. 그의 블로그는 pre-compiled static binaries를 링크합니다. 그것은 안드로이드 시스템 디버깅에 매우 유용합니다. 여러분 역시, static build busybox와 strace 바이너리를 빌드할 수 있지만, 갖다 쓰는 게 더 좋을 겁니다.

여러분은 안드로이드 커널과 바닐라 커널 2.6.23 버전 사이의 차이를 포함한 패치 파일을 얻을 수 있습니다. 그 것은 그것들 사이의 모든 차이를 가집니다. 그래서 여러분은 그것들의 일부를 추출할 필요가 있고, 여러분의 시스템 아키텍처를 위한 여러분 고유의 패치를 만들 수 있습니다.

예를 들면, 안드로이드 커널은 그 고유의 yaffs 파일 시스템 패치를 가집니다. 여러분의 아키텍처상에서 여러분 고유의 yaffs 나 jffs2 같은 어떤 다른 파일 시스템을 가진다면, yaffs 패치의 일부를 제거해야 합니다. 안드로이드 커널이 에뮬레이트하는 qemu 상의 ARM 아키텍처의 goldfish 아키텍처는 여러분의 아키텍처의 일부가 될 필요가 없습니다. 제거 될 수 있습니다.

안드로이드 커널은 ARMv5 명령을 에뮬레이트합니다. 그래서 ARM926EJ-S (ARMv5TEJ)는 작업하기 매우 좋을 겁니다.

5.1 커널 패치


Benno 는 openmoko의 NEO1973 디바이스로 작업했습니다. 그래서 그는 그 것을 위한 패치 파일을 만들었습니다. http://benno.id.au/blog/2007/11/21/android-neo1973 에서 원본 패치 파일을 얻고, android.diff를 사용했습니다. 그 것은 goldfish, qemu, yaffs 그리고 안드로이드에 특정적인 부분에 관한 전부를 가지고 있습니다.

여러분은 직접 패치 파일을 편집하고 제거할 수 있습니다. goldfish와 qemu에 특정적인 부분을 제외한 binder, 안드로이드 파워, 안드로이드 로거, low memory 킬러를 포함하는 패치를 만든 후에 바닐라 리눅스 커널 2.6.23을 얻고, 그 걸로 패치하세요.

여러분이 2.6.24.1 버전 리눅스 커널을 사용한다면 안드로이드 파워에 관련된 부분이 동작을 위해서 비활성화 되거나 적절히 고쳐져야 합니다.

5.2 .config


  • 필수적인 부분
...CONFIG_PANIC_TIMEOUT=0CONFIG_AEABI=yCONFIG_OABI_COMPAT=yCONFIG_BINDER=yCONFIG_LOW_MEMORY_KILLER=y...

  • 필요에 따른 부분
...# CONFIG_ANDROID_GADGET is not set# CONFIG_ANDROID_RAM_CONSOLE is not set# CONFIG_ANDROID_POWER is not set# CONFIG_ANDROID_LOGGER is not set...

6 루트 파일 시스템


루트 파일 시스템은 램 상의 기본 램디스크 이미지, NAND dev0 (/dev/block/mtdblock0) 그리고, NAND dev1 (/dev/block/mtdblock1)의 자료 이미지, 세가지 부분으로 제작되어 있습니다. MTD 디바이스는 yaffs2 파일 시스템을 가지고 각각은 안드로이드 에뮬레이터 상에서 64MiB 용량을 가집니다.

추출된 system 과 data 디렉토리는 실제 존재하는 NAND 디바이스 상에 복사되었고, 그들은 실제 하드웨어에서 동작시키기 위해서 --bind 옵션으로 마운트되어졌습니다.

6.1 에뮬레이터에서 램디스크 이미지 얻기


1. tools/lib/images/ramdisk.img에서 ramdisk 이미지를 unpack
$ gzip -cd ramdisk.img > ramdisk$ cpio -iv -F ramdisk

cpio 는 현재 작업중인 디렉토리상에 파일과 디렉토리를 푼다.

2. 램디스크의 내용 목록

datadevetcetc/default.propetc/firmwareetc/firmware/brf6150.binetc/firmware/brf6300.binetc/hcid.confetc/hostsetc/init.gprs-pppdetc/init.rcetc/init.riletc/init.testmenuetc/pppetc/ppp/chap-secretsetc/ppp/ip-downetc/ppp/ip-upetc/qemu-init.shetc/system.confetc/system.detc/system.d/bluez-hcid.confetc/usbd.confinitprocsbinsbin/recoverysyssystemtmpvarvar/run

6.2 에뮬레이터에서 data와 system 디렉토리 얻기



data와 system 디렉토리를 얻기 위해서 여러분은 busybox 바이너리를 static 컴파일하여야 합니다. 컴파일된 바이너리는 http://benno.id.au/blog/2007/11/14/android-busybox 에서 얻거나, 여러분 고유의 바이너리를 만들 수 있습니다.

1. 안드로이드 에뮬레이터를 실행시키세요.

2. 에뮬레이터 안에 static 컴파일된 busybox를 넣으세요.
# adb push busybox .

3. 안드로이드 쉘을 실행시키세요.
# adb shell

4. busybox로 tarball을 만드세요.
# chmod +x /busybox# busybox tar -c /data.tar /data# busybox tar -c /system.tar /system# exit

5. 에뮬레이터에서 tarball을 추출하세요.
# adb pull /data.tar .# adb pull /system.tar .

추출 명령은 종종 실패합니다. 성공적으로 될 때까지 계속 실행하세요.

6.3 존재하는 램디스크 이미지로 안드로이드 시스템을 통합하기


여러분의 아키텍처의 램디스크는 여러분의 작업을 조금 더 쉽게 만듭니다. system과 data 디렉토리를 제외한 안드로이드 램디스크의 내용을 여러분 고유의 램디스크로 복사하세요. 그리고 그냥 system과 data 디렉토리의 마운트 지점을 만드세요. 마운트 지점은 나중에 bind 옵션으로 사용될 수 있습니다. 안드로이드 램디스크 이미지의 init 바이너리는 시스템을 시작하기 위한 중요 바이너리이고, 그것은 /etc/init.rc 파일 상에서 설정 파일을 읽습니다.

/etc/init.rc를 편집하고 qemu 부분을 주석으로 만드세요.
...startup {        ...#       qemu-init {#           exec /etc/qemu-init.sh#       }}...

run.sh 스크립트를 만드세요. /dev/block/mtdblock5는 실제 NAND 디바이스의 mtd 파티션이고, 그 것은 /mnt 상에 마운트되어 집니다. data와 system 디렉토리는 이미 mtdblock5 상에 복사되어져 있습니다. 그래서 그 스크립트는 아래와 같이 / 상의 각 디렉토리의 바인드 마운팅(bind mounting)을 보입니다. 여러분의 보드 설정에 따라 스크립트를 고치세요.
#!/bin/shmount -t yaffs /dev/block/mtdblock5 /mntmount --bind /mnt/data   /datamount --bind /mnt/system /system# data folder is owned by system user on emulator. Fix 777 to other.chmod 777 /data#chmod 777 /systemexport PATH=/system/sbin:/system/bin:/sbin/usr/local/binexport LD_LIBRARY_PATH=/system/libexport ANDROID_BOOTLOGO=1export ANDROID_ROOT=/systemexport ANDROID_ASSETS=/system/appexport EXTERNAL_STORAGE=/sdcardexport ANDROID_DATA=/dataexport DRM_CONTENT=/data/drm/content/init &

터치스크린을 위한 필요에 따른 설정 - TSLib.
...export TSLIB_CONSOLEDEVICE=noneexport TSLIB_FBDEVICE=/dev/fb0export TSLIB_TSDEVICE=/dev/input/event1export TSLIB_CALIBFILE=/etc/pointercalexport TSLIB_CONFFILE=/etc/ts.confexport TSLIB_PLUGINDIR=/lib/tsexport LD_PRELOAD=/lib/libts.so:/lib/ts/pthres.so...

6.4 System 과 data 디렉토리


system 과 data 디렉토리의 내용은 이미 mtdblock5에 이미 복사되어져 있습니다. 여러분은 여러분 고유의 방법으로 복사하셔야 합니다. 그것을 사용하기 위해서 저는 루트 디렉토리상에 바인드 마운팅(bind mounting)을 선택했습니다. 바인드 마운팅은 이미 존재하는 디렉토리를 새로운 마운트 포인트로 마운트하는 기술입니다.

6.5 실행과 디버그


이제 커널과 램디스크와 자료 디렉토리 - data와 system -이 준비되었습니다. 빨간 사일런 눈을 볼 시간입니다. 여러분의 통합된 시스템을 부팅하고 나서 run.sh를 루트 디렉토리에서 실행하세요.
# cd /# . /android/run.shyaffs: dev is 32505861 name is "mtdblock5"yaffs: passed flags ""yaffs: Attempting MTD mount on 31.5, "mtdblock5"yaffs: auto selecting yaffs2# init: HOW ARE YOU GENTLEMENinit: reading config fileinit: device initinit: mtd partition -1,init: mtd partition 0, "l1boot"init: mtd partition 1, "u-boot"init: mtd partition 2, "params"init: mtd partition 3, "kernel"init: mtd partition 4, "ramdisk"init: mtd partition 5, "rootfs"sh: can't access tty; job control turned off# binder_open(c394bcc8 c3c731a0) (pid 1577) got c3e48000binder_open(c394bcc8 c3cd8dc0) (pid 1616) got c319f000binder_open(c394bcc8 c3cd8ac0) (pid 1673) got c3d10000binder_open(c394bcc8 c3cd8940) (pid 1680) got c0e19000binder_open(c394bcc8 c3cd88c0) (pid 1691) got c2fa0000binder_open(c394bcc8 c3d174a0) (pid 1592) got c25b8000binder_release(c394bcc8 c3cd88c0) (pid 1691) pd c2fa0000#

  • /dev 상에 eac 디바이스 파일을 만들지 마세요. 그 것은 qemu상의 오디오를 위한 것입니다. 만약 있다면 시작 절차(start up sequence)는 사운드 디바이스에 어떤 데이터를 쓰는 것을 끝마치기 위해서 영원히 기다릴 것입니다.
  • 수동 시작(manual startup) 대신에 안드로이드 init 바이너리를 사용하세요. 수동 시작은 안드로이드 패치가 필요합니다. 그 경우 시작 절차는 /sys/android_power/acquire_partial_wake_lock에 접근하고 기다릴 것입니다.

안드로이드 시스템을 디버깅하기 위해서 http://benno.id.au/blog/2007/11/18/android-runtime-strace 의 static 컴파일된 strace 바이너리를 사용하고, 안드로이드를 수동으로 실행하세요.

#!/bin/sh# set environment variables above example.../system/bin/app_process -Xzygote /system/bin --zygote &/system/bin/dbus-daemon --system &/system/bin/runtime

다음 예제는 수동 시작 절차를 보여줍니다. /system/bin/runtime 바이너리 상에서 strace를 사용하세요.

./strace -ff -F -tt -s 200 -o /tmp/strace runtime

6.6 스크린샷


recvfrom(4, "add@/devices/virtual/misc/networ"..., 1024, 0, NULL, NULL) = 144mknod("/dev/network_latency", S_IFCHR|0600, makedev(10, 58)) = 0chown32("/dev/network_latency", 0, 0)   = 0recvfrom(4, 0xbee2b72a, 1024, 0, 0, 0)  = -1 EAGAIN (invain)getdents64(8, /* 5 entries */, 4200)    = 136getdents64(8, /* 0 entries */, 4200)    = 0close(8)                                = 0SYS_305(0x7, 0x27f3b, 0x24000, 0, 0x28e98) = 8SYS_305(0x8, 0x1b6ec, 0x20001, 0, 0x28e98) = 9write(9, "add\n", 4)                    = 4close(9)                                = 0recvfrom(4, "add@/devices/virtual/misc/networ"..., 1024, 0, NULL, NULL) = 150mknod("/dev/network_throughput", S_IFCHR|0600, makedev(10, 57)) = 0chown32("/dev/network_throughput", 0, 0) = 0recvfrom(4, 0xbee2b72a, 1024, 0, 0, 0)  = -1 EAGAIN (Resource temporarily unavailable)getdents64(8, /* 5 entries */, 4200)    = 136getdents64(8, /* 0 entries */, 4200)    = 0close(8)                                = 0getdents64(7, /* 0 entries */, 4200)    = 0close(7)                                = 0SYS_305(0x6, 0x26f13, 0x24000, 0, 0x27e18) = 7SYS_305(0x7, 0x1b6ec, 0x20001, 0, 0x27e18) = -1 ENOENT (No such file or directory)getdents64(7, /* 3 entries */, 4200)    = 80SYS_305(0x7, 0x27e6b, 0x24000, 0, 0xffffffff) = 8SYS_305(0x8, 0x1b6ec, 0x20001, 0, 0x28e98) = 9write(9, "add\n", 4)                    = 4close(9)                                = 0recvfrom(4, "add@/devices/virtual/sound/timer"..., 1024, 0, NULL, NULL) = 128mknod("/dev/timer", S_IFCHR|0600, makedev(116, 33)) = 0chown32("/dev/timer", 0, 0)             = 0recvfrom(4, 0xbee2b72a, 1024, 0, 0, 0)  = -1 EAGAIN (Resource temporarily unavailable)getdents64(8, /* 5 entries */, 4200)    = 136getdents64(8, /* 0 entries */, 4200)    = 0close(8)                                = 0getdents64(7, /* 0 entries */, 4200)    = 0close(7)                                = 0getdents64(6, /* 0 entries */, 4200)    = 0close(6)                                = 0getdents64(5, /* 0 entries */, 4200)    = 0close(5)                                = 0

7 애플리케이션 개발


안드로이드 애플리케이션은 XML 레이아웃과 자바 문법을 사용합니다만, 자바는 아닙니다. 왜냐하면 그들은 그들 고유의 가상 머신 - dalvik - 과 dex 파일 형식을 위한 컴파일러를 사용하기 때문입니다. 그리고 Home.apk, Phone.apk, ApiDemos.apk 등 과 같이 apk로 이름붙여진 패키지를 사용합니다.

apk 파일은 ZIP 압축파일이고 네 가지 부분을 가집니다.

  • AndroidManifest.xml
  • classes.dex
  • resources.arsc
  • res 디렉토리

Dex 파일 형식은 http://www.retrodev.com/android/dexformat.html 에 설명되어져 있습니다. 그리고 그 파일들의 내용과 디렉토리는 언젠가 구글이 설명할 겁니다. 현재는 설명되지 않았습니다. 우리는 단지 그렇게 추측할 뿐입니다.

안드로이드 SDK는 *.apk 파일을 생성할 것입니다.

7.1 이클립스(Eclipse) 통합개발환경(IDE) 설치하기


http://code.google.com/android/intro/installing.html 의 설치 절차를 따르세요.

1. http://www.eclipse.org/downloads/ 의 (JDT와 WST 플러그인이 포함된)Eclipse IDE for Java developer


3. Apache Ant를 포함하는 eclipse plugin인 ADT (Android Development Tools)

7.2 샘플 애플리케이션을 빌드하고 실행하기


1. 샘플 프로젝트를 열고 빌드

2. 에뮬레이터 상에서 샘플 애플리케이션 실행

7.3 스크린샷


  • 노키아의 N810 제품(arm1136jf-s) 상의 안드로이드 플랫폼
    http://wiki.kldp.org/pds/AndroidPortingOnRealTarget/n810.kandroid200805.PNG

  • Android Platform on arm1136jf-S for another CE Product.
    fi.armadillo500.android1.0.jpg


8 에필로그


안드로이드 시스템은 데비안, 레드햇, 수세나 기타 등과 같은 모바일 환경을 위한 새로운 종류의 리눅스 기반의 배포판이 될 것으로 보입니다. 그들은 오픈소스 세상의 리눅스 커널과 많은 다른 라이브러리를 사용할 뿐입니다. 그들은 현재 3D 가속화를 OpenGL-ES 라이브러리에 기반한 소프트웨어를 제공합니다. 그러나 그들은 그를 위한 하드웨어 가속의 기본 프로세서 상에서 개발하고 있습니다. 그 하드웨어 가속은 추후의 빠른 UI 렌더링 효과를 위해 필수적입니다.

SDK 상의 안드로이드 시스템은 실제 하드웨어 상에 포팅하는 것은 완벽하지 않습니다. 왜냐하면, 라이브러리와 클래스에 관련된 어떤 디바이스 - 예를 들면, 카메라 -는 아직 구현되지 않았고, 사용자에게 공개되지 않았습니다. 그 것은 아직 개발 단계에 있는 것으로 보입니다. 그래서 구글의 전체 포팅 킷을 기다리는 것이 더 나을 것 같습니다.

그 전에, 우리는 안드로이드 시스템의 사업 모델을 살펴봐야만 합니다. 그 것은 약간 빠른 CPU 성능을 필요로 하기 때문에 운송 판매사는 싼 기본 프로세서(RF 부분)와 멀티미디어 코프로세서(co-processor)가 필요할 겁니다. 멀티미디어 기능을 포함하는 기본 프로세서는 매우 비싸기 때문입니다.

9 링크와 참조

Hello World

일단 전체 과정을 대략 정리..
  • eclipse를 실행한다.
  • android sdk 경로를 설정한다.
    menu > Window > Preferences > Android
  • 프로젝트를 만든다.
    1. menu > File > New Project > Android
    2. Project name, Build Target, Application name 등을 설정한다.
  • 코드 생성 : src > joinc.example > hello.java

    package joinc.example;  import android.app.Activity; import android.os.Bundle; import android.widget.TextView;    public class hello extends Activity {     /** Called when the activity is first created. */     @Override     public void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         TextView tv = new TextView(this);         tv.setText("Hello, Android");         setContentView(tv);     } }  
  • 실행 : Run > Run 후 Android Application을 선택한다. 그러면 Android 애뮬레이터가 뜨고, 부팅 과정을 거친후에 hello world 애플리케이션이 실행되는걸 볼 수 있다.

다음은 실행 화면


금방이네.. hello world를 찍었으니, 절반은 한 건가 ?

LayOut 편집


string resource 편집

프로그램에서 사용되는 다양한 자원들(프로그램 타이틀명, 각종 문자열등)은 XML데이터로 저장된다. 에디터로 XML 데이터를 편집하는 것으로 이들 자원의 값을 변경하거나 추가할 수 있다.
  • res/values/strings.xml
혹은 eclips ADT 플러그인 기능을 활용해도 된다. eclipse에서 해당 파일을 클릭하면, widzard 형식의 에디터로 값을 편집할 수 있다.

'Computer Science' 카테고리의 다른 글

Beginner iPhone SDK Hello World Tutorial [Example & Code]  (0) 2010.01.17
안드로이드 구조분석 wiki  (3) 2010.01.10
룩업 테이블  (0) 2010.01.09
EMACS 메뉴얼  (0) 2010.01.03
안드로이드 프로그래밍 개요  (0) 2010.01.03

+ Recent posts