Thứ Tư, 30 tháng 12, 2009

Android: Native Android Action

Native Android Action

Native Android applications allow Intents to launch Activities and Sub-Activities.
Actions list:
=> + content://contacts/people/1 -- Display information about the person whose identifier is "1".
=> + content://contacts/people/ -- Display a list of people, which the user can browse through.
=> +tel:123 -- Display the phone dialer with the given number filled in. Note how the VIEW action does what what is considered the most reasonable thing for a particular URI. => +content://contacts/people/1 -- Display the phone dialer with the person filled in.
=> +tel:123 -- Display the phone dialer with the given number filled in.

Thứ Ba, 29 tháng 12, 2009

Android: SharedPreferences

Shared Preferences
SharedPreferences let you save groups of key/value pairs of primitive data as named preferences. SharedPreferences is a lightweight mechanism to store a known set of values such as: user preferences, configuration, application settings...
The data which had created by SharedPreferences can be shared between applicaton components running in the same "Context".
Creating and Saving SharePreferences

//Define SharePreference Name
private static final String STRING_SHAREREF_NAME_USERREF = "USER REFERENCES";
//SharedPreferences object
private SharedPreferences mShareRefs = null;
//Create and save
protected void savePreferences() {
//get value from ui
boolean bAutoUpdate = mCbxAutoUpdate.isChecked();
int iFrequency = mSpinnerFrequency.getSelectedItemPosition();
int iMinMag = mSpinnerMinMagtitude.getSelectedItemPosition();

//Create SharedPreferences object
mShareRefs = getSharedPreferences(STRING_SHAREREF_NAME_USERREF,
Activity.MODE_PRIVATE);

//update to Preference by editor interface.
Editor editor = mShareRefs.edit();
editor.putBoolean(STRING_SHAREREF_USERREF_AUTOUPDATE, bAutoUpdate);
editor.putInt(STRING_SHAREREF_USERREF_FREQUENCYUPDATE, iFrequency);
editor.putInt(STRING_SHAREREF_USERREF_MINMAG, iMinMag);
editor.commit();
}
Notes:
- If you want to save information that doesn't need to be shared with others component, you can call Activity.getPreferences(Mode) without a specifying preference name.
(Activity).getPreferences(Activity.MODE_PRIVATE);

Retrieve the saved values:
SharedPreferences object offers some method to get persist data (type boolean, String, int, Long, ..):
  • getBoolean(..);
  • getInt(..);
  • getString(..);
  • ...


Ref:
- Pro Android June 2009
- Profession Android Application Development.

Android: Services

Because of the limited screen size of the mobile devices, typically only one application is visible and activate on device screen at any given time. Android offers Service class to create application components specifically to handle operation and functionality that should run silently, without a UserInterface. Android Services is higher priority than an inactive Activity, so they're less likely to be killed when the system requires resources. By using Service, you can ensure that applications continuous to run and response to events, even when they're inactive.

Android offers several techniques for application to communicate with users with an Activity providing a direct UserInterface, for ex: Notifications, Toast.
  • Toasts are a transient, non-modal Dialog-box mechanism used to display information to users without stealing focus from the active application.
  • Notifications represent a more robust mechanism for alerting users. Many users, when they're not actively using their mobile phones, they sit silent and unwatched in pocket or on a desk until it rings, vibrates or flashes. Should a user miss these alerts. This case, status bar icons are used to indicate that an event has occurred. All of these attention-grabbing antics are available within Android as Notifications.
  • Alarms provide a mechanism for fi ring Intents at set times, outside the control of your application lifecycle. An Alarm will fire even after its owner application has been closed, and can (if required) wake a device from sleep.
If your application regularly, or continuously, performs actions that don't depend directly from a user input, Services my be the answer. Start Service receive higher priority than inactive or invisible Activity, making them less likely to be terminated by run time's resource management. The only time Android will stop a Service prematurely is when it’s the only way for a foreground Activity to gain required resources; if that happens, your Service will be restarted automatically when resources become available.

