Aug 30, 2011

Android tips for developers

1. Be resolution independent. Check out “layoutopt” and “hierarchyviewer” that come with Android SDK under “tools”. They help analyzing and optimizing layouts.

2. Respect and use an application lifecycle.

3. In order to avoid friendly “Force Close” popups from your applications, use Android’s “AsyncTask” which will allow to execute a certain activity in background.

4. Only use a WakeLock when you need one with as minimum level as possible: PARTIAL_WAKE_LOCK, SCREEN_DIM_WAKE_LOCK, FULL_WAKE_LOCK. Here is more about PowerManager.

5. Always check whether “network connection” is enabled on a device, before attempting to transfer data.
continue reading Android tips for developers

Aug 29, 2011

Androit : FTP operation (connection, upload, download ,list,etc)


Android SDK does not provide FTP connection, so that We need to use external library for FTP operation, There are various option available for FTP connection like Apache, Here I am using ftp4j. I choose ftp4j because it's very lightweight api/jar file, the FTP library size is almost 70 KB. ftp4j provides listener (FTPDataTransferListener) to check progress of uploading or downloading.

Click here to download ftp4j library

To Test my android ftp demo application you need to have FTP Host Url or IP and FTP username and password.

Here is the uploadFile function, just pass File object which you want to upload, FTP_HOST, FTP_USER,FTP_PASS are static final String object, you need to replace value of there variable before test the android ftp demo application

