Amazon Gift Cards

Saturday, January 31, 2009

Getting the Contact Info when on a number

On android when someone call you or you receive a message, a non formatted number would be shown to you and for you to find out whom that number is, you have to use Contacts.Phones.CONTENT_FILTER_URL on your query. This article is based on Get Phone State When Someone is calling using BroadcastReceiver Example
public class MyPhoneStateListener extends PhoneStateListener {
  private String[] projection = new String[] {
    People._ID, People.NAME, People.NUMBER
  };
  public void onCallStateChanged(int state,String incomingNumber){
    switch(state)
    {
      case TelephonyManager.CALL_STATE_IDLE:
        Log.d("DEBUG", "IDLE");
      break;
      case TelephonyManager.CALL_STATE_OFFHOOK:
        if(!incomingNumber.equals("")){
          handleCall(incomingCall);
        }
      break;
      case TelephonyManager.CALL_STATE_RINGING:
        Log.d("DEBUG", "RINGING");
      break;
    }
  }
  public void handleCall(String incomingCall){
    Uri contactUri = Uri.withAppendedPath(Contacts.Phones.CONTENT_FILTER_URL, incomingNumber);
    contactsCursor = context.getContentResolver().query(contactUri, projection, null , null, People.NAME + " ASC");
    if(contactsCursor.moveToFirst()){
      int phoneNameIndex = contactsCursor.getColumnIndex(People.NAME);
      String phoneNameStr = contactsCursor.getString(phoneNameIndex);
      Log.d("DEBUG",phoneNameStr + " is calling");
    }else{
      Log.d("DEBUG","Not a contact");
    }
  }
}



Quick Explanation
Looking on the handleCall function, there is nothing really new here, for the BroadcastReceiver explanation go to this page and for the displaying contact names go to this page. Sorry i'm too lazy to explain here coz i already explained it on the previous post.

Anyway i have to temporarily stop my android adventure and do some stuff for work which is webbased stuff so the next article would be web based article. Thanks

Update History
   Jan 17, 2012 - Visual Update

Wednesday, January 28, 2009

Force Localize an Application on Android

Localization has always been a problem in tech at large and products from big companies like Google, Apple and Microsoft are not immune to it and so does Android (I know they came from Google). But one thing that was cool about Android is it was built for developers to localized their apps by default but the problem is that the API or documentation is lacking. If your in a journey to further localize your application, i suggest you to read this page on the official google groups for developers.

As the title stated, you can force your application to be localize on an application basis and not system basis. In this article we would use simplied chinese and english. To do this you have to edit something on your oncreate function on your default activity.

Update for Android 2.0
Add android:configChanges="locale" to your activity nodes on the manifest file
<activity android:name=".Main" android:configChanges="locale" android:label="@string/app_name" />

import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;

public class Main extends Activity {
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    String languageToLoad  = "cn";
    Locale locale = new Locale(languageToLoad); 
    Locale.setDefault(locale);
    Configuration config = new Configuration();
    config.locale = locale;
    getBaseContext().getResources().updateConfiguration(config, 
    getBaseContext().getResources().getDisplayMetrics());
    this.setContentView(R.layout.main);
  }
}


Quick Explanation
String languageToLoad = "cn";
Locale locale = new Locale(languageToLoad);
Locale.setDefault(locale);

-- Here we create an new Locale in ch (Simplified Chinese) and set our default locale to a specific locale (See this for more information)

Configuration config = new Configuration();
config.locale = locale;

-- This would create a new Configuration which we would use later and then we change the locale of this configuration with our chinese locale.

getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());

-- This is the core part, here we only update the configuration of our basecontext's resources. I might not be right here but according to the description of Context, Interface to global information about an application environment. Getting the baseContext should be application level.

Source Code
Main.java
main layout
strings.xml in values folder
strings.xml in values-cn folder

Update History
   Jan 17, 2012 - Visual Update

Thursday, January 22, 2009

Get Phone State When Someone is calling using BroadcastReceiver Example

