Oct 5, 2011

How to add a splash screen in an android application


Everyone wants his/her application to be beautiful and attractive for an eye of a user. And there are a lot of applications, at least desktop applications, mostly games that use splash screens. It’s nice and, moreover, while the splash screen is working, you can initialize your application. Many tutorials exist explaining how to begin Android programming and I won't repeat them here. You can find them all over the internet. So I will show only the programming stuff.


Activity class
---------------
public class SplashScreen extends Activity {
private final int DISPLAY_LENGTH = 2000; // splash screen duration
private ProgressBar mProgressBar;

@Override
public void onCreate(Bundle si) {
super.onCreate(si);
// removing status bar in
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);

setContentView(R.layout.splash);
mProgressBar=(ProgressBar)findViewById(R.id.xPbSplash);
// setting progress bar
mProgressBar.setVisibility(ProgressBar.VISIBLE);

// created handler for waiting
// post delayed to wait some time before going to next intenet

new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent login = new Intent(SplashScreen.this, HomeScreen.class);

SplashScreen.this.startActivity(login);
mProgressBar.setVisibility(ProgressBar.INVISIBLE);
SplashScreen.this.finish();
}

}, DISPLAY_LENGTH);
}

}


xml for UI
--------------

android:layout_width="fill_parent" android:layout_height="fill_parent"
android:background="@drawable/bg" android:orientation="vertical">
android:layout_height="60dip" android:background="@drawable/logo"
android:layout_centerInParent="true" />
android:layout_width="50dip" android:layout_height="50dip"
android:layout_centerInParent="true" android:indeterminateOnly="true" />




Sep 29, 2011

How to Implement Voice Recognize in Android

I’ve been searching for a simple tutorial on using voice recognition in Android but haven’t had much luck. The Google official documentation provide an example of the activity, but don’t speculate anything more than that, so you’re kind of on your own a little.

Luckily I’ve gone through some of that pain, and should make this easy for you, post up a comment below if you think I can improve this.

I’d suggest that you create a blank project for this, get the basics, then think about merging VR into your existing applications. I’d also suggest that you copy the code below exactly as it appears, once you have that working you can begin to tweak it.

With your blank project setup, you should have an AndroidManifest file like the following



manifest.xml

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


xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.voice.recog"
android:version
Code="1"
android:versionName="1.0">
<application android:label="VoiceRecognitionDemo" android:icon="@drawable/icon"
android:debuggable="true">
<activity android:name=".Main"
android:label="@string/app_name">
<intent-filter
>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
intent-filter>
activity>
application>
manifest>


And have the following in res/layout/voice_recog.xml :
xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="
http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="4dip"
android:text="Click the button and
start speaking" />

<Button android:id="@+id/speakButton"
android:layout_width="fill_parent"
android:onClick=
"speakButtonClicked"
android:layout_height="wrap_content"
android:text="Click Me!" />

<ListView android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="1" />

LinearLayout>

And finally, this in your res/layout/main.xml :

xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="VoiceRecognition Demo!"
/>
LinearLayout>

So thats your layout and configuration sorted. It will provide us with a button to start the voice recognition, and a list to present any words which the voice recognition service thought it heard. Lets now step through the actual activity and see how this works.

You should copy this into your activity :


package com.voice.re
cog;

import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.speech.RecognizerIntent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import
java.util.ArrayList;
import java.util.List;

/**
* A very simple application to handle Voice Recognition intents
* and display the results
*/
public class Main extends Activity
{

private static final int REQUEST_CODE = 1234;
private ListView wordsList;

/**
* Called with the activity is first created.
*/

@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.voice_recog);

Button speakButton = (Button) findViewById(R.id.speakButton);

wordsList = (ListView) findViewById(R.id.list);

// Disable button if no recognition service is present
PackageManager pm = getPackageManager();
List activities = pm.queryIn
tentActivities(
new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if (activities.size() == 0)
{
speakButton.setEnabled(false);
speakButton.setText("Recognizer not present");
}
}

