Tampilkan postingan dengan label Android. Tampilkan semua postingan
Tampilkan postingan dengan label Android. Tampilkan semua postingan

Selasa, 07 Februari 2012

Solve the “Debug certificate expired on” error message , Android Error: Error generating final archive: Debug certificate expired on

long ago i tried to run my running suddenly it showed error , but i didn't find any error in my source code in java & XML also ,


The problem comes from the fact that Android required the applications to be signed even in the debug mode. So it uses a keystore file called debug.keystore to providde keys for signing applications in debug mode. This key store file has a validity period by default 365 days from its creation date.


The First Solution:


Navigate to the .android folder in your home directory “~/.android” (Linux,Mac OS)
or c:\Documents and Settings\[User Name]\.android in windows XP
or C:\Users\.android in windows Vista or Windows 7, and delete debug.keystore file.


how to find .android folder in Linux ( UBuntu ) :

click on places menu under select home folder under then click on View Menu under click on showhiddenfiles (ctrl+h) , then u can find out .Android file


Then go to eclipse clean the project, this will create a new debug.keystore file with
default validity period 365 days.

The Second Solution:


Create a new default.keystore file with custom validity period (say 1000 days).
Navigate to the .android folder.
Delete the old default.keystore file.
We will use JDK Keytool.exe to generate the new key file. It is found in C:\Program Files\Java\jre6\bin in windows or inside the Java\jre6\bin folder in Mac OS or Linux.
Open the terminal app in Mac OS or Linux or the command prompt and navigate to keytool.exe directory.
Run the following command:
keytool -genkey -keypass android -keystore debug.keystore -alias androiddebugkey -storepass android -validity 1000 -dname “CN=Android Debug,O=Android,C=US”
This will generate a new default.keystore file with validity period 1000 days.
Copy the generated file to the .android folder, go to eclipse and clean projects and it should work.
The above command has the following options:
genkey: generates a key pair.
keystore : the name of the key store file.
alias : an alias for the key store. If the alias name is more than 8 characters the first 8 only are used.
storepass : the password for the key.
validity : the validity period for the key in days.
dname : A Distinguished Name that describes who created the key. The value is used as the issuer and subject fields in the self-signed certificate.

Senin, 21 November 2011

Print special symbols like " , / , \ . ..

Hi Every ody ,

I some case we have to print some special symbols like ' , " , / , like

that case simply add (forward slash ) \ before printing special symbol

Example :
-----------
here i want to print below message :

Hello " tutorials-Android " by sravan

then use
String str="Hello \" tutorials-Android \" by sravan";

Program :
-----------


public class Demo {
public static void main(String[] args) {
//String str="Hello\"hai\" wat dng";
String str="Hello \" tutorials-Android \" by sravan";
System.out.println(str);

}

}


out Put :
--------

Hello " tutorials-Android " by sravan

Senin, 14 November 2011

OutOfMemory exception when decoding with BitmapFactory





Google Android, Memory, and Bitmaps



Working on mobile devices forces one to make conscious decisions regarding coding choices, if for no other reason that resources are scarce (memory, screen size, bandwidth). Taking the easy route and ignoring wise mobile programming practices can take what could be a promising application and make it a disappointing user experience.



If you’ve spent any time with the Google Android SDK, and have tried to read a JPEG into a Bitmap using Media.getBitmap, you’ve almost certainly run into this little gem of an error message:



bitmap size exceeds VM budget



Unfortunately, since Android caps all applications’ VMs at 16MB in size, it only takes one or two big image reads to get you into trouble, regardless of all the garbage collection and Bitmap recycles you may try (see code snippet at the end of this post for more on that).



So, what’s a programmer to do?



Well, the only thing one can do is to read only what you need into memory. That means that you won’t be able to read in that 10MB jpeg sitting on your phone (at least, you won’t be able to read it reliably and / or repeatably) without trimming it down a bit.



The code below will do this for you; rather than calling Media.getBitmap, use this readBitmap function instead:











// Read bitmap

public Bitmap readBitmap(Uri selectedImage) {

Bitmap bm = null;

BitmapFactory.Options options = new BitmapFactory.Options();

options.inSampleSize = 5;

AssetFileDescriptor fileDescriptor =null;

try {

fileDescriptor = this.getContentResolver().openAssetFileDescriptor(selectedImage,”r”);

} catch (FileNotFoundException e) {

e.printStackTrace();

}

finally{

try {

bm = BitmapFactory.decodeFileDescriptor(fileDescriptor.getFileDescriptor(), null, options);

fileDescriptor.close();

} catch (IOException e) {

e.printStackTrace();

}

}

return bm;

}