In this article we shall try to listen to the phone state when contacts are calling us.

First of all we need to set our Manifest file to listen to the Phone State, to do that we need to edit our it.
<application>
  .....
  <receiver android:name=".ServiceReceiver">
    <intent-filter>
      <action android:name="android.intent.action.PHONE_STATE" />
    </intent-filter>
</receiver>
</application>
<uses-permission android:name="android.permission.READ_PHONE_STATE">
</uses-permission>



Here you can see that we created a receiver xml node inside our application and have the java class ServiceReceiver to listen to it. What it would listen to is the PHONE_STATE and thus we need the permission of READ_PHONE_STATE. Then our ServiceReceiver Class would look like this.



public class ServiceReceiver extends BroadcastReceiver {
  @Override
  public void onReceive(Context context, Intent intent) {
    MyPhoneStateListener phoneListener=new MyPhoneStateListener();
    TelephonyManager telephony = (TelephonyManager) 
    context.getSystemService(Context.TELEPHONY_SERVICE);
    telephony.listen(phoneListener,PhoneStateListener.LISTEN_CALL_STATE);
  }
}


For the full class including the imports, please download the files below. In here we have another class called MyPhoneStateListener, which would be shown at the bottom. What this class would do is execute the phoneListener when the telephony.listen has received a LISTEN_CALL_STATE.


public class MyPhoneStateListener extends PhoneStateListener {
  public void onCallStateChanged(int state,String incomingNumber){
  switch(state){
    case TelephonyManager.CALL_STATE_IDLE:
      Log.d("DEBUG", "IDLE");
    break;
    case TelephonyManager.CALL_STATE_OFFHOOK:
      Log.d("DEBUG", "OFFHOOK");
    break;
    case TelephonyManager.CALL_STATE_RINGING:
      Log.d("DEBUG", "RINGING");
    break;
    }
  } 
}


What we have is a function called onCallStateChanged which would be fired when the LISTEN_CALL_STATE dispatches it. The states are either, ringing(CALL_STATE_RINGING), answers (CALL_STATE_OFFHOOK), or hang up/end call (CALL_STATE_IDLE). To see the logs in eclipse. Go to Window -> Show View -> Other -> Android -> LogCat

Hope it helps.


Sources
AndroidManifest.xml
ServiceReceiver.java
MyPhoneStateListener.java


References
BroadcastReceiver

Update History
   Jan 17, 2012 - Visual Update

Thursday, January 15, 2009

Calling a Contact in Android

There will be a time where you might want to use the Caller on Android. Here is how you would do it, this article also introduces how to get an individual contact from your contact list. This is based on our previous article Clicking Items in ListActivity and Display Contact Names in Android.

protected void onListItemClick(ListView l, View v, int position, long id) {
  // GET THE ITEM THAT HAD BEEN TAPPED
  Uri uri = ContentUris.withAppendedId(People.CONTENT_URI, id);
  Cursor c = managedQuery(uri, new String[] {
    People.NUMBER
  }, null, null, null);
  c.moveToFirst();

  // CALL THE NUMBER FROM THE PREVIOUS SCREEN\
  int phoneNumberIndex = c.getColumnIndex(People.NUMBER);
  Uri parsedPhoneNumber = Uri.parse("tel:"+c.getString(phoneNumberIndex)); 
  Intent i = new Intent(Intent.ACTION_CALL,parsedPhoneNumber);
  startActivity(i);

  super.onListItemClick(l, v, position, id);
}


Quick Explanation
// GET THE ITEM THAT HAD BEEN TAPPED
Uri uri = ContentUris.withAppendedId(People.CONTENT_URI, id);
Cursor c = managedQuery(uri, new String[] {
People.NUMBER
}, null, null, null);
c.moveToFirst();
- Here we query our contacts with People.CONTENT_URI but on one specific contact. Then after we got the results we move the cursor to the first record.