/**
* Handle the action of the button being clicked

*/
public void speakButtonClicked(View v)
{
startVoiceRecognitionActivity();
}

/**
* Fire an intent to start the voi
ce recognition activity.
*/
private void startVoiceRecognitionActivity()
{
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Voice recognition Demo...");
startActivityForResult(intent, R
EQUEST_CODE);
}


/**
* Handle the results from the voice recognition activity.
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK)

{
// Populate the wordsList with the String values the recognition engine thought it heard
ArrayList matches = data.getStringArrayListExtra(
RecognizerIntent.EXTRA_RESULTS);
wordsList.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1,
matches));
}
super.onActivityResult(requestCode, resultCode, data);
}
}

Breakdown of what the activity does :

Declares a request code, this is basically a checksum that we use to confirm the response when we call out to the voice recognition engine, this value could be anything you want. We also declare a ListView which will hold any words the recognition engine thought it heard.

The onCreate method does the usual initialisation when the activity is first created. This method also queries the packageManager to check if there are any packages installed that can handle intents for ACTION_RECOGNIZE_SPEECH. The reason we do this is to check we have a package installed that can do the translation, and if n

ot we will disable the button.

The speakButtonClicked is bound to the button, so this method is invoked when the button is clicked.

The startVoiceRecognitionActivity invokes an activity that can handle the voice recognition, setting the language mode to free form (as opposed to web form)

The onActivityResult is the callback from the above invocation, it first checks to see that the request code matches the one that was passed in, and ensures that the result is OK and not an error.

Next, the results are pulled out of the intent and set into the ListView to be displayed on the screen.

Notes on debugging :

You won’t have a great deal of luck running this on the emulator, there may be ways of using a PC microphone to direct audio input into the emulator, but that doesn’t sound like a trivial task. Your best bet is to generate the APK and transfer it over to your device (I’m running an Orange San Francisco / ZTE Blade).

If you experience any crashing errors (I did), then connect your device via USB, enable debugging, and then run the following command from a console window

1
/platform-tools/adb -d logcat
What this does, is invoke the android device bridge, th

e -d switch specifies to run this against the physical device, and the logcat tells the ADB to print out any device logging to the console.

This means anything you do on the device will be logged into your console window, it helped me find a few null pointer issues.

That’s pretty much it, its quite a simple activity. Have a play with it and if you have any comments please let me know. You may have mixed results with what the recognition thinks you have said, I’ve had some odd surprises, let me know!

Happy coding!

Sep 28, 2011

Gesture detection in Android, part 2 of 2 ( Character Dector )

From Android 1.6 onwards includes a new package android.gesture which is used to for complex gesture recognition. This package includes APIs to store, load, draw and recognize gestures. We can define our own pre-defined patterns in our application and store these gestures in a file and later on use this file to recognize the gesture.

Gestures Builder application

There is a handy sample application, Gestures Builder, which comes with the Android 1.6 and higher. This application is pre-installed in 1.6 and higher emulators. Here is a screenshot of the application:




Gesture Builder Sample application
Using this application we can create our gesture library and save it to SD card. Once the file is created we can include this file in our application in /res/raw folder.

Loading a gesture library

To load the gesture file, we use the class GestureLibraries class. This class has functions to load from resource, SD card file or private file. GestureLibraries class has following methods:

static GestureLibrary fromFile(String path)
static GestureLibrary fromFile(File path)
static GestureLibrary fromPrivateFile(Context context, String name)
static GestureLibrary fromRawResource(Context context, int resourceId)
All these methods return a class GestureLibrary. This class is used to read gestures entries from file, save gestures entries to file, recognize the gestures, etc. Once the GestureLibraries return a GestureLibrary class that corresponds to the file specified, we read all the gesture entries using GestureLibrary.load method.

Drawing and recognize a gesture

To draw and recognize gestures, we use the class GestureOverlayView. This view extends the FrameLayout, i.e. we can use it inside any other layout or use it as a parent layout to include other child views. This view acts as an overlay view and the user can draw gestures on it. This view uses three callback interfaces to report the actions performed, they are:

interface GestureOverlayView.OnGestureListener
interface GestureOverlayView.OnGesturePerformedListener
interface GestureOverlayView.OnGesturingListener
The GestureOverlayView.OnGestureListener callback interface is used to handle the gesture operations in low-level. This interface has following methods:

void onGestureStarted(GestureOverlayView overlay, MotionEvent event)
void onGesture(GestureOverlayView overlay, MotionEvent event)
void onGestureEnded(GestureOverlayView overlay, MotionEvent event)
void onGestureCancelled(GestureOverlayView overlay, MotionEvent event)

All these methods have two parameters GestureOverlayView and MotionEvent and represent the overlay view and the event that occurred.

The GestureOverlayView.OnGesturingListener callback interface is used to find when the gesture is started and ended. The interface has following methods:

void onGesturingStarted(GestureOverlayView overlay)
void onGesturingEnded(GestureOverlayView overlay)
The onGestuingStarted will be called when gesture action is started and onGesturingEnded will be called when the gesture action ended. Both these methods contain the GestureOverlayView that is used.

Most important is the GestureOverlayView.OnGesturePerformedListener interface. This interface has only one method:

void onGesturePerformed(GestureOverlayView overlay, Gesture gesture)
This method is called when the user performed the gesture and is processed by the GestureOverlayView. The first parameter is the overlay view that is used and the second is a class Gesture that represents the user performed gesture. Gesture class represents a hand drawn shape. This representation has one or more strokes; each stroke is a series of points. The GestureLibrary class uses this class to recognize gestures.

To recognize a gesture, we use GestureLibrary.recognize method. This method accepts a Gesture class. This method recognizes the gestures using internal recognizers and returns a list of predictions. The prediction is represented by Prediction class and contains two member variables name and score. The name variable represents the name of the gesture and score variable represents the score given by the gesture recognizer. This score member is used to choose the best matching prediction from the list. One of the common methods is to choose the first value that has score greater that one. Another method used is to choose the value that is inside a minimum and maximum threshold limit. Choosing this threshold limit is entirely depends on the implementation ranging from simple limits based on trial and error methods and more complex methods that may include leaning the user inputs and improve the recognition based on that.

Sample application

The sample application that accompanies this article includes 5 pre-defined gestures A, B, C, D and E. When the user draws these patterns the application lists the names and scores of all the predictions.

Example Loding Predifined Gesture From Raw folder :
----------------------------------------------------

GestureLibrary gesturesLibrery=GestureLibraries.fromRawResource(this, R.raw.gestures_name);

setting listener to Gesture :
-----------------------------


gesture.addOnGestureListener(this);


Checking Gesture :
==================


if (gesture.getGesture() != null) {
String str1 = recGesture(gesture.getGesture());
if(st1.equals("-1))
print gesture sucess
else

print gesture not foud
}


recognizing Gesture using Prediction Class :
---------------------------------------------
private String recGesture(Gesture gesture) {
ArrayList alPredictions = mGesLib.recognize(gesture);
if (alPredictions.size() > 0) {
Prediction pRecGes = alPredictions.get(0);
Log.e("recGesture true", pRecGes.name + alPredictions.toString());

// Toast.makeText(getApplicationContext(),pRecGes.name,Toast.LENGTH_SHORT).show();
return pRecGes.name;
} else {
Log.e("recGesture", "did not find");
// Toast.makeText(getApplicationContext(),"did not find"+alPredictions.size(),Toast.LENGTH_SHORT).show();
return "-1";
}
}


For Source Check here :


code from : krvarma

Hope this article helps you to understand complex gesture recognition in Android.