Sunday, June 27, 2010

Showing Route through Google Map in Android

To show the route between two places in google map, we can use

"http://maps.google.com/maps?&saddr=13.042206,80.17000&daddr=9.580000,78.100000"

this url.

Here I used the latitude and longitude of Chennai and Madurai, two cities in India.

The complete code snippet is,

 

public class LaunchMap extends MapActivity {

Uri uri;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uri =Uri.parse("http://maps.google.com/maps?&saddr=13.042206,80.17000&daddr=9.580000,78.100000");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
finish();
}

@Override
protected boolean isRouteDisplayed() {
return false;
}
}



For showing this, we need to include the google map library in Manifest file.

A the time of launching , a pop up will ask to open in Browser or Google maps, just click on google map and it will show a list displaying the step by step direction as,



If we click on the list item it will show the map as,

Friday, June 25, 2010

Live Audio streaming using MediaPlayer in Android

Live Audio streaming in android, from 1.6 sdk onwards is become so easy. In setDataSource() API directly pass the url and audio will play without any issues.

The complete code snippet is,


 
public class AudioStream extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String url = "http://www.songblasts.com/songs/hindi/t/three-idiots/01-Aal_Izz_Well-(SongsBlasts.Com).mp3";
MediaPlayer mp = new MediaPlayer();
try {
mp.setDataSource(url);
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.prepare();
mp.start();
} catch (Exception e) {
Log.i("Exception", "Exception in streaming mediaplayer e = " + e);
}
}
}


The Url I used here is a song from a bollywood film 3 Idiots.


Happy Coding

Creating SDCard and using it in emulator

The command for creating sdcard is

mksdcard 16M image.iso

Here we created a sdcard of name "image" with 16MB of size.

For using the sdcard in emulator, give this command

-sdcard /image.iso

in "Additional Emulator Command Line Options"

Wednesday, June 23, 2010

INSTALL_PARSE_FAILED_NO_CERTIFICATES in Android

Today, when I am doing a project in Android, suddenly I got this error. Actually, when I got this error is, after putting a png file in drawable called "close_btn_nmb". After putting this png file and try to run, I got tINSTALL_PARSE_FAILED_NO_CERTIFICATES error in 1.6 SDK. After some googling, I just renamed the file as, "close_btnnmb" and it worked fine. At that time, I came to know about Issue-830

So, when giving name to drawable files, try to avoid, two underscores. This is not a hard core rule, just my insight.

File Browser in Andriod

File browser in android is used to access the internal file system in Android. Through the file browser, we can browse through the files. The features are

- sorting,
- size of the file
- an icon to recognize the file or directory
- open the file, if permission is there.

Then a Home button, to come to the root directory, SDcard button, to show sdcard files. A back button is always there, if the parent directory is not null.

For opening the file, there is function, I created called openFile(), in that, according to the extension of the file, I am setting the MIME type for intent using the API called setDataAndType(). The android file system contains lot of file types like audio, video, text, (text itself contain html, php, xml, csv etc).

Another important method(API), is listFiles(). This will return an array of files and this array, we are passing to the fill() in the FileBrowser class. We will check a file is a directory or not using isDirectory()


The code for openFile() which is an very important function in the fileBrowser application and can be used in several applications is,


 

private void openFile(File aFile) {
Log.i("openFile()", "openFile()");
String type = "";
String extension = "";
try {
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
Uri data = Uri.parse("file://" + aFile.getAbsolutePath());
int dot = aFile.getName().lastIndexOf(".");
extension = aFile.getName().substring(dot);
type = extension.toLowerCase();
// audio-types
if (type.equals(".ogg"))
type = "audio/x-ogg";
if (type.equals(".mp3"))
type = "audio/mp3";
if (type.equals(".wav"))
type = "audio/wav";
if (type.equals(".mid"))
type = "audio/mid";
if (type.equals(".midi"))
type = "audio/midi";
if (type.equals(".amr"))
type = "audio/AMR";
// video-types
if (type.equals(".mpeg"))
type = "video/mpeg";
if (type.equals("..3gp"))
type = "video/3gpp";
// package-types
if (type.equals(".jar"))
type = "application/java-archive";
if (type.equals(".zip"))
type = "application/zip";
if (type.equals(".rar"))
type = "application/x-rar-compressed";
if (type.equals(".gz"))
type = "application/gzip";
// android-specific
if (type.equals(".apk"))
type = "application/vnd.android.package-archive";
// web browser-types
if (type.equals(".htm"))
type = "text/html";
if (type.equals(".html"))
type = "text/html";
if (type.equals(".php"))
type = "text/php";
// text-types
if (type.equals(".txt"))
type = "text/plain";
if (type.equals(".csv"))
type = "text/csv";
if (type.equals(".xml"))
type = "text/";
// image-types
if (type.equals(".png"))
type = "image/png";
if (type.equals(".gif"))
type = "image/gif";
if (type.equals(".jpg"))
type = "image/jpg";
if (type.equals(".jpeg"))
type = "image/jpeg";
if (type.equals(".bmp"))
type = "image/bmp";

intent.setDataAndType(data, type);
startActivity(intent);
} catch (Exception e) {
Toast.makeText(this, "Protected, File can't open",
Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}


The complete code snippet is,

 
public class FileBrowser extends ListActivity {

private enum DISPLAYMODE {
ABSOLUTE, RELATIVE;
}

static boolean SORT_NAME = false;
static boolean SMALL_ICON = false;
private final DISPLAYMODE displayMode = DISPLAYMODE.RELATIVE;
private static List directoryEntries = new ArrayList();
private File currentDirectory = new File("");
private TextView fullPath;
private File[] filesToFill = null;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fileui);
fullPath = (TextView) findViewById(R.id.path);
findViewById(R.id.home).setOnClickListener(new OnClickListener() {

public void onClick(View view) {
Log.i("onClick, HomeButton", "onClick, HomeButton");
browseToRoot();
}
});
findViewById(R.id.sdcard).setOnClickListener(new OnClickListener() {


public void onClick(View view) {
browseTo(new File("/sdcard"));
}

});
browseToRoot();
}

private void browseToRoot() {
browseTo(new File("/"));
}

private void upOneLevel() {
if (this.currentDirectory.getParent() != null) {
this.browseTo(this.currentDirectory.getParentFile());
} else {
Toast.makeText(this, "FileBrowser can't go Up", Toast.LENGTH_SHORT)
.show();
}
}

private void browseTo(final File aDirectory) {

if (this.displayMode == DISPLAYMODE.RELATIVE) {
Log.i("browseTo(), DISPLAYMODE_RELATIVE, absPath : "
+ aDirectory.getAbsolutePath(), "DISPLAYMODE_RELATIVE : ");
fullPath.setText("CurrentPath :" + aDirectory.getAbsolutePath());
}
if (aDirectory.isDirectory()) {
Log.i("browseTo(), isDir() == true", "browseTo(), isDir() == true");
this.currentDirectory = aDirectory;
fill(aDirectory.listFiles());
} else {
Log.i("browseTo(), isDir() != true", "browseTo(), isDir() != true");
openFile(aDirectory);
}
}

private void openFile(File aFile) {
Log.i("openFile()", "openFile()");
String type = "";
String extension = "";
try {
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
Uri data = Uri.parse("file://" + aFile.getAbsolutePath());
int dot = aFile.getName().lastIndexOf(".");
extension = aFile.getName().substring(dot);
type = extension.toLowerCase();
// audio-types
if (type.equals(".ogg"))
type = "audio/x-ogg";
if (type.equals(".mp3"))
type = "audio/mp3";
if (type.equals(".wav"))
type = "audio/wav";
if (type.equals(".mid"))
type = "audio/mid";
if (type.equals(".midi"))
type = "audio/midi";
if (type.equals(".amr"))
type = "audio/AMR";
// video-types
if (type.equals(".mpeg"))
type = "video/mpeg";
if (type.equals("..3gp"))
type = "video/3gpp";
// package-types
if (type.equals(".jar"))
type = "application/java-archive";
if (type.equals(".zip"))
type = "application/zip";
if (type.equals(".rar"))
type = "application/x-rar-compressed";
if (type.equals(".gz"))
type = "application/gzip";
// android-specific
if (type.equals(".apk"))
type = "application/vnd.android.package-archive";
// web browser-types
if (type.equals(".htm"))
type = "text/html";
if (type.equals(".html"))
type = "text/html";
if (type.equals(".php"))
type = "text/php";
// text-types
if (type.equals(".txt"))
type = "text/plain";
if (type.equals(".csv"))
type = "text/csv";
if (type.equals(".xml"))
type = "text/";
// image-types
if (type.equals(".png"))
type = "image/png";
if (type.equals(".gif"))
type = "image/gif";
if (type.equals(".jpg"))
type = "image/jpg";
if (type.equals(".jpeg"))
type = "image/jpeg";
if (type.equals(".bmp"))
type = "image/bmp";

intent.setDataAndType(data, type);
startActivity(intent);
} catch (Exception e) {
Toast.makeText(this, "Protected, File can't open",
Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}

private void fill(File[] files) {
Log.i("in fill(), from browseTo()", "in fill(), from browseTo()");
FileBrowser.directoryEntries.clear();
filesToFill = files;

if (this.currentDirectory.getParent() != null) {
FileBrowser.directoryEntries.add(new IconifiedText("Back",
getResources().getDrawable(R.drawable.ic_menu_back_small)));
}
Drawable currentIcon = null;
for (File currentFile : files) {
String fileName = "";
Log.i("currentFile : Length :" + currentFile.length() + "Bytes",
"Size of currentFile");
if (currentFile.isDirectory()) {
currentIcon = getResources().getDrawable(R.drawable.folder3);
} else {
// String fileName = currentFile.getName();
// if (checkEndsWithInStringArray(fileName, getResources()
// .getStringArray(R.array.fileEndingImage))) {
// // currentIcon =
// // getResources().getDrawable(R.drawable.image);
// } else if (checkEndsWithInStringArray(fileName,
currentIcon = getResources().getDrawable(R.drawable.file);

}
switch (this.displayMode) {
case ABSOLUTE:
/* On absolute Mode, we show the full path */
FileBrowser.directoryEntries.add(new IconifiedText(currentFile
.getPath(), currentIcon));
break;
case RELATIVE:
int currentPathStringLength = this.currentDirectory.getPath()
.length();
fileName = currentFile.getAbsolutePath().substring(
currentPathStringLength);
Log.i("else part :" + fileName, "else part");
break;
}

if (FileBrowser.SMALL_ICON) {
if (currentFile.isDirectory())
currentIcon = getResources().getDrawable(R.drawable.folder);
else
currentIcon = getResources()
.getDrawable(R.drawable.webtext);
}
FileBrowser.directoryEntries.add(new IconifiedText(fileName,
currentIcon));

}

if (FileBrowser.SORT_NAME) {
Collections.sort(FileBrowser.directoryEntries);
}
IconifiedTextListAdapter itla = new IconifiedTextListAdapter(this);
itla.setListItems(FileBrowser.directoryEntries);
this.setListAdapter(itla);
}


@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String selectedFileString = FileBrowser.directoryEntries.get(position)
.getText();
Log.i("selectedItem : " + selectedFileString, "onListItemClick()");
if (selectedFileString.equals("Home")) {
// Refresh
// this.browseTo(this.currentDirectory);
browseToRoot();
} else if (selectedFileString.equals("Back")) {
this.upOneLevel();
} else if (selectedFileString.equals("data")) {
this.browseTo(new File("/data/misc/"));
} else {
File clickedFile = null;
switch (this.displayMode) {
case RELATIVE:
clickedFile = new File(this.currentDirectory.getAbsolutePath()
+ FileBrowser.directoryEntries.get(position).getText());
break;
case ABSOLUTE:
clickedFile = new File(FileBrowser.directoryEntries.get(
position).getText());
Log.i("ABSOLUTE", "ABSOLUTE");
break;
}
if (clickedFile != null) {
this.browseTo(clickedFile);
}
}
}



This itself is not complete, other class like IconifiedText, Adapter class , xml files are there.

The screenshots are,



Sunday, June 20, 2010

Launching Google Map using Intent in Android

Using intent we can open google map. The URI for launching google map is geo:13.042206,80.17000?z=10

The complete code snippet is,

 

double latitude = 13.042206;
double longitude = 80.17000;
uri = Uri.parse("geo:" + latitude + "," + longitude +"?z=10");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);


The latitude and longitude , I specified here is for Chennai. We can also specify the zoom level. Here I specified the zoom level as 10.

The screenshot is,



From the menu you will get all the options that are available in google map as,

Vibration in Android

The code snippet for vibrating android phone is,

 
Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(2000);


Here 2000 is 2000 milliseconds, the phone will vibrate. And of course you can't test this in emulator, you need a real device to test this.

Opening an Application using Intent

In Android, if we know the package name and the activity which is launching the application, we can open or launch the application from anywhere using Intent.

The code snippet is,

 
Intent intent = new Intent("android.intent.action.MAIN");
ComponentName component = new ComponentName("com.sample", "com.sample.Sample");
intent.setComponent(component );
startActivity(intent);

Tuesday, June 15, 2010

Manufacturer Name and phone model in Android

To get the manufacturer name and other details about the android phone, we can use the class called android.os.Build
 
To get the manufacturer name use, Build.MANUFACTURER
To get the phone model use, Build.MODEL

Friday, June 4, 2010

Accelerometer Sensor in Android

Android phones has lot of sensors. In this, I am showing you the how accelerometer sensor works. Accelerometer will show you thew x, y and z co-ordinates of your phone movement. Actually, this sensor, we used in one of our application. In that, when shake the phone horizontally, doing some action. So like this, you can also do according to the values you get from the onSensorChanged() in SensorEventListener interface.

The complete code is,

AndAccelorometer.java
 

public class AndAccelorometer extends Activity implements SensorEventListener {

SensorManager sMgr;
Sensor accelrometerSensor;
 
@Override
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); sMgr = (SensorManager) getSystemService(Context.SENSOR_SERVICE); accelrometerSensor = sMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sMgr.registerListener(this, accelrometerSensor, SensorManager.SENSOR_DELAY_UI); } public void onAccuracyChanged(Sensor sensor, int accuracy) { // TODO Auto-generated method stub } public void onSensorChanged(SensorEvent event) { // TODO Auto-generated method stub float[] sensorValues = event.values; if (event.sensor == accelrometerSensor) Toast.makeText(AndAccelorometer.this, "X = " + sensorValues[0] + " Y = " + sensorValues[1] + " Z = " + sensorValues[2], Toast.LENGTH_SHORT).show(); } }

Opening Camera from Application

The basic things for augmented reality are camera, Sensor to know the direction, and the GPS or network provider to get the current location details. Gradually, I will show you the Augmented Reality in Android. In this, showing you how to open a camera from application.

CameraPreview.java


 
class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {

SurfaceHolder holder;
Camera camera;

public CameraPreview(Context context) {
super(context);
holder = getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}

@Override
public void surfaceChanged(SurfaceHolder holder2, int format, int w,
int h) {
Camera.Parameters parameters = camera.getParameters();
parameters.setPreviewSize(w, h);
camera.setParameters(parameters);
camera.startPreview();
}

@Override
public void surfaceCreated(SurfaceHolder holder1) {
try {
camera = Camera.open();
camera.setPreviewDisplay(holder1);
} catch (Exception e) {
Log.i("Exception surfaceCreated()", "e = " + e);
camera.release();
camera = null;
}

}

@Override
public void surfaceDestroyed(SurfaceHolder arg0) {
camera.stopPreview();
camera.release();
camera = null;
}
}



Create an object of CameraPreview and using setContentView(), just display the camera

OpenCamera.java

 
public class OpenCamera extends Activity {

CameraPreview preview;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Hide the window title.
requestWindowFeature(Window.FEATURE_NO_TITLE);
preview = new CameraPreview(this);
setContentView(preview);
}
}


And ofcourse, the permission is needed,


<uses-permission android:name="android.permission.CAMERA"/>

Thursday, June 3, 2010

HTTP 100 Conitnue Error in Android

When I am doing a project in Android suddenly, I got this error "HTTP 100 conitnue" when sending request to server and I am not getting the proper response from the server. After some googling, I came to know about one API, and I want to share with all about that. It is setUseExpectContinue()

The complete code snippet is,


HttpProtocolParams.setUseExpectContinue(client.getParams(), false);

Here, client is an object of "HttpClient"

After using this code snippet, I got proper response from server and all work fine.

Happy Coding

Androidians