- int phoneNumberIndex = c.getColumnIndex(People.NUMBER);
Uri parsedPhoneNumber = Uri.parse("tel:"+c.getString(phoneNumberIndex));

The first on is used to get the index of NUMBER in our fields, we do this coz c.getString arguement is the column id. Then to create a number that our caller accepts we need to pass it a Uri that starts with "tel:"

Intent i = new Intent(Intent.ACTION_CALL,parsedPhoneNumber);
startActivity(i);

Here we create a new Intent that would use the default caller and we pass the Uri of our phone number, then we start the calling with startActivity(i).


Update History
   Jan 17, 2012 - Visual Update

Wednesday, January 14, 2009

Clicking Items in ListActivity

From our Display Contact Names in Android and Displaying AlertDialog in Android, lets further expand that so that we would make use if the items in our ListActivity when user click the an item list, this article would be a brief one. For the following code just add it to your class, you can view the full source code at the bottom if you don't know where to put them.
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
  alertDialog = new AlertDialog.Builder(this).create();
  alertDialog.setTitle("Item Selected");
  alertDialog.setMessage("You just clicked an 
  item position #" + String.valueOf(position));
  alertDialog.setButton("OK",new DialogInterface.OnClickListener(){
    public void onClick(DialogInterface dialog, int which) {
    return;
  } }); 
  alertDialog.show();

  super.onListItemClick(l, v, position, id);
}



Quick Explanation
Here all we need to do it implement a function, onListItemClick, you can do this in eclipse by Right Click->Source->Override/Implement Method->onListItemClick.
There would be 4 arguments ListView l, View v, int position, long id, view this to see that they mean.

References
Display Contact Names in Android
Displaying AlertDialog in Android
android.app.ListActivity

Source
Main.java of Clicking Items in ListActivity


Update History
   Jan 17, 2012 - Visual Update

Tuesday, January 13, 2009

Displaying AlertDialog in Android

After 3 days of not posting and a whole day staring at the command line, here we are again with Android. This time its how to display AlertDialog in Android. I'll just post the core codes and you can download the source code to see the whole code.

Update
Jun 12, 2011 - I created a small tool to generate code for this at http://www.generateandroidcode.com/android/alert

public void onClick(View view) {
  if(view == this.alertBtn){
    alertDialog = new AlertDialog.Builder(this).create();
    alertDialog.setTitle("Alert 1");
    alertDialog.setMessage("This is an alert");
    alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int which) {
        return;
    } }); 
  }else if(view  == this.alert2Btn){
    alertDialog = new AlertDialog.Builder(this).create();
    alertDialog.setTitle("Alert 2");
    alertDialog.setMessage("This is another alert");
    alertDialog.setIcon(R.drawable.search);
    alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int which) {
        return;
    } }); 
    alertDialog.setButton2("Cancel", new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int which) {
        return;
    }}); 
  }else if(view  == this.alert3Btn){
    alertDialog = new AlertDialog.Builder(this).create();
    alertDialog.setTitle("Alert 3");
    alertDialog.setMessage("This is the third alert");
    alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int which) {
        return;
    } }); 
    alertDialog.setButton2("Cancel", new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int which) {
        return;
    }}); 
    alertDialog.setButton3("Middle", new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int which) {
        return;
    }});
  }
  alertDialog.show();
}


Quick Explanation
alertDialog = new AlertDialog.Builder(this).create();
- Here using the AlertDialog Builder, we shall build a new AlertDialog on the current activity;

alertDialog.setTitle("Alert 1");
alertDialog.setMessage("This is an alert");

- This line is logical, it sets the title and message of our AlertDialog

alertDialog.setButton<[ ]|2|3>("OK", new DialogInterface.OnClickListener() {
....... });

- In AlertDialog there could be either 1 or 2 or 3 buttons, and you can set up each and their click functions as well.

alertDialog.setIcon(R.drawable.search);
- You can change the icon of the AlertDialog using this line.

alertDialog.show();
- This is the line where you show the AlertDialog we had created

Saturday, January 10, 2009