The magic fairy dust in this function that allows you to trim down large bitmaps into digestible sizes is the options.inSampleSize property. inSampleSize – in this instance – takes a bitmap and reduces its height and width to 20% (1/5) of its original size. The larger the value of inSampleSize N (where N=5 in our example), the more the bitmap is reduced in size.



There’s also another coding practice that one should always use when dealing with Bitmaps in Android, and that is the use of the Bitmap recycle() method. The recycle() method frees up the memory associated with a bitmap’s pixels, and marks the bitmap as “dead”, meaning it will throw an exception if getPixels() or setPixels() is called, and will draw nothing.



In my projects, I have a helper function that does cleanup when I am finished using a Bitmap, named clearBitmap:



// Clear bitmap



public static void clearBitmap(Bitmap bm) {



bm.recycle();



System.gc();



}







Dealing with memory errors on Android apps seems to be the “problem child” issue that crops up the most (like too many threads on Blackberry apps – different post for a different day).



But like parenting a problem child, what’s called for is attention and intention to mitigate havoc wreaked.

Kamis, 10 November 2011

How to call Android contacts list?

Hi this is very import concept to Read Existing Contacts from Your Emulator or Device

There are three steps to this process.

1) Permissions

Add a permission to read contacts data to your application manifest.

 android:name="android.permission.READ_CONTACTS"/>

2) Calling the Contact Picker

Within your Activity, create an Intent that asks the system to find an Activity that can perform a PICK action from the items in the Contacts URI.

Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);

Call startActivityForResult, passing in this Intent (and a request code integer, PICK_CONTACTin this example). This will cause Android to launch an Activity that's registered to support ACTION_PICKon the People.CONTENT_URI, then return to this Activity when the selection is made (or canceled).

startActivityForResult(intent, PICK_CONTACT);

3) Listening for the Result

Also in your Activity, override the onActivityResult method to listen for the return from the 'select a contact' Activity you launched in step 2. You should check that the returned request code matches the value you're expecting, and that the result code is RESULT_OK.

You can get the URI of the selected contact by calling getData() on the data Intent parameter. To get the name of the selected contact you need to use that URI to create a new query and extract the name from the returned cursor.

@Override
public vo
id onActivityResult(int reqCode, int resultCode, Intent data) {
sup
er.onA


ctivityResult(reqCode, resultCode, data);

switch (reqCode) {
case (PICK_CONTACT) :
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor c = managedQuery(contactData, null, null, null, null);
if (c.moveToFirst()) {
String name = c.getString(c.getColumnIndexOrThrow(People.NAME));
// TODO Whatever you want to do with the selected contact name.
}
}
break;
}
}

Home Screen If No Contacts Contacts










For Online Training :

For Full Source Cliked Here

Selasa, 08 November 2011

Kamis, 29 September 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!

Rabu, 28 September 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.

Multi-touch in Android

The word “multitouch” gets thrown around quite a bit and it’s not always clear what people are referring to. For some it’s about hardware capability, for others it refers to specific gesture support in software. Whatever you decide to call it, today we’re going to look at how to make your apps and views behave nicely with multiple fingers on the screen.

This post is going to be heavy on code examples. It will cover creating a custom View that responds to touch events and allows the user to manipulate an object drawn within it. To get the most out of the examples you should be familiar with setting up an Activity and the basics of the Android UI system. Full project source will be linked at the end.

We’ll begin with a new View class that draws an object (our application icon) at a given position:

public class TouchExampleView extends View {
private Drawable mIcon;
private float mPosX;
private float mPosY;

private float mLastTouchX;
private float mLastTouchY;

public TouchExampleView(Context context) {
this(context, null, 0);
}

public TouchExampleView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}

public TouchExampleView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mIcon = context.getResources().getDrawable(R.drawable.icon);
mIcon.setBounds(0, 0, mIcon.getIntrinsicWidth(), mIcon.getIntrinsicHeight());
}

@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);

canvas.save();
canvas.translate(mPosX, mPosY);
mIcon.draw(canvas);
canvas.restore();
}

@Override
public boolean onTouchEvent(MotionEvent ev) {
// More to come here later...
return true;
}
}
MotionEvent

The Android framework’s primary point of access for touch data is the android.view.MotionEvent class. Passed to your views through the onTouchEvent and onInterceptTouchEvent methods, MotionEvent contains data about “pointers,” or active touch points on the device’s screen. Through a MotionEvent you can obtain X/Y coordinates as well as size and pressure for each pointer. MotionEvent.getAction() returns a value describing what kind of motion event occurred.

