Archive

Archive for the ‘Android’ Category

Activate android mobile without activation key

April 21st, 2009 3 comments

You can activate Android mobile without activation key. After that you can easily access Internet or can
insert your sim card. Just follow the steps given:

1. You need android SDK first. You can get android SDK zip easily: http://developer.android.com/sdk/1.1_r1/index.html

2. Connect your android mobile phone to PC.

3. Get a driver for android mobile from site: http://modmygphone.com/wiki/index.php/Setting_up_ADB. Install this driver.

4. Open DOS prompt, goto android mobile SDK’s tool folder.

5. Enter a command: adb -d shell

6. In the shell, become root and modify settings.db to remove the “no sim card found” screen lock:
$ su
$ sqlite3 /data/data/com.android.providers.settings/databases/settings.db
sqlite> INSERT INTO system (name, value) VALUES (‘device_provisioned’, 1);
sqlite> .quit
#

7. Reboot the phone.

8. Reconnect with the adb shell and launch the settings activity (does not require root):
$ adb shell
$ am start -a android.intent.action.MAIN -n com.android.settings/.Settings

9. Using the settings activity that you’ve launched on the phone’s screen, enable wifi.

10. Activate the phone with a gmail account. You can insert your SIM card now.

Categories: Android Tags:

Tutorial – How to start a new Activity

March 31st, 2009 55 comments

For starting a new Activity we need to use intent, which is an abstract description of an operation to be performed.

http://developer.android.com/reference/android/content/Intent.html

Suppose we are on Activity named ‘CurrentActivity‘ and on certain event (like button click..) we want to start a new Activity named ‘NextActivity’

We can create a new activity as follows.

public class NextActivity extends Activity {

//Your member variable declaration here

// Called when the activity is first created.
@Override
public void onCreate(Bundle savedInstanceState) {
//Your code here
}
}

After we have created the new Activity, we have to register it in file ‘AndroidManifest.xml’.
For registering we have to create an entry in ‘AndroidManifest.xml’ as

<activity android:name=".NextActivity"
android:label="@string/app_name">

</activity>

Note that here we have not used intent filter , since we are going to use an explicit intent, the syntax of intent filter is

<intent-filter>

<action android:name="<action here>"/>

<category android:name="<category here>"/>

</intent-filter>

Here,
action — The general action to be performed

category — Gives additional information about the action to execute. For example, CATEGORY_LAUNCHER means it should appear in the Launcher as a top-level application, while CATEGORY_ALTERNATIVE means it should be included in a list of alternative actions the user can perform on a piece of data.

Note: you can also use application tab below the ‘AndroidManifest.xml’ file, and in ‘Application Nodes’ section click
‘Add’ button as shown in figure below and select the activity .

Application Node-Add Activity

Application Node-Add Activity

Next you can start this activity on any event as follows

Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);
CurrentActivity.this.startActivity(myIntent);

Here, you have to create and intent with CurrentActivity.this as first parameter
and the the next activity as second parameter.

After you have created the intent, you can start the new activity by calling
startActivity, on current Activity, with the created intent as parameter.

Categories: Android Tags: , ,

Android Audio Support

February 13th, 2009 4 comments

Android support Media API as optional APIs. The media APIs provide functionality of playing and recording audio files and video files. In today’s post we will see how to play and record audio files.

Playing Audio File:
Android has defined a MediaPlayer class for playing media file. This class can be used to play the audio files. The class provides static methods to create the instance of the media player. Here is how the MediaPlayer object can be obtained using create methods