Creating and Controlling Service
Services is extended from Service base class. Services are designed to run in the background, so they need to be started, stopped and controlled by other application component.

Notes:
- Once you've contructed a new Service, you have to register it in the application manifest file within the service tag:
...

(... to be continuous...)


Ref:
- Pro Android June 2009
- Profession Android Application Development.

Thứ Hai, 28 tháng 12, 2009

Android: Http Connection

This time, I'm going to building a service in Android. There are a lot of types of services with Android included: IPC (communication between applications on the same device), get resources outside the devices by various type of connections. I'll focus on Http connection first.
Although Android included web-browser application in the basic applications, but there are several benefits to creating thick and thin native application rather than relying on entirely web-base:
- Bandwidth
- Caching
- Native features.
With currently connection methods:
- GPRS, EDGE, 3G.
- Wi-Fi.
more details could collected from reference books below.

Connection permission for Android application
By Eclipse ADT plug-in:
- Open AndroidManifest.xml file (in design mode)
- Select "Permissions" tab ==> click "Add" and select "Uses permission"
- At the "Name" property, select "android.permission.INTERNET"
- Save setting.

By XML editor:
- Open AndroidManifest.xml file (in editor mode)
- Add below code:
Open an URL connection and get content:

public static String getHttpContent(String prURL) {
String strResult = "";
StringBuffer sbfResult = new StringBuffer();
String newline = System.getProperty("line.seperator");

try {
URL url = new URL(prURL);
URLConnection urlcon = url.openConnection();
HttpURLConnection httpurlcon = (HttpURLConnection) urlcon;

int responseCode = httpurlcon.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream in = httpurlcon.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = br.readLine()) != null) {
sbfResult.append(line).append(newline);
}
br.close();
in.close();
}
} catch (Exception e) {
sbfResult.append(e.getMessage()).append(newline);
}finally{
if (sbfResult != null) {
strResult = sbfResult.toString();
}else{
strResult = "StringBuffer has failed.";
}
}
return strResult;
}
}

Referenced:
- Pro Android June 2009
- Profession Android Application Development.

Thứ Năm, 24 tháng 12, 2009

Android: Overridable functions in Application's lifecycle

onSaveInstanceState
onSaveInstanceState() is called by Android if the Activity is being stopped and may be killed before it is resumed! This means it should store any state necessary to re-initialize to the same condition when the Activity is restarted. It is the counterpart to the onCreate() method, and in fact the savedInstanceState Bundle passed in to onCreate() is the same Bundle that you construct as outState in the onSaveInstanceState() method.

Thứ Tư, 23 tháng 12, 2009

Android: Introduction

What is Android ?
q
Is a Platform:
  • §Built on Linux kernel.
  • §For open handset devices.
  • §Open-source libraries for Web, SQLLite, OpenGL, SSL,…
Also included Middle-ware
  • §Base on C/C++ Linux kernel.
  • §Fully support for Java developer (by JNI).
  • §Use XML for flexible UI and Effect definition.
And is Key Applications with Android Software Stack
  • §Have a lot of applications fully support for PIM. (Contacts, Calendar, Phone, SMS Manager, Browser, Player, ..)