One of the more common uses of touch input is letting the user drag an object around the screen. We can accomplish this in our View class from above by implementing onTouchEvent as follows:

@Override
public boolean onTouchEvent(MotionEvent ev) {
final int action = ev.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN: {
final float x = ev.getX();
final float y = ev.getY();

// Remember where we started
mLastTouchX = x;
mLastTouchY = y;
break;
}

case MotionEvent.ACTION_MOVE: {
final float x = ev.getX();
final float y = ev.getY();

// Calculate the distance moved
final float dx = x - mLastTouchX;
final float dy = y - mLastTouchY;

// Move the object
mPosX += dx;
mPosY += dy;

// Remember this touch position for the next move event
mLastTouchX = x;
mLastTouchY = y;

// Invalidate to request a redraw
invalidate();
break;
}
}

return true;
}
The code above has a bug on devices that support multiple pointers. While dragging the image around the screen, place a second finger on the touchscreen then lift the first finger. The image jumps! What’s happening? We’re calculating the distance to move the object based on the last known position of the default pointer. When the first finger is lifted, the second finger becomes the default pointer and we have a large delta between pointer positions which our code dutifully applies to the object’s location.

If all you want is info about a single pointer’s location, the methods MotionEvent.getX() and MotionEvent.getY() are all you need. MotionEvent was extended in Android 2.0 (Eclair) to report data about multiple pointers and new actions were added to describe multitouch events. MotionEvent.getPointerCount() returns the number of active pointers. getX and getY now accept an index to specify which pointer’s data to retrieve.

Index vs. ID

At a higher level, touchscreen data from a snapshot in time may not be immediately useful since touch gestures involve motion over time spanning many motion events. A pointer index does not necessarily match up across complex events, it only indicates the data’s position within the MotionEvent. However this is not work that your app has to do itself. Each pointer also has an ID mapping that stays persistent across touch events. You can retrieve this ID for each pointer using MotionEvent.getPointerId(index) and find an index for a pointer ID using MotionEvent.findPointerIndex(id).

Feeling Better?

Let’s fix the example above by taking pointer IDs into account.

private static final int INVALID_POINTER_ID = -1;

// The ‘active pointer’ is the one currently moving our object.
private int mActivePointerId = INVALID_POINTER_ID;

// Existing code ...

@Override
public boolean onTouchEvent(MotionEvent ev) {
final int action = ev.getAction();
switch (action & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN: {
final float x = ev.getX();
final float y = ev.getY();

mLastTouchX = x;
mLastTouchY = y;

// Save the ID of this pointer
mActivePointerId = ev.getPointerId(0);
break;
}

case MotionEvent.ACTION_MOVE: {
// Find the index of the active pointer and fetch its position
final int pointerIndex = ev.findPointerIndex(mActivePointerId);
final float x = ev.getX(pointerIndex);
final float y = ev.getY(pointerIndex);

final float dx = x - mLastTouchX;
final float dy = y - mLastTouchY;

mPosX += dx;
mPosY += dy;

mLastTouchX = x;
mLastTouchY = y;

invalidate();
break;
}

case MotionEvent.ACTION_UP: {
mActivePointerId = INVALID_POINTER_ID;
break;
}

case MotionEvent.ACTION_CANCEL: {
mActivePointerId = INVALID_POINTER_ID;
break;
}

case MotionEvent.ACTION_POINTER_UP: {
// Extract the index of the pointer that left the touch sensor
final int pointerIndex = (action & MotionEvent.ACTION_POINTER_INDEX_MASK)
>> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
final int pointerId = ev.getPointerId(pointerIndex);
if (pointerId == mActivePointerId) {
// This was our active pointer going up. Choose a new
// active pointer and adjust accordingly.
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
mLastTouchX = ev.getX(newPointerIndex);
mLastTouchY = ev.getY(newPointerIndex);
mActivePointerId = ev.getPointerId(newPointerIndex);
}
break;
}
}

return true;
}
There are a few new elements at work here. We’re switching on action & MotionEvent.ACTION_MASK now rather than just action itself, and we’re using a new MotionEvent action constant, MotionEvent.ACTION_POINTER_UP. ACTION_POINTER_DOWN and ACTION_POINTER_UP are fired whenever a secondary pointer goes down or up. If there is already a pointer on the screen and a new one goes down, you will receive ACTION_POINTER_DOWN instead of ACTION_DOWN. If a pointer goes up but there is still at least one touching the screen, you will receive ACTION_POINTER_UP instead of ACTION_UP.

The ACTION_POINTER_DOWN and ACTION_POINTER_UP events encode extra information in the action value. ANDing it with MotionEvent.ACTION_MASK gives us the action constant while ANDing it with ACTION_POINTER_INDEX_MASK gives us the index of the pointer that went up or down. In the ACTION_POINTER_UP case our example extracts this index and ensures that our active pointer ID is not referring to a pointer that is no longer touching the screen. If it was, we select a different pointer to be active and save its current X and Y position. Since this saved position is used in the ACTION_MOVE case to calculate the distance to move the onscreen object, we will always calculate the distance to move using data from the correct pointer.

This is all the data that you need to process any sort of gesture your app may require. However dealing with this low-level data can be cumbersome when working with more complex gestures. Enter GestureDetectors.

GestureDetectors

Since apps can have vastly different needs, Android does not spend time cooking touch data into higher level events unless you specifically request it. GestureDetectors are small filter objects that consume MotionEvents and dispatch higher level gesture events to listeners specified during their construction. The Android framework provides two GestureDetectors out of the box, but you should also feel free to use them as examples for implementing your own if needed. GestureDetectors are a pattern, not a prepacked solution. They’re not just for complex gestures such as drawing a star while standing on your head, they can even make simple gestures like fling or double tap easier to work with.

android.view.GestureDetector generates gesture events for several common single-pointer gestures used by Android including scrolling, flinging, and long press. For Android 2.2 (Froyo) we’ve also added android.view.ScaleGestureDetector for processing the most commonly requested two-finger gesture: pinch zooming.

Gesture detectors follow the pattern of providing a method public boolean onTouchEvent(MotionEvent). This method, like its namesake in android.view.View, returns true if it handles the event and false if it does not. In the context of a gesture detector, a return value of true implies that there is an appropriate gesture currently in progress. GestureDetector and ScaleGestureDetector can be used together when you want a view to recognize multiple gestures.

To report detected gesture events, gesture detectors use listener objects passed to their constructors. ScaleGestureDetector uses ScaleGestureDetector.OnScaleGestureListener. ScaleGestureDetector.SimpleOnScaleGestureListener is offered as a helper class that you can extend if you don’t care about all of the reported events.

Since we are already supporting dragging in our example, let’s add support for scaling. The updated example code is shown below:

private ScaleGestureDetector mScaleDetector;
private float mScaleFactor = 1.f;

// Existing code ...

public TouchExampleView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mIcon = context.getResources().getDrawable(R.drawable.icon);
mIcon.setBounds(0, 0, mIcon.getIntrinsicWidth(), mIcon.getIntrinsicHeight());

// Create our ScaleGestureDetector
mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());
}

@Override
public boolean onTouchEvent(MotionEvent ev) {
// Let the ScaleGestureDetector inspect all events.
mScaleDetector.onTouchEvent(ev);

final int action = ev.getAction();
switch (action & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN: {
final float x = ev.getX();
final float y = ev.getY();

mLastTouchX = x;
mLastTouchY = y;
mActivePointerId = ev.getPointerId(0);
break;
}

case MotionEvent.ACTION_MOVE: {
final int pointerIndex = ev.findPointerIndex(mActivePointerId);
final float x = ev.getX(pointerIndex);
final float y = ev.getY(pointerIndex);

// Only move if the ScaleGestureDetector isn't processing a gesture.
if (!mScaleDetector.isInProgress()) {
final float dx = x - mLastTouchX;
final float dy = y - mLastTouchY;

mPosX += dx;
mPosY += dy;

invalidate();
}

mLastTouchX = x;
mLastTouchY = y;

break;
}

case MotionEvent.ACTION_UP: {
mActivePointerId = INVALID_POINTER_ID;
break;
}

case MotionEvent.ACTION_CANCEL: {
mActivePointerId = INVALID_POINTER_ID;
break;
}

case MotionEvent.ACTION_POINTER_UP: {
final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK)
>> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
final int pointerId = ev.getPointerId(pointerIndex);
if (pointerId == mActivePointerId) {
// This was our active pointer going up. Choose a new
// active pointer and adjust accordingly.
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
mLastTouchX = ev.getX(newPointerIndex);
mLastTouchY = ev.getY(newPointerIndex);
mActivePointerId = ev.getPointerId(newPointerIndex);
}
break;
}
}

return true;
}

@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);

canvas.save();
canvas.translate(mPosX, mPosY);
canvas.scale(mScaleFactor, mScaleFactor);
mIcon.draw(canvas);
canvas.restore();
}

private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
@Override
public boolean onScale(ScaleGestureDetector detector) {
mScaleFactor *= detector.getScaleFactor();

// Don't let the object get too small or too large.
mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 5.0f));