Icons in Options Menu in Android (Code)

Here is a brief topic on how to set icons on options menu in Android, this is an extension to Options Menu in Android.

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class Main extends Activity {
  private int searchBtnId = Menu.FIRST;
  private int scheduleBtnId = Menu.FIRST + 1;

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

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    MenuItem searchMItm = menu.add(Menu.NONE,
searchBtnId ,searchBtnId,"Search");
    searchMItm.setIcon(R.drawable.search);
    MenuItem scheduleMItm = menu.add(Menu.NONE,
scheduleBtnId ,scheduleBtnId,"Schedule" );
    scheduleMItm.setIcon(R.drawable.schedule);
    return super.onCreateOptionsMenu(menu);
  }
}


Quick Explanation
MenuItem scheduleMItm = menu.add(Menu.NONE, scheduleBtnId ,scheduleBtnId,"Schedule" );
menu.add returns a MenuItem in which we can use its method setIcon, scheduleMItm.setIcon(R.drawable.schedule);, here we imported a png into our folder and named it as schedule.
 
Source Code
Main.java
 
References
MenuItem
Options Menu in Android (Code)

Update History
   Jan 17, 2012 - Visual Update

Friday, January 9, 2009

Displaying Maps and going to a location in Android

One thing that you would enjoy in Android is the Maps, and in this article i would show how to display maps for you to start your map application.

First of all you need to get a API Key, and here a more detailed explanation, i suggest you to read the last link.

Then on your Manifest file, insert uses-permissions of INTERNET and ACCESS_COARSE_LOCATION, and uses-library of com.google.android.maps resulting in
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="<Your package>"
  android:versionCode="1"
  android:versionName="1.0.0"
>
  <application android:icon="@drawable/icon"
    android:label="@string/app_name">
    <uses-library android:name="com.google.android.maps" 
  />
    <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>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
</manifest>



Our main.java code
import android.os.Bundle;
import android.view.ViewGroup;

import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.GeoPoint;

public class Main extends MapActivity {
  private MapView mapView;
  private MapController mapController;
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.setContentView(R.layout.main);

    this.mapView = (MapView) this.findViewById(R.id.mapView);
    ViewGroup zoom = (ViewGroup) this.findViewById(R.id.zoom);
    zoom.addView(this.mapView.getZoomControls());

    this.mapController = this.mapView.getController();
    this.mapController.setZoom(16);
    this.gotoMyHome();
  }

  private void gotoMyHome(){
    Double lat = 22.312381*1E6;
    Double lng = 114.225242*1E6;
    this.mapController.setCenter(new GeoPoint(lat.intValue()
,lng.intValue()));
  }

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


Quick Explanation
this.mapView = (MapView) this.findViewById(R.id.mapView);
- In this article we would use xml as our layout so we need to get our MapView element from our xml

ViewGroup zoom = (ViewGroup) this.findViewById(R.id.zoom);
zoom.addView(this.mapView.getZoomControls());

- Here we add a ViewGroup zoom component so that we could zoom in and zoom out our map.

this.mapController = this.mapView.getController();
- Next we get our MapController, A utility class to manage panning and zooming of a map.

this.mapController.setZoom(16);
- Zoom our map to level 16, you can set this between 1 and 21 but on the higher number (deeper zoom) it will depend if the map can zoom up to that level.

Double lat = 22.312381*1E6;
Double lng = 114.225242*1E6;

- Here we get the latitude and longitude near my home and we multiply it to a constant of 1E6 so that we can convert it to int which is needed by GeoPoint.
this.mapController.setCenter(new GeoPoint(lat.intValue(),lng.intValue()));
- Now we center our map to the GeoPoint or location near my home. Remember GeoPoint accepts integers only so we had to convert it.

Now our xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent" 
> 
  <com.google.android.maps.MapView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:enabled="true"
    android:clickable="true"
    android:apiKey="<your api key>"
    android:id="@+id/mapView"
  />

  <LinearLayout android:id="@+id/zoom"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
  />