Android Application Software Stack
Slide 4
-
Linux Kernel 2.6 -Set of C/C++ open-source libraries had been converted to Java protocol for Java developer. -Surface Manager - manages access to the display subsystem and seamlessly composites 2D and 3D graphic layers from multiple applications -Android runtime with multi Dalvik VM instances and GC,.. Each Android Application (process) have it own Dalvik VM. -Application Framework: include so many services for management: - Content Providers: share data between components or applications. - Activity Manager: manages the lifecycle of applications and provides a common navigation back stack. (based on Android Software Stack) - Window Manager: - View System: Create interfaces for user. - Package Manager: manage installed applications, packages, librabries. - Telephony Manager: Phone’s services. - Resource Manager: providing access to non-code resources (strings, graphics, and layout files) - Location Manager: - Notification Manager: display custom alerts in the status bar. -APIs (JDK or NDK) for fully interacted with services and devices.
The Dalvik Virtual Machine
The Dalvik VM is a registered-base virtual machine. It is optimized for low memory requirements, and is designed to allow for multiple VM instances to run at once, relying on underlying operating system for process isolating, memory management and threading support. Dalvik use .dex files format:
A dx tool will compile Java class files to. dex file format. Multi classes are included in one .dex file, alls duplicate string or resource will be reduced for smallest size. Java byte codes are also converted into a alternative instruction set used by Dalvik VM. Dalvik executables may be modified again when they get installed onto a device.
Dalvik VM was slimmed down to use less space. Dalvik has modified constant pool to use only 32-bit indexes to simplify the interpreter. Dalvik VM use it own byte code, not Java byte code. The name “Dalvik” is belong to the name of a village in Iceland where Dan Bornstein’s ancestors lived. -The executable code on Android, as a result in Dalvik VM, is based not on Java byte code, but on .dex files format instead. -The java compiled class or .jar standard executable file are not compatible with Android. Why no “JIT” : Google has fine-tuned the garbage collection in the Dalvik VM, but it has chosen to omit a just-in-time (JIT) compiler, in this release at least. The company can justify this choice because many of Android’s core libraries, including the graphics libraries, are implemented in C and C++. For example, the Java graphics APIs are actually thin wrapper classes around the native code using the Java Native Interface (JNI). Similarly, Android provides an optimized C-based native library to access the SQLite database, but this library is encapsulated in a higher-level Java API. Because most of the core code is in C and C++, Google reasoned that the impact of JIT compilation would not be significant.

Thứ Năm, 17 tháng 12, 2009

Android: Error on missing resource

Now in Android - Eclipse IDE technique.
Have you ever got into an error like:

""is missing required source folder: 'gen'"
or this pic:


On Eclipse IDE, just right click and delete "gen" folder in your Package Explorer and Build project again. Got that ?

Gook luck,

Thứ Năm, 10 tháng 12, 2009

How to create a certificate with "makekeys"

Duty:
Create a self-sign certificate to sign on MIDlet, Symbian apps, Applet, .Net appls, ..

Resource: makekeys.exe executable file

Command:
%prompt%>makekeys -expdays 3650 -cert -password yourpassword -len 2048 -dname "CN=CertificateName OU=OrganizationUnit OR=ORganization CO=COuntry EM=yourEMail@now
here.com" keyfilename.key certificatefilename.cer


Result:
Reference from Symbian.com

Good luck!!

Thứ Ba, 8 tháng 12, 2009

Symbian - Carbide: Compilation Fails: Bareword Found Where Operator Expected (Wrong Active Perl version)

Compilation Fails: Bareword Found Where Operator Expected

Problem: When compiling an application, the process fails. The Problems view of Carbide.c++ reports that a .hlp.hrh file cannot be opened. In the Console view, problems with a Perl script are obvious (params.pm).

.hlp.hrh file cannot be opened
Problems with the perl script

Cause: The version of Perl on your system is newer than 5.6.x. The Symbian OS toolchain is not fully compatible to the 5.8.x/5.10.x release – you will probably not notice it for most projects, but, for example, compiling help files does not work with ActivePerl 5.8/5.10.

Solution: Either install Perl 5.6.1 , or follow the steps at http://wiki.forum.nokia.com/index.php/KIS001302_-_Compiling_context-sensitive_help_fails_with_latest_version_of_Perl:

Go to your SDK installation's "Epoc32\tools\perllib" path:

- Open file args.pm, change the following line (# 688)

$self->_iSpecArray->{$aName}= New CArgsSpec($aName, $aDefault, $aPattern,
$aExclusions, $aMandatory, $aRepeatable);

to

$self->_iSpecArray->{$aName}= CArgsSpec->New($aName, $aDefault, $aPattern,
$aExclusions, $aMandatory, $aRepeatable);

- Open file params.pm, search for the word "New" and replace it with "foo->New()"; for example, if there is a function "New CLogs()".

Reference from Developer.Symbian.com and Wiki.forum.nokia.com