invalidate();
return true;
}
}
This example merely scratches the surface of what ScaleGestureDetector offers. The listener methods receive a reference to the detector itself as a parameter that can be queried for extended information about the gesture in progress. See the ScaleGestureDetector API documentation for more details.

Now our example app allows a user to drag with one finger, scale with two, and it correctly handles passing active pointer focus between fingers as they contact and leave the screen. You can download the final sample project at http://code.google.com/p/android-touchexample/. It requires the Android 2.2 SDK (API level 8) to build and a 2.2 (Froyo) powered device to run.

From Example to Application

In a real app you would want to tweak the details about how zooming behaves. When zooming, users will expect content to zoom about the focal point of the gesture as reported by ScaleGestureDetector.getFocusX() and getFocusY(). The specifics of this will vary depending on how your app represents and draws its content.

Different touchscreen hardware may have different capabilities; some panels may only support a single pointer, others may support two pointers but with position data unsuitable for complex gestures, and others may support precise positioning data for two pointers and beyond. You can query what type of touchscreen a device has at runtime using PackageManager.hasSystemFeature().

As you design your user interface keep in mind that people use their mobile devices in many different ways and not all Android devices are created equal. Some apps might be used one-handed, making multiple-finger gestures awkward. Some users prefer using directional pads or trackballs to navigate. Well-designed gesture support can put complex functionality at your users’ fingertips, but also consider designing alternate means of accessing application functionality that can coexist with gestures.

code by : developers blog

Senin, 01 Agustus 2011

Android Interview Questions And Answers



What is android?

Android is a stack of software for mobile devices which has Operating System, middleware and some key applications. The application executes within its own process and its own instance of Dalvik Virtual Machine. Many Virtual Machines run efficiently by a DVM device. DVM executes Java languages byte code which later transforms into .dex format files.



What is activity?

A single screen in
an application, with supporting Java code.



What is intent in Android?

A class (Intent) will describes what a caller desires to do. The caller will send this intent to Android's intent resolver, which finds the most suitable activity for the intent. E.g. opening
a PDF document is an intent, and the Adobe Reader apps will be the perfect activity for that intent(class).



What is a Sticky Intent?

sendStickyBroadcast() performs a sendBroadcast (Intent) known as sticky, i.e. the Intent you are sending stays around after the broadcast is complete, so that others can quickly retrieve that data through the return value of registerReceiver (BroadcastReceiver, IntentFilter). In all other ways, this behaves the same as sendBroadcast(Intent).

One example of a sticky broadcast sent via the operating system is ACTION_BATTERY_CHANGED. When you call registerReceiver() for that action -- even with a null BroadcastReceiver -- you get the Intent that was last broadcast for that action. Hence, you can use this to find the state of the battery without necessarily registering for all future state changes in the battery.

Is there anyway to determine if an Intent passed into a BroadcastReceiver's onReceive is the result of a sticky Boradcast Intent, or if it was just sent?



Example for sticky broadcast

When you call registerReceiver() for that action -- even with a null BroadcastReceiver -- you get the Intent that was last broadcast for that action. Hence, you can use this to find the state of the battery without necessarily registering for all future state changes in the battery.



How the nine-patch Image different from a regular bitmap? or Different between nine-patch Image vs regular Bitmap Image

It is one of a resizable bitmap resource which is being used as backgrounds or other images on the device. The NinePatch class allows drawing a bitmap in nine sections. The four corners are unscaled; the middle of the image is scaled in both axes, the four edges are scaled into one axis.



What Programming languages does Android support for application development?

Android applications supports using Java Programming Language. which is coded in Java and complied using Android SDK.



What is a resource?

A user defined JSON, XML, bitmap, or other file, injected into the application build process, which can later be loaded from code.



How will you record a phone call in Android? or How to handle on Audio Stream for a call in Android?

Permissions.PROCESS_OUTGOING_CALLS: Will Allows an application to monitor, modify, or abort outgoing calls. So through that we can monitor thePhone calls.



What's the difference between class, file and activity in android?

Class - The Class file is complied from .java file. Android will use this .class file to produce the executable apk.

File - It is a block of resources, srbitrary information. It can be any file type.

Activity - An activity is the equivalent of a Frame/Window in GUI toolkits. It is not a file or a file type it is just a class that can be extended in Android for loading UI elements on view.



Does Android support the Bluetooth serial port profile?

A. Yes.





Can an application be started on powerup?

A. Yes.



What is APK format.

The APK file is compressed AndroidManifest.xml file with extension .apk, Which have application code (.dex files), resource files, and other files which is compressed into single .apk file.



How to Translate in android