</RelativeLayout>


Quick Explanation
Here we created a MapView element and a LinearLayout for our zoom control. In this xml you should replace android:apiKey="<your api key>" with your api key.

Source Code
Main Layout of Displaying Maps
AndroidManifest of Displaying Map
Main.java of Displaying Map

References
Obtaining a Maps API Key
www.anddev.org

Update History
   Jan 17, 2012 - Visual Update

Thursday, January 8, 2009

Options Menu in Android (Code)

There are 2 types of menu in Android one is the "options menu" and the other is "context menu".

The options menu is shown when you press the "Menu" button on the device, In this example we would only show how to use codes to display the options.
There are four ways of adding a menu item on your application, but it can be minimized into 2 ways, the following codes would explain these.

package com.monmonja.firstDemo;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;

public class Main extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.setContentView(R.layout.main);
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    menu.add("Search");
    menu.add(R.string.schedule);
    return super.onCreateOptionsMenu(menu);
  }
}

Quick Explanation
In creating a menu you need to override onCreateOptionsMenu (on Eclipse, right click on your codes then Source, Override/Implement Methods, search for onCreateOptionsMenu). Then inside we call menu.add which takes one parameter either int titleRes or CharSequence title. Here either it takes a string or a resource object.


package com.monmonja.firstDemo;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;

public class Main extends Activity {
  private int searchBtnId = Menu.FIRST;
  private int scheduleBtnId = Menu.FIRST + 1;
  private int playBtnId = Menu.FIRST + 2;
  private int stopBtnId = Menu.FIRST + 3;
  private int group1Id = 1;
  private int group2Id = 2;

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

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    menu.add(group1Id,searchBtnId ,searchBtnId,"Search");
    menu.add(group2Id,scheduleBtnId ,scheduleBtnId,R.string.schedule);
    menu.add(group2Id,playBtnId ,playBtnId,"Play");
    menu.add(group2Id,stopBtnId ,stopBtnId,R.string.stop);
    // the following line will hide search 
    // when we turn the 2nd parameter to false
    menu.setGroupVisible(1, false);
    return super.onCreateOptionsMenu(menu);
  }
}


Quick Explanation
Second menu.add takes 4 parameters, having an int groupId, int itemId, int order, and the four one as either int titleRes or CharSequence title. The first one is a group id, so you can group menu and hide other groups or show other groups. The second one is the menu item id, then the third is the order where you want then to be shown and the last one is the label of the menu item.

References
Common Tasks in Android

Wednesday, January 7, 2009

Searching Audio Files in Android

Searching for Audio Files in Android is so much similar in Display Contact Names in Android (I suggest you to look back at the explanation for a more detailed explanation). The audio formats that Android allows are MP3, AAC, AMR.
public class Main extends ListActivity {
  private Cursor audioCursor;
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    audioCursor = this.managedQuery(Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
    startManagingCursor(audioCursor);

    String[] columnsToMap = new String[] {Audio.Media.TITLE , Audio.Media._ID};
    int[] mapTo = new int[] {android.R.id.text1,android.R.id.text2};

    ListAdapter mAdapter = new SimpleCursorAdapter(this, android.R.layout.two_line_list_item , audioCursor, columnsToMap, mapTo);
    this.setListAdapter(mAdapter);
  }
}


Quick Explanation
The thing that you need here is Audio.Media.EXTERNAL_CONTENT_URI, as stated on the the contact display article, managedQuery acts like a sql call and the table this time is Audio.Media.EXTERNAL_CONTENT_URI.
Another thing you might have notice is String[] columnsToMap = new String[] {Audio.Media.TITLE , Audio.Media._ID};. These and a lot more are the columns that can be used.

Source Code
Main.java file for Searching Audio in Android

References
android.provider.MediaStore.Audio.Media
Display Contact Names in Android



Update History
   Jan 17, 2012 - Visual Update

Monday, January 5, 2009

Changing the Screen Brightness Programatically