MediaPlayer.create(context, Uri.parse("file:///sdcard/audio_file.mp3");

and

MediaPlayer.create(context, R.raw.song_file);

The first create methods gets the Uri for the audio file and can be used to play files present on the phone sdcard. The second create method use the application resource file song_file.mp3. The song_file.mp3 file is added as a raw resource under res/raw directory.
Note that if the MediaPlayer object does not get created successfully, the create methods will return null so it will be better to check for the return object for null value to avoid NullPointer exception.

The MediaPlayer object can also be obtained by instantiating using MediaPlayer constructor. The object created like this has to be initialized with the file that needs to be played. setDataSource() method can be used to initialize the object with the audio file.

MediaPlayer mediaPlayer = new MediaPlayer();

try {
mediaPlayer.setDataSource("/sdcard/audio_file.mp3"); // provide path to the file.
} catch (IllegalArgumentException e) {
// handle exception
} catch (IllegalStateException e) {
// handle exception
} catch (IOException e) {
// handle exception
}

If you want to send the media player object with one of the files from application raw resources or from application assets files you can do that as follows:

try {
AssetFileDescriptor fd = getResources().openRawResouceFd(R.raw.song_file);
mediaPlayer.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
fd.close();
} catch (IllegalArgumentException e) {
// handle exception
} catch (IllegalStateException e) {
// handle exception
} catch (IOException e) {
// handle exception
}

The MediaPlayer object has to be prepared before the player can start playing the song. The prepare() method is the blocking method and blocks until the media player is ready to play the song. One non blocking method prepareAsync() is also provided. The non blocking prepare method should be used in case media player is used to play a song from a stream and need to buffer data before song can be played. The create methods that we saw earlier call the prepare() method and application must not call it again. To start file playback use start() method. This is how you play a file:

MediaPlayer mediaPlayer = new MediaPlayer();

try {
mediaPlayer.setDataSource("/sdcard/audio_file.mp3"); // provide path to the file.
mediaPlayer.prepare();
} catch (IllegalArgumentException e) {
// handle exception
} catch (IllegalStateException e) {
// handle exception
} catch (IOException e) {
// handle exception
}

mediaPlayer.start();

The file playback can be pause with pause() method, and can be resumes with start method. The file playback can be stopped with stop() method. The media player object has to reset before it can be setup for some other song file. The media player object has to be released after its use.

Android Media API defines some listeners like OnCompletionListener, OnPrepareListener, OnErrorListener, OnBufferingUpdateListener
OnCompletionListener event gets fired when media player complete the playing of the current audio file. You can use this listener event for playing next song from the list or releasing the media player object.

OnPrepareListener is needed when prepareAsync method is used. Since the prepareAsync method does not block for the call duration, the application can not start playing the song. The onPrepared() event function will be called once the media player is ready. You can start playing the song in the onPrepared() method.

OnErrorListener is also used in case of asynchronous operations. If any error occurs in asynchronous operation, onError() method of this listener will be called.

Recording Audio Files:

The Media API also provides functionality to record audio files. The MediaRecorder class can be used for media recording. The MediaRecorder has to be initialized with the Audio Encoder, output format (codec to be used for recorded file), Audio Source (like Microphone) and output file path where the recorded file will be stored. Here is how recording can be done:

MediaRecorder recorder = new MediaRecorder();

recorder.setAudioSource(MediaRecorder.AudioSource.MIC); recorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT); recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

recorder.setOutputFile(filePath); // complete file path

recorder.prepare(); recorder.start();

This will start the recording the recording can be stored with stop() method. The MediaRecorder object also needs to be release after its use.
That all for today’s post. We will see Media APIs Video support in some other post.

App attacks on Gphones

January 27th, 2009 1 comment

Malware has already made its way into the Android market place. According to these news reports 1, 2 applications which takes “advantage” of Android phones or applications which harms the phone are available for download in Android market place. According to few experts this has raised question on the policy of keeping the open market.

First of all, Android market place does not mean that Google or Open handset alliance is verifying the applications. So a user can be mislead to download a malicious application. Even though Google has reactively removed such application from market place, but from here onwards if Google/OHA wants to keep up the momentum around Android and make Android as mainstream mobile platform they will have to become proactive. A small certification fees which will cover the cost of testing out the application can be applied before an application is made available on the market place. I dont think Android developers and application vendors will mind such entry fees as we hope to reach a very large consumer base through such market place which users trust and hence use.

Categories: Android Tags:

Android Basics – Managing Activity States – Part II

January 26th, 2009 2 comments

In the last post we saw how to use android provided onSaveInstanceState() method to manage the activity state. In this post we will see how we can use preferences to save the activity state.

Android provided two ways to use the preferences

1. Shared Preferences: The shared preferences can be used by all the components (activities, services etc) off the applications.

2. Activity handled preferences: These preferences can only be used with in the activity and can not be used by other components of the application.