The Google translator translates the data of one language into another language by using XMPP to transmit data. You can type the message in English and select the language which is understood by the citizens of the country in order to reach the message to the citizens.



What is an action?

A description of something that an Intent sender desires.



What are the advantages of Android?

The following are the advantages of Android:



* The customer will be benefited from wide range of mobile applications to choose, since the monopoly of wireless carriers like Orange and AT&T will be broken by Google Android.

* Features like weather details, live RSS feeds, opening screen, icon on the opening screen can be customized

* Innovative products like the location-aware services, location of a nearbyconvenience store etc., are some of the additive facilities in Android.

What is the TTL (Time to Live)? Why is it required?

TTL is a value in data packet of Internet Protocol. It communicates to the network router whether or not the packet should be in the network for too long or discarded. Usually, data packets might not be transmitted to their intended destination within a stipulated period of time. The TTL value is set by a system default value which is an 8-bit binary digit field in the header of the packet. The purpose of TTL is, it would specify certain time limit in seconds, for transmitting the packet header. When the time is exhausted, the packet would be discarded. Each router receives the subtracts count, when the packet is discarded, and when it becomes zero, the router detects the discarded packets and sends a message, Internet Control Message Protocol message back to the originating host.





How is nine-patch image different from a regular bitmap?

It is a resizable bitmap resource that can be used for backgrounds or other images on the device. The NinePatch class permits drawing a bitmap in nine sections. The four corners are unscaled; the four edges are scaled in one axis, and the middle is scaled in both axes.





Explain IP datagram, Fragmentation and MTU ?

IP datagram can be used to describe a portion of IP data. Each IP datagram has set of fields arranged in an order. The order is specific which helps to decode and read the stream easily. IP datagram has fields like Version, header length, Type of service, Total length, checksum, flag, protocol, Time to live, Identification, source and destination ip address, padding, options and payload.

MTU:- Maximum Transmission Unit is the size of the largest packet that a communication protocol can pass. The size can be fixed by some standard or decided at the time of connection

Fragmentation is a process of breaking the IP packets into smaller pieces. Fragmentation is needed when the datagram is larger than the MTU. Each fragment becomes a datagram in itself and transmitted independently from source. When received by destination they are reassembled.





Explain about the exceptions of Android?

The following are the exceptions that are supported by Android

* InflateException : When an error conditions are occurred, this exception is thrown

* Surface.OutOfResourceException: When a surface is not created or resized, this exception is thrown

* SurfaceHolder.BadSurfaceTypeException: This exception is thrown from the lockCanvas() method, when invoked on a Surface whose is SURFACE_TYPE_PUSH_BUFFERS

* WindowManager.BadTokenException: This exception is thrown at the time of trying to add view an invalid WindowManager.LayoutParamstoken.





Describe Android Application Architecture?

Android Application Architecture has the following components:

* Services ? like Network Operation

* Intent - To perform inter-communication between activities or services

* Resource Externalization - such as strings and graphics

* Notification signaling users - light, sound, icon, notification, dialog etc.

  • Content Providers - They share data between applications

What are the advantages of Android?

The following are the advantages of Android:

* The customer will be benefited from wide range of mobile applications to choose, since the monopoly of wireless carriers like AT&T and Orange will be broken by Google Android.

* Features like weather details, live RSS feeds, opening screen, icon on the opening screen can be customized

  • Innovative products like the location-aware services, location of a nearbyconvenience store etc., are some of the additive facilities in Android.

How to select more than one option from list in android xml file? Give an example.

Specify android id, layout height and width as depicted in the following example.





Explain about the exceptions of Android?

The following are the exceptions that are supported by Android

* InflateException : When an error conditions are occurred, this exception is thrown

* Surface.OutOfResourceException: When a surface is not created or resized, this exception is thrown

* SurfaceHolder.BadSurfaceTypeException: This exception is thrown from the lockCanvas() method, when invoked on a Surface whose is SURFACE_TYPE_PUSH_BUFFERS

  • WindowManager.BadTokenException: This exception is thrown at the time of trying to add view an invalid WindowManager.LayoutParamstoken.

What are the features of Android?

*Components can be reused and replaced by the application framework.

*Optimized DVM for mobile devices

*SQLite enables to store the data in a structured manner.

*Supports GSM telephone and Bluetooth, WiFi, 3G and EDGE technologies

*The development is a combination of a device emulator, debugging tools, memory profiling and plug-in for Eclipse IDE.





What are the differences between a domain and a workgroup?

In a domain, one or more computer can be a server to manage the network. On the other hand in a workgroup all computers are peers having no control on each other. In a domain, user doesn?t need an account to logon on a specific computer if an account is available on the domain. In a work group user needs to have an account for every computer.