Update: If your target is cupcake(android 1.5), you might want to see this tutorial


There are some discussion on Google group on this matter so i try to see if how this problem can be fixed. This problem could be fixed by using something that is not documented and is not advised to use (Its sort of a hack, i'm not responsible if something went wrong on your android). What this app will do it count to 240, 20 per second starting from 0. Then on each count it will set the brightness of your phone.

Anyway here is the how i did it. Please read the Note at the bottom.

First add <uses-permission android:name="android.permission.HARDWARE_TEST"></uses-permission> to your Manifest file.
package com.monmonja.firstDemo;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.IHardwareService;
import android.os.Message;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.widget.TextView;

public class Main extends Activity  { 
  private TextView txtStatus;
  private RefreshHandler mRedrawHandler = new RefreshHandler();

  class RefreshHandler extends Handler {
    @Override
    public void handleMessage(Message msg) {
      Main.this.updateUI();
    }

    public void sleep(long delayMillis) {
      this.removeMessages(0);
      sendMessageDelayed(obtainMessage(0), delayMillis);
    }
  };

  private void updateUI(){
    int currentInt = Integer.parseInt((String) txtStatus.getText()) + 20;
    if(currentInt <= 250){
      mRedrawHandler.sleep(1000);
      setBrightness(currentInt);
      txtStatus.setText(String.valueOf(currentInt));
    }
  }

  @Override 
  public void onCreate(Bundle icicle) { 
    super.onCreate(icicle); 
    setContentView(R.layout.main);
    this.txtStatus = (TextView) this.findViewById(R.id.txtStatus);
    updateUI();
  } 

  private void setBrightness(int brightness) {
    try {
      IHardwareService hardware = IHardwareService.Stub.asInterface(
ServiceManager.getService("hardware"));
      if (hardware != null) {
        hardware.setScreenBacklight(brightness);
      }
    } catch (RemoteException doe) {          
    }        
  }
}


Note
By default there is no IHardwareService and other classes related to it. In order to have this you can download hardware09.jar and place it on your application folder (In my app, i created a new folder named lib). In order to use this on eclipse, you need to right click on your application, Properties, Java Build Paths, and click Add JAR.

Set to include hardware.jar

Quick Explanation
We get our hardware services via IHardwareService hardware = IHardwareService.Stub.asInterface(ServiceManager.getService("hardware")); then we set the brightness hardware.setScreenBacklight(brightness);

Source Code
Main.xml of Changing Brightness
Main.java of Changing Brightness

References
Using Handler in Android
FlashLight Source File

Hope you will get the hardware09.jar to work/referenced in your eclipse.

Hope it helps :)

Update History
   Jan 17, 2012 - Visual Update

Using Handler in Android

If you come from a Javascript/Actionscript 1 or 2, you probably know setInterval coz you need to use it a lot, in Android there are several ways in making your setInterval, one of which is using a Handler with Thread or using Timer, on this article would focus on using Handler. The reference of where i learn this is on your android sdk folder, under the samples, there is an app named Snake.java. You can take a look at that one and see more advance than the codes below.
package com.monmonja.firstDemo;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;

public class Main extends Activity  { 
  private TextView txtStatus;
  private RefreshHandler mRedrawHandler = new RefreshHandler();

  class RefreshHandler extends Handler {
    @Override
    public void handleMessage(Message msg) {
      Main.this.updateUI();
    }

    public void sleep(long delayMillis) {
      this.removeMessages(0);
      sendMessageDelayed(obtainMessage(0), delayMillis);
    }
  };

  private void updateUI(){
    int currentInt = Integer.parseInt((String) txtStatus.getText()) + 10;
    if(currentInt <= 100){
      mRedrawHandler.sleep(1000);
      txtStatus.setText(String.valueOf(currentInt));
    }
  }

  @Override 
  public void onCreate(Bundle icicle) { 
    super.onCreate(icicle); 
    setContentView(R.layout.main);
    this.txtStatus = (TextView) this.findViewById(R.id.txtStatus);
    updateUI();
  } 
}