Shared Preferences:

The shared preferences are managed with the help of getSharedPreferences method of the Context class. The preferences are stored in the file and file name is used to refer to the preferences.

Here is how you can retrieve the stored values from the preferences

...
public static final String PREF_FILE_NAME = "PrefFile";
...

SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);

 int storedPreference = preferences.getInt("storedInt", 0);
 // use the values

MODE_PRIVATE is the operating mode for the preferences. It is the default mode and means the created file will be accessed by only the calling application.  Other two mode supported are MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE. In MODE_WORLD_READABLE other application can read the created file but can not modify it. In case of MODE_WORLD_WRITEABLE other applications also have write permissions for the created file.

To store values in the preference file SharedPreference.Editor object has to be used. Editor is the nested interface of the SharedPreference class.

...
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);

 SharedPreferences.Editor editor = preferences.edit();
 editor.putInt("storedInt", storedPreference); // value to store
 editor.commit();
....

Editor also support methods like remove() and clear() to delete the preference value from the file.

Activity Preferences:

The shared preferences can be used by other application components. But if you do not need to share the preferences with other components and want to have activities private preferences. You can do that with the help of getPreferences() method of the activity. The getPreference method uses the getSharedPreferences() method with the name of the activity class for the preference file name.

Following is the code to get preferences

SharedPreferences preferences = getPreferences(MODE_PRIVATE);
int storedPreference = preferences.getInt("storedInt", 0);
// use the values

The code to store values is also same as in case of shared preferences.

SharedPreferences preferences = getPreference(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();

You can also use other methods like storing the activity state in database. Note Android also contains a package called ‘android.preference’. The package defines classes to implement application preferences UI. We will see the preference package in some other post.

Android Basics – Managing Activity States – Part I

January 24th, 2009 5 comments

Managing and preserving an activity state is very important.  If the activity state is not preserved properly, application can loose the data.

Using onSaveInstanceState():
Android provide two method onSaveInstanceState() and onRestoreInstanceState() to handle the activity state. onSaveInstanceState method gets called for an activity when user leaves the activity. Note this method is only called when activity is present in the History state and user can come back to the activity. Android provide a default implementation for this method. The default implementation save state of all the views which has id attribute defined. The default implementation of the onRestoreInstanceState() restores the state of the views. The bundle saved by the onSaveInstanceState() activity is passed to onCreate() and onRestoreInstanceState() methods both.

You can override the onSaveInstaceState method to save activity internal variable in the bundle. But do not forget to call the onSaveInstanceState method of the super class, otherwise handle the UI component state management your self.

Let’s create an example that clears the concepts

Example:
Here is the layout of the activity that ask user about it name and a secret

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="@+id/mainLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter your name:"
>
</TextView>
<EditText
android:id="@+id/nameEditText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="18sp"
>
</EditText>
<TextView
android:id="@+id/secretMessage"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Enter your Secret (I will not remember this):"
>
</TextView>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="18sp"
>
</EditText>
</LinearLayout>

Note that the editText for the secret message dose not have an Id attribute defined. The StateExampleActivity class looks like this

 public class StateExampleActivity extends Activity {

        /**
        * @see android.app.Activity#onCreate(android.os.Bundle)
        */
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.state_example_activity);
        }

        /**
        * @see android.app.Activity#onSaveInstanceState(android.os.Bundle)
        */
        @Override
        protected void onSaveInstanceState(Bundle outState) {
            super.onSaveInstanceState(outState); // the UI component values are saved here.
            Toast.makeText(this, "Activity state saved", Toast.LENGTH_LONG).show();
        }

        /**
        * @see android.app.Activity#onDestroy()
        */
        @Override
        protected void onDestroy() {
            super.onDestroy();
            Toast.makeText(this, "Activity is getting killed", Toast.LENGTH_LONG).show();
        }
    }

Our implementation of onSaveInstanceState() does not do much since the state of the views with Id is by default saved by the onSaveInstanceSate() method of super class.

Make the entry of the StateExampleActivity in the AndroidManifest.xml

<activity android:name="StateExampleActivity" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