In a domain, Computers can be on different local networks. In a work group all computers needs to be a part of the same local network.









What is needed to make a multiple choice list with a custom view for each row?

Multiple choice list can be viewed by making the CheckBox android:id value be “@android:id /text1". That is the ID used by Android for the CheckedTextView in simple_list_item_multiple_choice.





What are the dialog boxes that are supported in android? Explain.

Android supports 4 dialog boxes:



AlertDialog : An alert dialog box supports 0 to 3 buttons and a list of selectable elements, including check boxes and radio buttons. Among the other dialog boxes, the most suggested dialog box is the alert dialog box.



ProgressDialog: This dialog box displays a progress wheel or a progress bar. It is an extension of AlertDialog and supports adding buttons.



DatePickerDialog: This dialog box is used for selecting a date by the user.



TimePickerDialog: This dialog box is used for selecting time by the user.





How to Remove Desktop icons and Widgets?

Press and Hold the icon or widget. The phone will vibrate and on the bottom of the phone you will see an option to remove. While still holding the icon or widget drag it to the remove button. Once remove turns red drop the item and it is gone





Common Tricky questions

  • Remember that the GUI layer doesn't request data directly from the web; data is always loaded from a local database.

  • The service layer periodically updates the local database.

  • What is the risk in blocking the Main thread when performing a lengthy operation such as web access or heavy computation? Application_Not_Responding exception will be thrown which will crash and restart the application.

  • Why is List View not recommended to have active components? Clicking on the active text box will pop up the software keyboard but this will resize the list, removing focus from the clicked element.





For senior employees

Beyond a certain level of experience, the job interview questions cease to be "difference between abstract class and interface", and focus more on testing your technical acumen, collaboration and communication skills. A list of such questions, typically asked during interviews for senior positions is given below:

  • Explain the life cycle of an application development process you worked on previously.

    What the interviewer looks for is communication of requirements, planning, modeling, construction and deployment on the back end.

  • Here's a hypothetical project. Explain how you would go about it.

    They want to know how you would break your work down into tasks and how many weeks for each task. I'm really looking to find out about planning methods, their skill set and how quickly they can execute.

  • How do you respond to requirement changes in the middle of a cycle?

  • What type of methodology have you used in the past? What are its drawbacks?

  • What are different techniques for prototyping an application?

    Similar question: Do you feel there is value in wireframing an application? Why?

  • How do you manage conflicts in Web applications when there are different people managing data?

  • Tell me something you learned from a team member in the last year.

  • What software testing procedures have you used to perform a QA?

Once the coding skills verified. Sample I

· The Activity life cycle is must. Ask about the different phases of Activity Life cycle. For example: when and how the activity comes to foreground?

· Check the knowledge on AndroidManifest file, For example: Why do we need this file, What is the role of this file in Android app development.

· Different Kinds of Intents

· Ask about different Kinds of context

· Ask about different Storage Methods in android

· Kinds of Log debugger and Debugger Configuration

· How to debug the application on real device.

· How do you ensure that the app design will be consistent across the different screen resolutions

· Thread concepts also plus points as we deal with the treads more.

· Can you able to build custom views and how?

· How to create flexible layouts, For example to place English, Chinese fonts.

· What is localization and how to achieve?

· What are 9-patch images

· How to avoid ANR status

· How to do Memory management

· Ask about IPC

· What is onCreate(Bundle savedInstanceState), Have you used savedInstanceState when and why?

· To check how updated the person is just ask about what are Fragments in an Activity





If this is an Android specific job, just ask the obvious stuff. Sample II

  • Application lifecycle

  • When to use a service

  • How to use a broadcast receiver and register it both in the manifest and in code

  • Intent filters

  • Stuff about what manifest attributes and tags mean

  • The types of flags to run an application

    • FLAG_ACTIVITY_NEW_TASK

    • FLAG_ACTIVITY_CLEAR_TOP

    • etc

  • How to do data intensive calculations using threads

  • Passing large objects (that can't be passed via intents and shouldn't be serialized) via a service

  • Binding to a service and the service lifecycle

  • How to persist data (both savedInstanceState and more permanent ways)

Just go through http://developer.android.com/guide/topics/fundamentals.html and see what sounds like it's important. Hopefully you're an android developer and know what all those things are, otherwise you're just waiting your interviewee's time =P

But like @Mayra said. A lot of android can be picked up fairly quickly if they're experienced programmers. If you just ask android specific questions, you'll get people who started off with android and that could be bad.



