Custom widgets

August 25th, 2009 No comments

(Android phone – how-to/example)

If you consider doing your own custom widgets, you must start by creating a new class, that extends android.view.View

The simplest example is customizing a bit the screen layout. Consider you want to draw a frame, on top of an image or the camera preview. In this example you just need to extend View (as mentioned), and than override the onDraw(Canvas canvas) method, where you will be doing your drawing.

public final class CaptureLayout extends View
{
….
@Override
public void onDraw(Canvas canvas)
{
   int width = canvas.getWidth();
   int height = canvas.getHeight();

   // Draw the exterior (i.e. outside the framing rect) darkened
   Paint m_Paint = new Paint();
   m_Paint.setColor(Color.GREEN);
   Rect m_Box = new Rect();
   m_Box.set(0, 0, width, frame.top); // create a box
   canvas.drawRect(m_Box, m_Paint); // draw the box with the given color

If you want more, let’s add some interaction with the widget.
For example let’s say we want to display a message if the user hits the green box (that we just drew).
In order to do this, we need to add a click listener. Thus, when we allocate the widget, we need to pass this click_listener as a parameter to setOnClickListener. Example:

CaptureLayout cl = (CaptureLayout)findViewById(R.id.mezzofanti_capturelayout_view);
cl.setOnClickListener(new OnClickListener() {
     public void onClick(View clickedView) {
     // action for green rectangle pressed
     }
     }
);

Categories: android java Tags:

Shared Preferences

August 25th, 2009 No comments

(Android phone – how-to/example)

The android.content.SharedPreferences may be useful if you want to save some application settings in a file, and share them through-out all the activities in your application. One cool feature is that the SharedPreferences is directly linked to the android.preference package, that is if you use a android.preference.PreferenceActivity in your application for storing/retrieving the setup, all the variables in the setup and the variables in the SharedPreferences will share the same xml file on the disk. This file may be found on disk in /data/data/com.my.package.name/. For more info about creating your own PreferenceActivity consult the appropriate post on this website.

Let’s say you want to store on disk a boolean variable, to know if you want to skip the introduction at the start of the application or not. The code to write the variable is:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor spe = prefs.edit();
spe.putBoolean(KEY_SKIP_INTRO_AT_STARTUP, true); // we just save “true” in the xml file
spe.commit();

The code to read the variable is:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
m_bSkipIntroAtStartup = prefs.getBoolean(KEY_SKIP_INTRO_AT_STARTUP, false); // if it cannot read the value from file, will by default return false

where “this” is the current activity, m_bSkipIntroAtStartup is the variable to be initialized, and KEY_SKIP_INTRO_AT_STARTUP is the string key (ex: String KEY_SKIP_INTRO_AT_STARTUP = “preferences_skip_intro_at_startup”;)

Categories: android java Tags:

Get the orientation of the phone

August 25th, 2009 No comments

(Android phone – how-to/example)

If your application is dependent on the orientation of the phone, you may like to take a look at android.view.OrientationEventListener package.

To create the OrientationListener you will need the current activity Context.

private void CreateOrientationListener(Context context)
{
   m_OEListener = new OrientationEventListener (context, SensorManager.SENSOR_DELAY_UI)
   {
   public void onOrientationChanged (int orientation)
   {
   // in orientation you will find the orientation expressed in degrees

To enable/disable the listener:

public void OrientationEnable(boolean enable)
{
if (m_OEListener==null)
   return;

if (enable)
   m_OEListener.enable();
else
   m_OEListener.disable();
}

Note: You may choose to enable/disable while pausing/resuming the current activity.

Categories: android java Tags: ,

Broadcast Receiver

August 25th, 2009 No comments

(Android phone – how-to/example)

Android implements in an elegant manner the intent broadcast. One will use this, if for example you want to register to some actions (ex: one wants to know when something happens to the sdcard).

For the sdcard example, in order to register your “intentions”, use the following:

IntentFilter intentFilter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED);
intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED);
intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
intentFilter.addAction(Intent.ACTION_MEDIA_CHECKING);
intentFilter.addAction(Intent.ACTION_MEDIA_EJECT);
intentFilter.addDataScheme(”file”);
registerReceiver(m_brSDcardEvent, intentFilter);

where m_brSDcardEvent is the Broadcast Receiver itself, while the intentFilter is the filter where we register our interests.

To receive the intents and using them, is done in the Broadcast Receiver:

private final BroadcastReceiver m_brSDcardEvent = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();

if (action.equals(Intent.ACTION_MEDIA_MOUNTED))
{
// SD card available
}
else if (action.equals(Intent.ACTION_MEDIA_UNMOUNTED)
|| action.equals(Intent.ACTION_MEDIA_CHECKING))
{

….

all other intents will be treated similarly.

Note: do not forget to un-register your activity from the broadcast, if you do not want to alter the functionality of all other applications residing on the phone.

unregisterReceiver(m_brSDcardEvent);

The Message Handler

August 25th, 2009 No comments

(Android phone – how-to/example)

A Handler allows you to send and process Message and Runnable objects associated with a thread’s MessageQueue. Each Handler instance is associated with a single thread and that thread’s message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it — from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.

There are two main uses for a Handler: (1) to schedule messages and runnables to be executed as some point in the future; and (2) to enqueue an action to be performed on a different thread than your own.

This is how one will send an empty signaling message from a function to another.
In the main activity declare your handler:

private Handler m_myMsgHandler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
   switch(msg.what)
   {
   case R.id.message_id1:
   // do the according processing
….

In the caller method, one has just to send the empty message:

m_myMsgHandler.sendEmptyMessage(R.id.message_id1);

Alternatively, one can send a delayed message:

m_myMsgHandler.sendEmptyMessageDelayed(R.id.message_id1, longDelayMilliseconds);

Passing data from one caller method to the message handler is also straight-forward:

Message message = m_myMsgHandler.obtainMessage(R.id.message_id2, data);
message.sendToTarget();

where data, is the data you want to encapsulate (ex: byte[] data, int data etc)

In the message handler, in the switch, one will use the data as follows:


case R.id.message_id1:
   byte[] val = (byte[]) msg.obj;

Categories: android java Tags: