Android Device Bottom Key Panel Management Programatically

There are various Android Application where we need to control the android bottom key panel. This bottom key panel is organised by five keys

1. Back
2. Menu
3. Home
4. Search
5. Settings

If we take any example like online payment Application then we can’t allow a user to press the back button in the middle of payment. So we have to override the back press event and managed the click event.

There are many cases where we provide certain action of the application like action bar menu will be appeared when menu button user will pressed.

This key panel button events are identified by android in following ways

1. Back – KEYCODE_BACK
2. Menu -KEYCODE_MENU
3. Home – KEYCODE_HOME
4. Search – KEYCODE_SEARCH
5. Settings – KEYCODE_SETTINGS

For handling this keys we need to override this method of the Activity

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {

if (keyCode == KeyEvent.KEYCODE_BACK) {
//Do Code Here
// If want to block just return false
return false;
}
if (keyCode == KeyEvent.KEYCODE_MENU) {
//Do Code Here
// If want to block just return false
return false;
}
if (keyCode == KeyEvent.KEYCODE_HOME) {
//Do Code Here
// If want to block just return false
return false;
}
if (keyCode == KeyEvent.KEYCODE_SEARCH) {
//Do Code Here
// If want to block just return false
return false;
}
if (keyCode == KeyEvent.KEYCODE_SETTINGS) {
//Do Code Here
// If want to block just return false
return false;
}

return super.onKeyDown(keyCode, event);
}

From Android 4.0 (ICS) onward KEYCODE_HOME has been deprecated. As Android believed that it is wrong to give all the option blocked for user. User can pressed the Home button to navigate to other application. But android keep the current application as it is state in the background. So that user can back to the previous application.

There are another instance user can accidentally press back button and exit the application. In that case we have to give alert to the user before quit the application. For that we need to identify for the last activity in the stack. For that we need to identify and checked for the last activity form the stack.

private boolean isLastActivity() {
final ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
final List tasksInfo = am.getRunningTasks(1024);

final String ourAppPackageName = getPackageName();
RunningTaskInfo taskInfo;
final int size = tasksInfo.size();
for (int i = 0; i < size; i++) {
taskInfo = tasksInfo.get(i);
if (ourAppPackageName
.equals(taskInfo.baseActivity.getPackageName())) {
return taskInfo.numActivities == 1;
}
}
return false;
}

So we can use this android device bottom key panel to Application short key.

Android : Alert dialog with single choice item selection implementation

Android dialog is a small window that prompts the user to make a decision or enter additional information. Android dialog does not fill the screen and is normally used for modal events that require users to take an action before they can proceed.

Android dialog is very useful for adding a persistent single choice list in the activity. It help the user to select the alternative choice just like web page. It is one of useful features as regards to iOS. iOS not provide this type of controls.

Here is the explicit code for this type of android dialog

public Dialog onCreateDialogSingleChoice() {

//Initialize the Alert Dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
//Source of the data in the DIalog
CharSequence[] array = {“High”, “Medium”, “Low”};

// Set the dialog title
builder.setTitle(“Select Priority”)
// Specify the list array, the items to be selected by default (null for none),
// and the listener through which to receive callbacks when items are selected
.setSingleChoiceItems(array, 1, new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub

}
})

// Set the action buttons
.setPositiveButton(“Ok”, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
// User clicked OK, so save the result somewhere
// or return them to the component that opened the dialog

}
})
.setNegativeButton(“Cancel”, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {

}
});

return builder.create();
}

Call this function from any where of the activity through this way.

Dialog dialog = onCreateDialogSingleChoice();
dialog.show();
Alert dialog with single choice item selection implementation

Android : How to read files from the android project structure dynamicaly

There are many times in our Android Application we need to read flat file or xml file that contain certain information of the application. We can not put these files in just any where of the android project structure because in every thing are identified by an ID in the android application and it is access through the R.java file runtime.So there is specific folder where we have to put these files and that place is “raw” in the “res” folder structure in the android project structure.

There is the sample code how to read a file. here I take an example of XMl file. Lets say file name is test.xml and package name is com.example.android.

// initialize the storing string in order to avoid getting garbage value
String xmlString = null;

// Write the code in try catch block in order to get better error handling and it does not cause unexpected application cause
try {

// getting the resource id which is generated by android application
int rID = getResources().getIdentifier(“test”, “raw”,”com.example.android”);

//Reading through the Input stream from file
InputStream iS = getResources().openRawResource(rID);
// Storing for buffering
byte[] buffer;
buffer = new byte[iS.available()];
iS.read(buffer);

//Redirecting to the Output Stream
ByteArrayOutputStream oS = new ByteArrayOutputStream();
oS.write(buffer);

// Close the Input and output stream
oS.close();
iS.close();

// Transfer to native String in order to doen programming operation
xmlString = oS.toString();
System.out.println(xmlString);

} catch (IOException e) {

e.printStackTrace();
}

Android: Playing Audio File In Background Of An Activity

There are many time in an application we need to play the music audio file in background. For this problem after googling I found many way, but most them are very much complex.After done of certain R & D I found this is the easiest way in the android to play the music file as a background in an activity.This is the way.

1.Put your music file in the asset folder in the android project structure.
2.Import android.media.MediaPlayer in your activity.
3.Code these lines in OnCraete() method of an Activity

MediaPlayer player;
AssetFileDescriptor afd;
try {
// Read the music file from the asset folder
afd = getAssets().openFd(“home.mp3”);
// Creation of new media player;
player = new MediaPlayer();
// Set the player music source.
player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(),afd.getLength());
// Set the looping and play the music.
player.setLooping(true);
player.prepare();
player.start();
} catch (IOException e) {
e.printStackTrace();
}
## Always use try catch block two avoid error exception.

If an activity is pause, say out of user visibility you have call this in order to avoid collision of other sound of other activity
public void onPause() {
super.onPause();
player.pause();
}

To resume this player we have to call following method.
public void onResume() {
super.onResume();
player.start();
}

When activity is going to stop we have to call this to release the media player
protected void onStop() {
super.onStop();
player.stop();
player = null;
}

For more resource about this topic go to android developer community.

Android UI element update – with timer implementation

Todays technological development is based on the mainly dynamic development from web to mobile development. In web development we can achieve the continuous update a page by using Ajax technology, but if we want to continuous update of screens on basis of data received from various web service in mobile development it quite complex. This is the point we need the Timer logic. Basically Timer is one of the most important logical component of the mobile app development in both Android and iOs.

In iOs Timer implementation is quite simple , Just declare a NSTimer object , then schedule the timer with selector and regular time interval.iOs framework is basically work on the Objective-C which is a sub set of native C language.So in iOS Timer concept is quite simple.

But for Android it throughly based on the Java language. So It inherit the java Timer concept. As per java timer concept we have to declare the timer object and for schedule the timer we have to declare a java class java.util.TimerTask object.This is create a separate thread in which run method continuous data is retrieved and update the GUI.

Here is the implementation.

//Android UI element declaration
TextView T=(TextView)findViewById(R.id.txtView);
// Timer object creation and Staring;
final Timer timer = new Timer();
// Timer task creation which will be executed on timer schedule
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
if(counter<=5)
counter++;
//Android UI get Updated continouly
t.setText("The counter is " + counter);

} else {
// If condition full filled the timer will stop here
timer.cancel();
timer.purge();
}

}
};
// Timer will schedule with task and periodical time interval.
timer.schedule(timerTask, 5000, 5000);

This is the logical implementation of the Java timer, but this is give an error when it trying to update the Android UI component , because Android can’t give the permission to update the UI element from any other thread . If we need to update the UI element we have to do it through the UI main thread.here is another way to update the GUI element . It is Handler .The main use of this is to schedule messages and runnables to be executed as some point in the future; and to enqueue an action to be performed on a different thread than your own. which help us to update the GUI element.. here is the implementation.

//Handler object declaration
final Handler h = new Handler();
//Android UI element declaration
TextView T=(TextView)findViewById(R.id.txtView);
// Timer object creation and Staring;
final Timer timer = new Timer();
// Timer task creation which will be executed on timer schedule
TimerTask timerTask = new TimerTask() {
@Override
public void run() {

h.post(new Runnable() {

public void run() {
// Do something

if(counter<=5)
counter++;
//Android UI get Updated continually
t.setText("The counter is " + counter);

} else {
// If condition full filled the timer will stop here
timer.cancel();
timer.purge();
}

}
});

}
};
// Timer will schedule with task and periodical time interval.
timer.schedule(timerTask, 5000, 5000);

This is all about android timer illustration.