Quick Explanation
This one is probably the most hardest for me to explain so far, okay so here is how it goes. We created a class inside our Activity that extends Handler, now on this handler we override handleMessage so what we can use this Handler to handle our messages to it. We then declare a sleep function to delay another execute of this handler with the function sendMessageDelayed. Now on our updateUI we set our own codes and call mRedrawHandler.sleep(1000); to delay our message. But before all of this to happen on our onCreate function we call updateUI to start updating our textfield.


Hope it helps and hope i'm not wrong with my explanations.

Sunday, January 4, 2009

Getting Battery Information on Android

Getting the Battery Information in Android without Apps like AnyCut, Power Manager or System Monitor is one of the hardest task. You can try those if you have an Android phone, anyway here is how to get the Battery Information (some of the codes are undocumented).
public class Main extends Activity {
  private TextView contentTxt;
  private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
    @Override
    public void onReceive(Context arg0, Intent intent) {
      // TODO Auto-generated method stub
      int level = intent.getIntExtra("level", 0);
      contentTxt.setText(String.valueOf(level) + "%");
    }
  };

  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
    contentTxt = (TextView) this.findViewById(R.id.monospaceTxt);
    this.registerReceiver(this.mBatInfoReceiver, 
    new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
  }
}



Quick Explanation
Here we listen to a Intent (ACTION_BATTERY_CHANGED) and register a receiver when the intent is fired. In ActionScript, this is i believe is DispatchEvent, and we would call mBatInfoReceiver and get the current level of our battery life and put that int value to our textfield or TextView.

Source Code
My Battery Status 1 Source

Here is the source where i got the this stuff working



Update History
   Jan 17, 2012 - Visual Update

Saturday, January 3, 2009

Default fonts in Android

There are 3 default fonts in android, there are monospace, sans and serif, here is a xml and the screen cap of those fonts.
<?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_height="wrap_content" 
    android:typeface="monospace" 
    android:id="@+id/monospaceTxt" 
    android:layout_width="fill_parent" 
    android:text="Monospace: The quick brown 
    fox jumps over the lazy dog" 
    android:background="#424242">
  </TextView>
  <TextView android:layout_height="wrap_content" 
    android:typeface="sans" 
    android:id="@+id/sansTxt" 
    android:layout_width="fill_parent" 
    android:text="sans: The quick brown fox 
    jumps over the lazy dog">
  </TextView>
  <TextView android:layout_height="wrap_content" 
    android:typeface="serif" 
    android:layout_width="fill_parent" 
    android:text="serif: The quick brown fox 
    jumps over the lazy dog" 
    android:id="@+id/serifTxt" 
    android:background="#424242">
  </TextView>
</LinearLayout>



Quick Explanation
Changing the font on xml is just one attribute and that is android:typeface. Any view/components that extends TextView would instantly have a typeface attribute.

Here is how you can set this as your layout in your java code




Update History
   Jan 17, 2012 - Visual Update

Changing Activity in Android

In Android, a new page(html) is a new screen and thus is a new Activity, for example you have an application that has a preferences screen and you want to open that preferences on your application, here is how to do it.

Quick background, here we have 2 Activity classes, Main and Preferences, each activity has its own layout xml. I shall provide only the core code to do this and add a link to the other files that is required for this article.
package com.monmonja.firstDemo;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class Main extends Activity implements View.OnClickListener{ 
  private View preferencesBtn;
  @Override 
  public void onCreate(Bundle icicle) { 
    super.onCreate(icicle); 
    setContentView(R.layout.main); 
    this.preferencesBtn = (Button) this.findViewById(R.id.preferencesBtn);
    this.preferencesBtn.setOnClickListener(this);
  }

  public void onClick(View view) {
    if(view == this.preferencesBtn){
      Intent prefIntent = new Intent(this,Preferences.class);
      this.startActivity(prefIntent);
    }
  } 
}