.apk extension
The extension for an Android package file, which typically contains all of the files related to a single Android application. The file itself is a compressed collection of an AndroidManifest.xml file, application code (.dex files), resource files, and other files. A project is compiled into a single .apk file.
.dex extension
Android programs are compiled into .dex (Dalvik Executable) files, which are in turn zipped into a single .apk file on the device. .dex files can be created by automatically translating compiled applications written in the Java programming language.
Action
A description of something that an Intent sender wants done. An action is a string value assigned to an Intent. Action strings can be defined by Android or by a third-party developer. For example, android.intent.action.VIEW for a Web URL, or com.example.rumbler.SHAKE_PHONE for a custom application to vibrate the phone.


adb
Android Debug Bridge, a command-line debugging application shipped with the SDK. It provides tools to browse the device, copy tools on the device, and forward ports for debugging. See Using adb for more information.


Application
A collection of one or more activities, services, listeners, and intent receivers. An application has a single manifest, and is compiled into a single .apk file on the device.


Content Provider
A class built on ContentProvider that handles content query strings of a specific format to return data in a specific format. See Reading and writing data to a content provider for information on using content providers.
Content URI
A type of URI. See the URI entry.
Dalvik
The name of Android’s virtual machine. The Dalvik VM is an interpreter-only virtual machine that executes files in the Dalvik Executable (.dex) format, a format that is optimized for efficient storage and memory-mappable execution. The virtual machine is register-based, and it can run classes compiled by a Java language compiler that have been transformed into its native format using the included “dx” tool. The VM runs on top of Posix-compliant operating systems, which it relies on for underlying functionality (such as threading and low level memory management). The Dalvik core class library is intended to provide a familiar development base for those used to programming with Java Standard Edition, but it is geared specifically to the needs of a small mobile device.
DDMS
Dalvik Debug Monitor Service, a GUI debugging application shipped with the SDK. It provides screen capture, log dump, and process examination capabilities. See Using the Dalvik Debug Monitor Server to learn more about this program.
Drawable
A compiled visual resource that can be used as a background, title, or other part of the screen. It is compiled into an android.graphics.drawable subclass.
Intent
A class (Intent) that contains several fields describing what a caller would like to do. The caller sends this intent to Android’s intent resolver, which looks through the intent filters of all applications to find the activity most suited to handle this intent. Intent fields include the desired action, a category, a data string, the MIME type of the data, a handling class, and other restrictions.
Intent Filter
Activities and intent receivers include one or more filters in their manifest to describe what kinds of intents or messages they can handle or want to receive. An intent filter lists a set of requirements, such as data type, action requested, and URI format, that the Intent or message must fulfill. For Activities, Android searches for the Activity with the most closely matching valid match between the Intent and the activity filter. For messages, Android will forward a message to all receivers with matching intent filters.
Intent Receiver
An application class that listens for messages broadcast by callingContext.broadcastIntent(). For example code, see Listening for and broadcasting global messages.


Layout resource
An XML file that describes the layout of an Activity screen.
Manifest
An XML file associated with each Application that describes the various activies, intent filters, services, and other items that it exposes. See AndroidManifest.xml File Details.


Nine-patch / 9-patch / Ninepatch image
A resizeable bitmap resource that can be used for backgrounds or other images on the device. See Nine-Patch Stretchable Image for more information.
Query String
A type of URI. See the URI entry.
Resource
A user-supplied XML, bitmap, or other file, entered into an application build process, which can later be loaded from code. Android can accept resources of many types; see Resources for a full description. Application-defined resources should be stored in theres/ subfolders.
Service
A class that runs in the background to perform various persistent actions, such as playing music or monitoring network activity.
Theme
A set of properties (text size, background color, and so on) bundled together to define various default display settings. Android provides a few standard themes, listed in R.style (starting with “Theme_”).
URIs
Android uses URI strings both for requesting data (e.g., a list of contacts) and for requesting actions (e.g., opening a Web page in a browser). Both are valid URI strings, but have different values. All requests for data must start with the string “content://”. Action strings are valid URIs that can be handled appropriately by applications on the device; for example, a URI starting with “http://” will be handled by the browser

Q: Can I write code for Android using C/C++?

A:

Android applications are written using the Java programming language.

Android includes a set of core libraries that provides most of the functionality available in the core libraries of the Java programming language.

Every Android application runs in its own process, with its own instance of the Dalvik virtual machine. Dalvik has been written so that a device can run multiple VMs efficiently. The Dalvik VM executes files in the Dalvik Executable (.dex) format which is optimized for minimal memory footprint. The VM is register-based, and runs classes compiled by a Java language compiler that have been transformed into the .dex format by the included “dx” tool.

Android only supports applications written using the Java programming language at this time.