public void uploadFile(File fileName){
    	
    	
		 FTPClient client = new FTPClient();
		try {
			client.connect(FTP_HOST,21);
			client.login(FTP_USER, FTP_PASS);
			client.setType(FTPClient.TYPE_BINARY);
			client.changeDirectory("/");
			client.upload(fileName, new MyTransferListener());
		} catch (Exception e) {
			e.printStackTrace();
			try {
				client.disconnect(true);	
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		
    }


Click Here to download full source code.

Note: Click on File select download original.

continue reading Androit : FTP operation (connection, upload, download ,list,etc)

Aug 18, 2011

Android: Check application is running ?

Android has different application lifecycle, Many times user press Home hardware button and application goes in background, Application is still running but it's in background, Now We want to identify that application is running in background or not. It require when we don't want to create new instance of Activity. Android SDK provide class named ActivityManager. Using ActivityManager we can check application is running in background.

Here is the simple code for the same. you just need to change package name as per your requirement.

ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
 // get the info from the currently running task
List < ActivityManager.RunningTaskInfo > taskInfo = am.getRunningTasks(1);

Log.d("current task :", "CURRENT Activity ::" + taskInfo.get(0).topActivity.getClass().getSimpleName());

ComponentName componentInfo = taskInfo.get(0).topActivity;
//if  app is running
if(componentInfo.getPackageName().equalsIgnoreCase(*Package Name*))
{
 //do the implementation for if your app is running
}

Reference:
http://developer.android.com/reference/android/app/ActivityManager.html
continue reading Android: Check application is running ?

Android fetch Hardware Information

Sometime we required to identify the device information (Hardware Information).

Android SDK provide following class to get Hardware Information like Manufacturer, CPU, Memory ....
Example
String manu = Build.MANUFACTURER;
String board = Build.BOARD;
String display = Build.DISPLAY;

Reference
http://developer.android.com/reference/android/os/Build.html

continue reading Android fetch Hardware Information

Aug 12, 2011

Send Email without User Interaction (In Background)

Android provide Intent to send the email. It compose email in Native Email editor and user need to click on Send button to send the email. It crease issue when application need to send more then one email. User will not click on send button 10 or 20 times.

To solve this issue. I found javaMail API implemented for Andorid.

I have create Demo project, attached with this article. JavaMail also allowed to send email with attachment and HTML as body content. JavaMail required email user name & password to send the email.

You can find "Mail" class in attached source code.  In following code you need to replace USER EMAIL, PASSWORD, user name and password is require to send email.

Code Snippet To Send Email
        Mail m = new Mail("USER EMAIL", "PASSWORD"); 
        String[] toArr = {"EMAIL-1", "EMAIL-2"}; 
        m.setTo(toArr); 
        m.setFrom("USER EMAIL"); 
        m.setSubject("This is an email sent using my Mail JavaMail wrapper from an Android device."); 
        m.setBody("Email body"); 
        try { 
          m.addAttachment("/sdcard/bday.jpg"); 
          if(m.send()) { 
            Toast.makeText(this, "Email was sent successfully.", Toast.LENGTH_LONG).show(); 
          } else { 
            Toast.makeText(this, "Email was not sent.", Toast.LENGTH_LONG).show(); 
          } 
        } catch(Exception e) { 
          Log.e("MailApp", "Could not send email", e); 
        } 

Click Here to Download the Source Code
 Note: To download source code click on File->Download Original File
continue reading Send Email without User Interaction (In Background)

Aug 11, 2011

Android Application Crash Logs

Android SDK shipped with many tools for development but sometime situation occur that application works perfect when you test. When you provide APK to client then error occur. How do you identify where the error comes. It difficult because usually clients are non-technical person. clients might be in another country. In these situation you can suggest your client to follow following steps to collect application crash logs.

  1. Download & Install Log collector app from https://market.android.com/details?id=com.xtralogic.android.logcollector&feature=search_result on device.
  2. Now run application which you want to Test for crash logs.
  3. Whenever application crashes, start Log Collector application.
  4. It will ask you for sending options for crash logs, choose gmail app.
  5. write recipient email id and send the email.





continue reading Android Application Crash Logs

Aug 5, 2011

Android In-Depth : How layoutopt works ?

Hello All,

In my previous post, I have explain you how to use layoutopt. It is common question how layoutopt works.
As you all aware that Android OS is open source. so I find the source code of layoutopt. layout is developed in core java. It parse the XML file and verify set of rules.  Apache Groovy library to implemented for rule engine.

I have also attached source code with this article.

Layoutopt apply following rules on every Layout.

  1. IncorrectHeightInScrollView.rule
  2. IncorrectWidthInHorizontalScrollView.rule
  3. InefficientWeight.rule
  4. InefficientWeight.rule
  5. NestedScrollingWidgets.rule
  6. TooManyChildren.rule
  7. TooManyLevels.rule
  8. TooManyViews.rule
  9. UseCompoundDrawables.rule
  10. UselessLayout.rule
  11. UselessView.rule
continue reading Android In-Depth : How layoutopt works ?

Android Layout Optimize (layoutopt)

Android has many command-line tools available in platform-tools folder. "layoutopt" is one of them. Many time we take layout inside layout and never think about optimization of UI. Our main fous to achieve the final output. layoutopt tool allow us to verify our layout and suggest the change (if any). layoutopt is command-line tool. layoutopt analyze XML files.

1. Open Terminal
2. Go to Android-SDK/platform-tools/


To run layoutopt against a given list of layout resources:
layoutopt <file_or_directory> ...
For example:

$ layoutopt samples/
samples/compound.xml
   7:23 The root-level <FrameLayout/> can be replaced with <merge/>
   11:21 This LinearLayout layout or its FrameLayout parent is useless
samples/simple.xml
   7:7 The root-level <FrameLayout/> can be replaced with <merge/>
samples/too_deep.xml
   -1:-1 This layout has too many nested layouts: 13 levels, it should have <= 10!
   20:81 This LinearLayout layout or its LinearLayout parent is useless
   24:79 This LinearLayout layout or its LinearLayout parent is useless
   28:77 This LinearLayout layout or its LinearLayout parent is useless
   32:75 This LinearLayout layout or its LinearLayout parent is useless
   36:73 This LinearLayout layout or its LinearLayout parent is useless
   40:71 This LinearLayout layout or its LinearLayout parent is useless
   44:69 This LinearLayout layout or its LinearLayout parent is useless
   48:67 This LinearLayout layout or its LinearLayout parent is useless
   52:65 This LinearLayout layout or its LinearLayout parent is useless
   56:63 This LinearLayout layout or its LinearLayout parent is useless
samples/too_many.xml
   7:413 The root-level <FrameLayout/> can be replaced with <merge/>
   -1:-1 This layout has too many views: 81 views, it should have <= 80!
samples/useless.xml
   7:19 The root-level <FrameLayout/> can be replaced with <merge/>
   11:17 This LinearLayout layout or its FrameLayout parent is useless


Reference Article.
1. http://developer.android.com/guide/developing/debugging/debugging-ui.html#layoutopt
2. http://mobile.tutsplus.com/tutorials/android/android-sdk-tools-layout-optimization/
continue reading Android Layout Optimize (layoutopt)

Aug 2, 2011

Android Plist Parser



The Android-PList-Parser is designed to work with valid PList XMLs only. Before you start getting into the code, you want to be certain that the PList XML you're working with is valid according to the DTD). If it's valid, proceed to the next paragraph. you may want to write code from scratch instead of trying to modify this code (since it's algorithm relies on the assumption of validity).

The basic rule for the algorithm is that elements are treated in two different ways: ones that can have children (Dict and Array), and ones that can't. Elements that can have children are pushed onto a ArrayList method is used. With these concepts in mind, reading the code should be a little easier.

This is very basic parser. you require to modify as per your requirement.

Let's me show you the example which I have prepare specially for my Plist problem. There are two main file 1. DataModel.java and 2. ParsePlist.java

1. DataMode.java - A model class holds the value of Plist.
2. ParsePlist.java - Class which parse the plist.
3. Sample.plist  - Plist file placed in Asset folder.
4. PlistParser.java - Activity has button to trigger the parsing event.  On Parse Button click, Application will fetch plist file from assets and pass the XML string content to ParsePlist class.

Download Source  

continue reading Android Plist Parser