Quick Explanation
We set up a button to listen to a click event, and on that event we create a new Intent with Intent prefIntent = new Intent(this,Preferences.class);, where we pass the class name of Preferences, then we use this.startActivity(prefIntent); to start our new Activity. You can take a look at our Preferences.java and Preferences.xml to see that the results. When we're on the Preferences Screen you can hit the back button to go back to the Main Screen.

Preferences.xml Chaging Activity In Android
Main.xml Chaging Activity In Android
Preferences.java Chaging Activity In Android
Main.java Chaging Activity In Android

Update History
   Jan 17, 2012 - Visual Update

Friday, January 2, 2009

AbsoluteLayout in Android (XML)

AbsoluteLayout is the layout that you may want if you want to specify the x and y, in html its position:absolute, and the x(top) and y(left) is android:layout_x and android:layout_y. By looking at this, you can see that there are 5 possible value. Yet in our example i'm going to give you 4 coz i cant successful run the 5th one.
<?xml version="1.0" encoding="utf-8"?> 
<AbsoluteLayout
  xmlns:android="http://schemas.android.com/apk/res/android"   android:orientation="vertical"   android:layout_width="fill_parent"   android:layout_height="fill_parent" >   <Button android:id="@+id/pixelsBtn"     android:layout_width="wrap_content"     android:layout_height="wrap_content"     android:text="Pixels"     android:layout_y="50px"     android:layout_x="80px">   </Button>   <Button android:id="@+id/scaledBtn"     android:layout_width="wrap_content"     android:layout_height="wrap_content"     android:text="Scaled"     android:layout_y="100px"     android:layout_x="80sp">   </Button>   <Button android:id="@+id/inchesBtn"     android:layout_width="wrap_content"     android:layout_height="wrap_content"     android:text="Inches"     android:layout_y="150px"     android:layout_x="0.5in">   </Button>   <Button android:id="@+id/millimetersBtn"     android:layout_width="wrap_content"     android:layout_height="wrap_content"     android:text="Milli Meters"     android:layout_y="200px"     android:layout_x="8mm">   </Button> </AbsoluteLayout>


Quick Explanation
Here we just specify the x and y, by looking at this you would logically understand what they mean.

Here is how you can set this as your layout in your java code

absoluteLayout in android

Update History
   Jan 17, 2012 - Visual Update

Thursday, January 1, 2009

RelativeLayout in Android (XML)

RelativeLayout, from the word Relative, the concept here is that every children is a relative of the other. The catch here is that they are related by where you put them according to the other components, these relationship are above a component, below a component, on the left of the component and on the right of the components and some others like align to positions. Here we shall cover the above, below, left of, right of.
<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout 
  xmlns:android="http://schemas.android.com/apk/res/android" 
  android:orientation="vertical" 
  android:layout_width="fill_parent" 
  android:layout_height="fill_parent"
> 
  <Button android:id="@+id/topBtn" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Top" 
    android:layout_centerHorizontal="true">
  </Button>

  <Button android:id="@+id/leftBtn" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Left"
    android:layout_below="@+id/topBtn"
    android:layout_toLeftOf="@+id/topBtn">
  </Button>

  <Button android:id="@+id/bottomBtn" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Bottom"
    android:layout_below="@+id/leftBtn"
    android:layout_toRightOf="@+id/leftBtn">
  </Button>

  <Button android:id="@+id/rightBtn" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Right"
    android:layout_above="@+id/bottomBtn"
    android:layout_toRightOf="@+id/bottomBtn"&
  </Button>
</RelativeLayout>


Quick Explanation
Here you shall see Top is aligned to the middle (android:layout_centerHorizontal="true"), the Left button is below top (android:layout_below="@+id/topBtn") and also is on its left. The Bottom is below leftBtn and on the right of leftBtn too. Lastly the Right is above and on the right of bottomBtn.

Further reading
RelativeLayout in Hello View in Android

Update History
   before 2012: Here is how you can set this as your layout in your java code
   Jan 17, 2012 - Visual Update