Now start the application in the emulator. Put some data in the activity fields when activity is shown. Click on the Home button on the emulator.  If only ‘Activity saved’ message is shown means the activity is not killed and the UI components does not loose their values.  If you go back to the activity, you will be able to see values for both the text boxes name and secret text box.

To kill the activity when we leave it, android provided ‘Dev Tools’ can be used.  Dev tools application can be opened from list of applications.  Go to the Development Settings. You will see number of useful development settings. Check the ‘Immediately destroy activities’ check box. This will kill the activity after we left it.

Now run the application and follow the steps we followed earlier. Now after clicking the emulator home button the activity save and destroy message will be shown.  If you reopen the activity now only user name value will be restored and secret will be lost.

Note if you click on the emulator BACK button the activity state will not be saved since the activity dose not go in the History stack. In that case the values for all the components will be lost.

Using state Bundle to save data:

Application can use activity’s state bundle to save data other than the UI component values, as shown

   protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("TO_REMEMBER", "Remember this"); // adding a string in bundle
        Toast.makeText(this, "Activity state saved", Toast.LENGTH_LONG).show();
    }

The saved value can be restored in onCreate method as follows:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.state_example_activity);

        if (savedInstanceState != null) {
            Toast.makeText(this, "onCreate() : " + savedInstanceState.getString("TO_REMEMBER"), Toast.LENGTH_LONG).show();
        }
    }

The state can be restored in onRestoreInstanceState() method too. Note that the onCreate() or onRestoreInstanceState() methods will only be called if the activity is killed.

As we saw the Android helps us to keep the state of the activity. But what if application wants to preserve the values even when user cancels the activity by using BACK button? That can be achieved with the help of preferences. We will see how to use preferences in second part of this post.

Samsung’s Android handset will reach market in 2009

January 24th, 2009 No comments

Samsung is also launching an Android based smartphone. The phone is expected to be released in mid 2009. All the device features are not known yet but the phone will be touch-screen based with minimum buttons and design similar to Omnia (see image).

Samsung Omnia

After Sony Ericsson and Motorola, Samsung is now the third major phone manufacturer to have announced Android based phones. Android market is getting hot.

Android Powers Netbook

January 9th, 2009 No comments

Today Qualcomm said it is using Android to power the latest netbook from its offerings. Industry experts have been speculating that Android will not merely remain a mobile operating system but soon will become operating system powering other, essentially, mobile devices like Netbooks, laptops.
Move was expected but this will happen so soon, with in 2 years of Android announcement is definitely a little surprising. We think that it will take another 2 years for Android to start dominating the entire range of mobile and slim devices market.
As developers, this means more and more enterprises will be porting applications to Android.
Overall momentum around Android is definitely picking up!

Categories: Android Tags:

Why Android? : Equality of applications

December 30th, 2008 No comments

In this series of articles we will be exploring why Android is considered to be future of mobile platforms.

One of the most important reason is All Android applications are equal. Android platform is developed as set of applications. You have a core engine which runs all these applications. The core engine is essentially a virtual machine which provides APIs to communicate with hardware resources to applications.

Apart from this core engine/virtual machine everything else in Android is an application.  So user can replace the default dialer software with some other customized one. You can change how your home window is displayed. You can replace absolutely any application installed on your phone.

From developer perspective, this opens up a whole new range of applications that you can build. It was not possible to this before Android. Most of the other mobile platforms come with set of applications which are hardwired into the system and can not be replaced. With Android, change is here. You do not have to live with boring applications any more.

Categories: Android Tags:

Hello Android

December 29th, 2008 No comments

Finally Google decides to enter mobile market. Big time.

Recently all the big companies have realized potential of the mobile market and users. Everyone who has funds available at disposal is looking at mobile market. We have big players now and with Google’s entry things are going to get really competitive. Users are going to be the people who win in all this competition.

This blog and this competency center for people who are -

  • Users of Android phones
  • Android application developers
  • Experts on mobile markets
  • Android evangelists and enthusiasts

We will be talking here about new developments in the world of Android and over all mobile markets. We will be providing in depth analysis of Android as commercial platform for mobile application delivery. We will provide hands on instructions, help, work arounds for Android application developers. Keep reading.

Categories: Android Tags: ,