Oct 19, 2011

Android API Difference between 3.0 and 4.0 OS - Ice Cream Sandwich


API Difference between Honeycomb and Ice Cream Sandwich

The overall difference between API Levels 13 and 14 is approximately 3.95%. The table below lists the numbers of program elements (packages, classes, constructors, methods, and fields) that were added, changed, or removed. The table includes only the highest-level program elements — that is, if a class with two methods was added, the number of methods added does not include those two methods, but the number of classes added does include that class.

Type Additions Changes Removals Total
Packages 5 48 0 53
Classes and Interfaces 90 192 0 282
Constructors 19 2 0 21
Methods 265 94 29 408
Fields 405 34 16 455
Total 804 370 45 1219

Here I found the list of removed classes, methods and interfaces in Android SDK 4.0.


  • ALBUM_ART 
  • freeze ()
  • FX_SURFACE_BLUR 
  • FX_SURFACE_DIM 
  • FX_SURFACE_MASK 
  • FX_SURFACE_NORMAL 
  • GPU 
  • HARDWARE 
  • HIDDEN 
  • hide ()
  • NON_PREMULTIPLIED 
  • obtain (long, long, int, int, int[], PointerCoords[], int, float, float, int, int, int, int)
  • PUSH_BUFFERS 
  • readData
    • type  (float[]) in android.renderscript.AllocationAdapter 
    • type  (int[]) in android.renderscript.AllocationAdapter 
  • SECURE 
  • setAlpha (float)
  • setDataSource (String)
  • setFlags (int, int)
  • setFreezeTint (int)
  • setLayer (int)
  • setMatrix (float, float, float, float)
  • setOrientation (int, int)
  • setPosition (int, int)
  • setSize (int, int)
  • setSummaryOff
    • type  (int) in android.preference.CheckBoxPreference 
    • type  (CharSequence) in android.preference.CheckBoxPreference 
  • setSummaryOn
    • type  (int) in android.preference.CheckBoxPreference 
    • type  (CharSequence) in android.preference.CheckBoxPreference 
  • setTransparentRegionHint (Region)
  • show ()
  • subData (int, FieldPacker)
  • subData1D
    • type  (int, int, byte[]) in android.renderscript.AllocationAdapter 
    • type  (int, int, float[]) in android.renderscript.AllocationAdapter 
    • type  (int, int, int[]) in android.renderscript.AllocationAdapter 
    • type  (int, int, short[]) in android.renderscript.AllocationAdapter 
  • subData2D
    • type  (int, int, int, int, float[]) in android.renderscript.AllocationAdapter 
    • type  (int, int, int, int, int[]) in android.renderscript.AllocationAdapter 
  • subElementData (int, int, FieldPacker)
  • SURACE_FROZEN 
  • SURFACE_BLUR_FREEZE 
  • SURFACE_DITHER 
  • SURFACE_FROZEN 
  • SURFACE_HIDDEN 
  • unfreeze ()

continue reading Android API Difference between 3.0 and 4.0 OS - Ice Cream Sandwich

Oct 10, 2011

Android Add menu in Share




Many times you might observe 3rd party application icon in Android Share menu. Suppose your application pick image/video from gallery, pick contact from contact book or pick audio from music player In this situation better options is to add your application menu in Share options so that user can directly select image/video from gallery or relavent application.

Share menu will display name & icon of your application

It is very easy to add menu in Share option.

Step 1 : Create Android project

Step 2 : Create activity named "MyShareMenu.java" (No need to create xml layout for this Activity)

Step 3: Register new activity in AndroidManiFest.xml file like following



<activity android:name="MyShareMenu">
            <intent-filter>
                <action android:name="android.intent.action.SEND"></action>
                <data android:mimetype="*/*"></data>
                <category android:name="android.intent.category.DEFAULT"></category>
            </intent-filter>
    </activity>
The importent part is data tag in that you can specify mimeType as per your application supports. For the demo purpose I have choose */* means every mimeType but you can write image/*, audio/* , video/* as per the need of your application.

Step 4: Fetch Uri of selected item, When user click on application from the Share menu, Android will call "MyShareMenu" activity with uri of selected item. Use following code to get Uri.

protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  
  Intent intent = getIntent();
  Bundle extras = intent.getExtras();
  String action = intent.getAction();
  
  // if this is from the share menu
  if (Intent.ACTION_SEND.equals(action)) {   
   if (extras.containsKey(Intent.EXTRA_STREAM)) {
    //  Get resource path
    Uri uri = (Uri) extras.getParcelable(Intent.EXTRA_STREAM);
    Toast.makeText(this, "Selected File :" + uri.toString(), Toast.LENGTH_LONG).show();
    }
  } 
 }

In above code I have displays Toast but your can write business logic as per your need.


continue reading Android Add menu in Share

Sep 2, 2011

Android - Copy sqlite database from device to PC

Android supports SQLite database. It is placed in /data/data/<package name>/databases folder. When we are working with Emulator. we can access /data/data/<package name>/database folder. We can pull database from Emulator by using DDMS or adb pull comment. As we know that mobile device does not allow data/data folder for security reason. We can not access /data/data folder by using DDMS or abd pull. It may create problem for debugging. To solve this problem following function can use. Following function copy sqlite database from device to PC.

public void copyDatabaseToSdCard() {
		Log.e("Databasehealper", "********************************");
		try {
			File f1 = new File("DATABASE PATH AND NAME");
			if (f1.exists()) {

				File f2 = new File(Environment.getExternalStorageDirectory().getAbsoluteFile()+ "/My_App_Database.db");
				f2.createNewFile();
				InputStream in = new FileInputStream(f1);
				OutputStream out = new FileOutputStream(f2);
				byte[] buf = new byte[1024];
				int len;
				while ((len = in.read(buf)) > 0) {
					out.write(buf, 0, len);
				}
				in.close();
				out.close();
			}
		} catch (FileNotFoundException ex) {
			System.out.println(ex.getMessage() + " in the specified directory.");
			System.exit(0);
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println(e.getMessage());
		}
		Log.e("Databasehealper", "********************************");
	}

Generally I use this function in "DataBaseHelper.java" class. In Above function you have to replace "DATABASE PATH AND NAME" (i.e. /data/data/com.kpbird.sqldemo/databases/mydatabase.db) value. the function copy your database in root of sdcard with "My_App_Database.db" name.
continue reading Android - Copy sqlite database from device to PC

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

Jul 27, 2011

UltimatePinger

Dear fellas,

Greetings of the day.

Allow me to introduce our free service : "UltimatePinger" - The Ultimate Ping Engine. UltimatePinger is a Service like Ping-o-matic, Pingoat, PingDevice etc., just more intuitive, less obtrusive and may be fun to use. Furthermore, it is the only free ping engine that allows pinging multiple updates (urls) to multiple ping servers (of your choice) in realtime. Did I mention it's free?

UltimatePinger is free because it's how we conceived it, plus, it's based upon (mostly) free resources. Additionally, it's anonymous, and will stay so if it's not being grossly misused.

If you are serious about popularizing your site or blog, you need to make sure that every new content on your blog is indexed by the search engines and directories. Further, every new backlink pointing to your site/blog must get indexed too (otherwise the very purpose of building backlinks gets defeated)! Pinging the new updates and pages containing the backlinks to search engines and ping servers expedites the process of crawling and subsequent indexing.

Now imagine you create a single post/page and 25 back links to the new page (say using SocialMonkey) per day, then you need to make 26 pings to 30+ ping servers everyday. Doing it manually is impossible. Ping-o-matic and other such ping services come to your rescue here, which automatically ping single urls to a list of predefined services, though you still have to ping every single one of 26 urls manually. Sure, there are bulk-ping services like pingdevice - which will let you ping all 26 urls at a single go, but still, not all services ping to all ping servers (of search engines and directories), so, you still have to ping other ping servers that your chosen ping service doesn't ping. It is here, apart from other things that UltimatePinger is different, probably batter too, from other services. You see, it lets you ping multiple urls to multiple ping servers of your choice in a single go! Further, it keeps track of your failed pings and lets you reping only the failed ones in a single click. Not to mention, it allows you to save the list of your preferred ping servers to your computer. It's real time, so you get to know the results of your pings in real time.

Right now it is in beta. If you like it, tell your friends about it, and if not, tell us "exactly what doesn't click for you". To know more about the UltimatePinger, be sure to read the FAQs.

So without further ado, welcome to the UltimatePinger



http://ultimatepinger.tk/
continue reading UltimatePinger

Jun 12, 2011

Boost Traffic to Your Site with SocialMonkee - Why and How?


This article is intended towards novice bloggers, but everyone is welcome to read it and hopefully comment upon it. This is not a HowTo, rather a WhyTo, if you know what I mean, in which case, title of this blog is a bit misleading!

If you are reading this post, you are interested in increasing traffic to your blog, and I will tell you one very good way to do it just in a while, but before that, take a few moments to consider this question, "What do we mean by traffic and how do we increase it?" In simple terms, the number of people visiting your website in a specific time, say a day, is traffic, but like everything else in life, there is more to it. You see, if your website is OKAY, people may visit it again, but that won't be considered increase in traffic. The real increase is new visitors, which brings us to the other half of the question, how do we get new visitors to achieve increase in traffic? The answer is advertising, be it paid (as in google adwords) or free (Search Engine Optimization), people need to know of the existence of your site and they need to reach you through a hyperlink. So, where do you put this hyperlink then? Surely some place visible to your target audience - like google search results!

There are many ways to increase your visibility on the web like social networking/bookmarking, directories, link exchange and other link building exercises etc., however, ultimately, google search results is the only way you can make yourself truly visible. Sure, there are many search engines and infinite ways to promote your website, but google targeted SEO weighs probably more than everything else combined. Thus, everything you do, make sure you are targeting search engine optimization (SEO) with respect to Google.

So, how can this SocialMonkee help me about this SEO thing, you ask? You see, SEO used to be about keywords a decade ago, but it's now about Pagerank? That is not to say keywords are useless nowadays, but the search engine algorithms of today are so much sophisticated that stuffing your pages with keywords or even keyphrases won't help you for a longer period of time, instead, it may earn you a ban from search engines. Pagerank is a mixture of the credibility and relevance of your site with respect to a specific topic. Pagerank depends upon internal as well as external SEO. Internal SEO depends solely upon the content of your site, where as external SEO depends upon backlinks. Backlinks are links on external domains (other than the domain of your own site) pointing towards a page on your site. Backlinks are considered to be endorsement(s) of the quality of the content on your site by the webmaster of respective sites (where your backlink resides). Further, the more backlinks you have, the more are chances that someone will click them and visit your site. So backlinks increase traffic to your website by improving your search engine ranking (pagerank - and thus visibility of your site) and by providing a means to reach your site.

There are two ways you can get backlinks. Either someone will put a link of your site/page on his site or you will have to put your own link on other(s') sites. The former is achieved by link exchange, where two webmasters agree to put each other's links on their sites, but is a stale and probably a worthless thing to do in present times, however, if done unsolicited (no link-exchange/resiprocal links) is a very good thing for your pagerank, depending upon pagerank of the linking site. Putting your links to other sites can be accomplished by social networking/bookmarking. The problem with most social bookmarking sites is, however, that they are 'no-follow', which means, the backlinks will be ignored by search engines. It is here that SocialMonkee comes to rescue.

SocialMonkee is a free service that allows to put one backlink of your site (or any page thereof) to 25 different sites every 24 hours with a single click in a semiautomated and search engine friendly manner. All these links are posted by different user credentials on any 25 of 100 domains owned by the creator of SocialMonkee. That means you can collect 25 x 30 = 750 backlinks for your site in a month, which is a huge number if you ask me, and all these without a single dime! SocialMonkee won't let you post any url more than once so you don't need to worry about search engines considering you a spammer. An efficient workflow would include posting to SocialMonkee after every new post has been published. Of course, if you want to post to 100 sites thrice a day (three different urls, obviously), you can opt for their premium membership (paid), and you can get premium membership free too by referring SocialMonkee to 12 fellow bloggers (subject to change, I suppose).

To register, follow this link or link.  A few people have found some difficulties in getting registered with SocialMonkee, but I believe that's only because it's such a young service, and everyone has eventually got registered, so have faith. There is not much to be explained about how to use this service as it's very simple and there are videos available for that, go search, be creative. The SocialMonkey website also has a great deal of info on how to use the service, so repeating it here would be a waste of your time.

Now a word about internet marketing, a caution or a plea really. You see, if you read this article in hope of diverting the internet traffic to your site to generate some big money or fame, please be advised that, although it has happened before, the success ratio is close to zero. There is no alternative of quality content. A quality content is what your readers want to read. All your efforts will go in vain if your content is not good. The internet nowadays is full with crap, don't contribute yours as well. If your content does not have a real purpose, adding SocialMonkee links will add more crap to internet. Refrain from such practice.

I will try to write for KPBird, as and when I get more time. Till then, stay tuned.

About myself: I am Mitesh Patel, a guest author on KPBird. I am a chemistry graduate and my interests range from Guitars to Motorbikes to Computing, and anything in-between. As a hobbyist blogger, I maintain a blog (more of a database) about Luthiers (guitar makers) named LuthierDB. Fellow bloggers/readers are welcome to visit my blog to observe what is "simplicity and elegance of design" from my perspective.
continue reading Boost Traffic to Your Site with SocialMonkee - Why and How?

May 30, 2011

Android Clipboard Framework

Android SDK 3.0 has various new API. Android 3.0 has 1180 new classes, methods and interfaces. (Click Here for complete list).  Clipboard Framework is newly introduce in Android 3.0. basic purpose of this framework is to provide copy and paste data between various application.  It is very powerful framework. It supports simple data like text (String) and complex type like binary data, objects etc.

Here I am going to explain very simple example of Android Clipboard Framework. Let's start with introduction of key classes.

1. ClipboardManager: It is represent as global object. We do not need to create new object of ClipboardManager. We can directly fetch object from system service. we can get reference by invoking getSystemService(CLIPBOARD_SERVICE).

2. ClipData: To put any object in clipboard we need to create object of ClipData class. ClipData object contain ClipData.Item and ClipDescription.

3. ClipData.Item: It contain object which we copied. Object can be Text, URI or Intent data.

4. ClipDescription: It is metadata about clip. It contain MIME type of clip data.
 
Let's start with very simple demo of ClipBoard Framework.
continue reading Android Clipboard Framework

May 25, 2011

Android API Difference between 2.0 and 3.1 OS

History of Android API Changes in Percentages.

The table below list the changes from version 2.0 to 3.1. The table includes only the highest-level program elements— that is, if a class with two methods was added, the number of methods added does not include those two methods, but the number of classes added does include that class.


OS Version API Level % change Addition Changes Removals Total
Android 2.0 to 2.1 6 to 7 0.48 81 37 0 118
Android 2.1 to 2.2 7 to 8 5.7 475 225 33 733
Android 2.2 to 2.3 8 to 9
Android 2.3 to 2.3.4 9 to 10 0.65 25 17 2 44
Android 2.3.4 to 3.0 10 to 11 2.56 1182 375 27 1584
Android 3.0 to 3.1 11 to 12 1.15 174 126 14 314

Calculation of Change Percentages

The percent change statistic reported for all elements in the "to" API Level specification is defined recursively as follows:

Percentage difference = 100 * (added + removed + 2*changed)
                        -----------------------------------
                        sum of public elements in BOTH APIs
where added is the number of packages added, removed is the number of packages removed, and changed  is the number of packages changed. This definition is applied recursively for the classes and their program  elements, so the value for a changed package will be less than 1,  unless every class in that package has changed. The definition ensures that if all packages are removed and all new  packages are added, the change will be 100%.

Related Post

1. Android API Difference between 3.0 and 3.1 OS

continue reading Android API Difference between 2.0 and 3.1 OS

Android API Difference between 3.0 and 3.1 OS


Android 3.1 is the first revision to Android 3.0 (Honeycomb), It is optimized for Tablet.  Google announced the update on 10 May 2011. The first major update to Honeycomb refines many of the features in the original Honeycomb version. I am not going to discuss the new feature or functionality Google has added but I am going to discuss API difference specially things which are removed in 3.1
API Changes between Android OS 3.0 and Android OS 3.1,

Overall difference between API Levels 11 and 12 is 1.15%. Table shows statics, additions, changes and removals.


Type Additions Changes Removals Total
Packages 3 24 0 27
Classes and Interfaces 5 65 6 76
Constructors 4 1 6 11
Methods 75 27 2 104
Fields 87 9 0 96
Total 174 126 14 314


Here I found the list of removed classes, methods and interfaces in Android SDK 3.1.

1. Config()  - Removed Constructor
2. DebugUtils() - Removed Constructor
3. EventLog() - Removed Constructor
4. getPluginList()  - Remove Method
5. Plugin   - Remove Classes and Interface
6. Plugin.PerferencesClickHandler - Remove Classes and Interface
7. Plugin.Data - Remove Classes and Interface
8. PluginList - Remove Classes and Interface
9. refereshPlugins() - Removed Method
10. StateSet() - Removed Constructor
11. TimeUtils() - Removed Constructor
12. UrlInterceptHandler - Remove Classes and Interface
13 UrlInterceptRegistry - Remove Classes and Interface
14. Xml() - Removed Constructor

Related Post
1. Android API Difference between 2.0 and 3.1 OS

continue reading Android API Difference between 3.0 and 3.1 OS

May 23, 2011

Android Light Sensor

Hello Guys,

Here I am explaining you how to use Light Sensor of Android.
1. Implement SensorEventListener
2. Create variable for SensorManager and Sensor
3. Get Object of SensorManager using system service
4. Get Object of Light Sensor from SensorManager
5. Implement onAccuracyChanged and onSensorChanged method



package com.test;

import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;

public class Test extends Activity implements SensorEventListener{

 private SensorManager mSensorManager;
 private Sensor mLight;

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

   mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
         mLight = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);

 }
 @Override
 protected void onResume() {
   mSensorManager.registerListener(this, mLight, SensorManager.SENSOR_DELAY_NORMAL);
  super.onResume();
 }
 @Override
 protected void onPause() {
  mSensorManager.unregisterListener(this);
  super.onPause();
 }
 public void onAccuracyChanged(Sensor sensor, int accuracy) {
   if(sensor.getType() == Sensor.TYPE_LIGHT){
    Log.i("Sensor Changed", "Accuracy :" + accuracy);
   }
  
 }

 public void onSensorChanged(SensorEvent event) {
  if( event.sensor.getType() == Sensor.TYPE_LIGHT){
   Log.i("Sensor Changed", "onSensor Change :" + event.values[0]);
  }
  
 }
}

Screen Shot of Change Values


continue reading Android Light Sensor

May 20, 2011

Android Loading Image from Server

Hello Guys,


Here I am writing easiest way to download image from server. Following function return Drawable object.  Use drawable object as per your  requirement.




private Drawable LoadImageFromWeb(String url) {
  try {
   InputStream is = (InputStream) new URL(url).getContent();
   Drawable d = Drawable.createFromStream(is, "src name");
   return d;
  } catch (Exception e) {
   System.out.println("Exc=" + e);
   return null;
  }
 }
continue reading Android Loading Image from Server

May 8, 2011

Android: Seek Bar with Two Thumb

Seek bar with two thumb control is badly required by some developer, including my self, When I start looking this control I was tired and frustrated.  and finally I have decided to create my own seek bar control with two thumb. I have used my control in one of the my android project. Initially I tried to extend SeekBar control but I am unable to extend it. so finally I decided to extend ImageView control and I got succes.




Here I am publishing my own seek bar control with two thumb.

continue reading Android: Seek Bar with Two Thumb

May 4, 2011

Android:Bottom Tabbar Control

Introduction

In this tutorial, You will learn how to create application with bottom TabBar Control. Tab Bar control is present in Android UI component but It always displays at top of screen. Many times we required to display Tabs at bottom of screen, just like iPhone, Unfortunately Android native TabBar control does not provide facility to display Tabs at bottom of the screen.  

Tabbar Control Screen Shots






Download Source Code from Here : Click
[Note: Click On File-> Download To download source code zip file]
continue reading Android:Bottom Tabbar Control

May 2, 2011

Android: How to fetch Media File list


You can use following code to fetch media files. It is possible using managedQuery function. Android has default MediaPlayer application. MediaPlayer application manage Audio and Video files list.. so, We can fetch list from MediaPlayer application using following code.

Using managedQuery we can fetch media file list

 String[] proj = { MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Video.Media.SIZE };
            musiccursor = managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
proj, null, null, null);


I assume that you have basic knowledge of create & execute Android Projects.
Let's create project step by step to use above code.

continue reading Android: How to fetch Media File list

Apr 29, 2011

Android: WebView, Detect HTML Element on Click

Android WebView allow us to display web pages inside the application. Also allowed to  interact with web content, there are several reasons that you might want to use WebView in your applications. It is powerful enough to execute JavaScript. It allow us to load HTML content as String and also display Web Page from domain/URL.

Here I am going to teach you how to detect user's action. Suppose you want to take specific action when user click on image or button or link then it is possible.

We can detect following HTML elements as per Android API Document.

int ANCHOR_TYPE HitTestResult for hitting a HTML::a tag
int EDIT_TEXT_TYPE HitTestResult for hitting an edit text area
int EMAIL_TYPE HitTestResult for hitting an email address
int GEO_TYPE HitTestResult for hitting a map address
int IMAGE_ANCHOR_TYPE HitTestResult for hitting a HTML::a tag which contains HTML::img
int IMAGE_TYPE HitTestResult for hitting an HTML::img tag
int PHONE_TYPE HitTestResult for hitting a phone number
int SRC_ANCHOR_TYPE HitTestResult for hitting a HTML::a tag with src=http
int SRC_IMAGE_ANCHOR_TYPE HitTestResult for hitting a HTML::a tag with src=http + HTML::img
int UNKNOWN_TYPE Default HitTestResult, where the target is unknown
 
Src : http://developer.android.com/reference/android/webkit/WebView.HitTestResult.html

Here are many HTML element missing. like RadioButton, CheckBox etc.. I can not detect radio button or check box click event.

continue reading Android: WebView, Detect HTML Element on Click

Apr 28, 2011

Android: Send Image via Bluetooth

I assume that you have experience of developing Bluetooth application in Android. Android Bluetooth API  is not supporting OBEX directly, means I can not push any file directly to any device. Android Bluetooth API provide basic functionalities like discovery, connection and data transfer using streams (InputStream and OutputStream).

Transferring file using Bluetooth need lot of coding. We need to manage device discovery, connection, IO etc.

Now I found very simple way to send file using Bluetooth. Android has build-in Bluetooth application which allow us to send file across the devices.  Build-in Bluetooth Application use SharedPerference to manage queue for Incoming and Outgoing files.

I find the way to use same technique. Android Bluetooth application use ContentProvider to manage communication between storage and user interface. so I found the way that we can use it's functionality 

Here is the code, Following 6 line allow you to send file using bluetooth,  you required only two things 1. URI of file which you want to send 2. DeviceAddress.



  1. ContentValues values = new ContentValues();
  2. values.put(BluetoothShare.URI, "content://" + uritoSend);
  3. values.put(BluetoothShare.DESTINATION, deviceAddress);
  4. values.put(BluetoothShare.DIRECTION, BluetoothShare.DIRECTION_OUTBOUND);
  5. Long ts = System.currentTimeMillis();
  6. values.put(BluetoothShare.TIMESTAMP, ts);
Description of above code.
1. Create object of ContentValue
2. put URI of file which you want to send
3. put DeviceAdddress, destination device address
4. put Direction, set outbound means you want to send the file.
5. time stamp which will display at Notification bar
6. put time stamp.

Note: Above code is useful only if we can have URI of file which we want to send. It is perfectly work for Images because we can get URI of images available in Gallery but If we want to send file from SDCard then it difficult because we can not get URI of file available in SDCard.

BluetoothShare.java
import android.provider.BaseColumns;
import android.net.Uri;

/**
 * Exposes constants used to interact with the Bluetooth Share manager's content
 * provider.
 */

public final class BluetoothShare implements BaseColumns {
private BluetoothShare() {
}
/**
 * The permission to access the Bluetooth Share Manager
 */
public static final String PERMISSION_ACCESS = "android.permission.ACCESS_BLUETOOTH_SHARE";

/**
 * The content:// URI for the data table in the provider
 */
public static final Uri CONTENT_URI = Uri.parse("content://com.android.bluetooth.opp/btopp");

/**
 * Broadcast Action: this is sent by the Bluetooth Share component to
 * transfer complete. The request detail could be retrieved by app * as _ID
 * is specified in the intent's data.
 */
public static final String TRANSFER_COMPLETED_ACTION = "android.btopp.intent.action.TRANSFER_COMPLETE";

/**
 * This is sent by the Bluetooth Share component to indicate there is an
 * incoming file need user to confirm.
 */
public static final String INCOMING_FILE_CONFIRMATION_REQUEST_ACTION = "android.btopp.intent.action.INCOMING_FILE_NOTIFICATION";

/**
 * This is sent by the Bluetooth Share component to indicate there is an
 * incoming file request timeout and need update UI.
 */
public static final String USER_CONFIRMATION_TIMEOUT_ACTION = "android.btopp.intent.action.USER_CONFIRMATION_TIMEOUT";

/**
 * The name of the column containing the URI of the file being
 * sent/received.
 */
public static final String URI = "uri";

/**
 * The name of the column containing the filename that the incoming file
 * request recommends. When possible, the Bluetooth Share manager will
 * attempt to use this filename, or a variation, as the actual name for the
 * file.
 */
public static final String FILENAME_HINT = "hint";

/**
 * The name of the column containing the filename where the shared file was
 * actually stored.
 */
public static final String _DATA = "_data";

/**
 * The name of the column containing the MIME type of the shared file.
 */
public static final String MIMETYPE = "mimetype";

/**
 * The name of the column containing the direction (Inbound/Outbound) of the
 * transfer. See the DIRECTION_* constants for a list of legal values.
 */
public static final String DIRECTION = "direction";

/**
 * The name of the column containing Bluetooth Device Address that the
 * transfer is associated with.
 */
public static final String DESTINATION = "destination";

/**
 * The name of the column containing the flags that controls whether the
 * transfer is displayed by the UI. See the VISIBILITY_* constants for a
 * list of legal values.
 */
public static final String VISIBILITY = "visibility";

/**
 * The name of the column containing the current user confirmation state of
 * the transfer. Applications can write to this to confirm the transfer. the
 * USER_CONFIRMATION_* constants for a list of legal values.
 */
public static final String USER_CONFIRMATION = "confirm";

/**
 * The name of the column containing the current status of the transfer.
 * Applications can read this to follow the progress of each download. See
 * the STATUS_* constants for a list of legal values.
 */
public static final String STATUS = "status";

/**
 * The name of the column containing the total size of the file being
 * transferred.
 */
public static final String TOTAL_BYTES = "total_bytes";

/**
 * The name of the column containing the size of the part of the file that
 * has been transferred so far.
 */
public static final String CURRENT_BYTES = "current_bytes";

/**
 * The name of the column containing the timestamp when the transfer is
 * initialized.
 */
public static final String TIMESTAMP = "timestamp";

/**
 * This transfer is outbound, e.g. share file to other device.
 */
public static final int DIRECTION_OUTBOUND = 0;

/**
 * This transfer is inbound, e.g. receive file from other device.
 */
public static final int DIRECTION_INBOUND = 1;

/**
 * This transfer is waiting for user confirmation.
 */
public static final int USER_CONFIRMATION_PENDING = 0;

/**
 * This transfer is confirmed by user.
 */
public static final int USER_CONFIRMATION_CONFIRMED = 1;

/**
 * This transfer is auto-confirmed per previous user confirmation.
 */
public static final int USER_CONFIRMATION_AUTO_CONFIRMED = 2;

/**
 * This transfer is denied by user.
 */
public static final int USER_CONFIRMATION_DENIED = 3;

/**
 * This transfer is timeout before user action.
 */
public static final int USER_CONFIRMATION_TIMEOUT = 4;

/**
 * This transfer is visible and shows in the notifications while in progress
 * and after completion.
 */
public static final int VISIBILITY_VISIBLE = 0;

/**
 * This transfer doesn't show in the notifications.
 */
public static final int VISIBILITY_HIDDEN = 1;

/**
 * Returns whether the status is informational (i.e. 1xx).
 */
public static boolean isStatusInformational(int status) {
    return (status >= 100 && status < 200);
}

/**
 * Returns whether the transfer is suspended. (i.e. whether the transfer
 * won't complete without some action from outside the transfer manager).
 */
public static boolean isStatusSuspended(int status) {
    return (status == STATUS_PENDING);
}

/**
 * Returns whether the status is a success (i.e. 2xx).
 */
public static boolean isStatusSuccess(int status) {
    return (status >= 200 && status < 300);
}

/**
 * Returns whether the status is an error (i.e. 4xx or 5xx).
 */
public static boolean isStatusError(int status) {
    return (status >= 400 && status < 600);
}

/**
 * Returns whether the status is a client error (i.e. 4xx).
 */
public static boolean isStatusClientError(int status) {
    return (status >= 400 && status < 500);
}

/**
 * Returns whether the status is a server error (i.e. 5xx).
 */
public static boolean isStatusServerError(int status) {
    return (status >= 500 && status < 600);
}

/**
 * Returns whether the transfer has completed (either with success or
 * error).
 */
public static boolean isStatusCompleted(int status) {
    return (status >= 200 && status < 300) || (status >= 400 && status < 600);
}

/**
 * This transfer hasn't stated yet
 */
public static final int STATUS_PENDING = 190;

/**
 * This transfer has started
 */
public static final int STATUS_RUNNING = 192;

/**
 * This transfer has successfully completed. Warning: there might be other
 * status values that indicate success in the future. Use isSucccess() to
 * capture the entire category.
 */
public static final int STATUS_SUCCESS = 200;

/**
 * This request couldn't be parsed. This is also used when processing
 * requests with unknown/unsupported URI schemes.
 */
public static final int STATUS_BAD_REQUEST = 400;

/**
 * This transfer is forbidden by target device.
 */
public static final int STATUS_FORBIDDEN = 403;

/**
 * This transfer can't be performed because the content cannot be handled.
 */
public static final int STATUS_NOT_ACCEPTABLE = 406;

/**
 * This transfer cannot be performed because the length cannot be determined
 * accurately. This is the code for the HTTP error "Length Required", which
 * is typically used when making requests that require a content length but
 * don't have one, and it is also used in the client when a response is
 * received whose length cannot be determined accurately (therefore making
 * it impossible to know when a transfer completes).
 */
public static final int STATUS_LENGTH_REQUIRED = 411;

/**
 * This transfer was interrupted and cannot be resumed. This is the code for
 * the OBEX error "Precondition Failed", and it is also used in situations
 * where the client doesn't have an ETag at all.
 */
public static final int STATUS_PRECONDITION_FAILED = 412;

/**
 * This transfer was canceled
 */
public static final int STATUS_CANCELED = 490;

/**
 * This transfer has completed with an error. Warning: there will be other
 * status values that indicate errors in the future. Use isStatusError() to
 * capture the entire category.
 */
public static final int STATUS_UNKNOWN_ERROR = 491;

/**
 * This transfer couldn't be completed because of a storage issue.
 * Typically, that's because the file system is missing or full.
 */
public static final int STATUS_FILE_ERROR = 492;

/**
 * This transfer couldn't be completed because of no sdcard.
 */
public static final int STATUS_ERROR_NO_SDCARD = 493;

/**
 * This transfer couldn't be completed because of sdcard full.
 */
public static final int STATUS_ERROR_SDCARD_FULL = 494;

/**
 * This transfer couldn't be completed because of an unspecified un-handled
 * OBEX code.
 */
public static final int STATUS_UNHANDLED_OBEX_CODE = 495;

/**
 * This transfer couldn't be completed because of an error receiving or
 * processing data at the OBEX level.
 */
public static final int STATUS_OBEX_DATA_ERROR = 496;

/**
 * This transfer couldn't be completed because of an error when establishing
 * connection.
 */
public static final int STATUS_CONNECTION_ERROR = 497;

}


AndroidManifast.xml
<uses-permission android:name="android.permission.BLUETOOTH"/>

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








continue reading Android: Send Image via Bluetooth

Apr 27, 2011

Android InDepth : SharedPreference


1. Introduction

SharedPreference is used to store settings/preferences. It stores data as key/value pairs. It share data between activities but not across the processes.

Shared Preference is stored in /data/data/[package name]/shared_prefs/[SP Name].xml.

In Device data/data folder is not accessible but we can access data/data folder in Emulator. Using DDMS allow access to every folders including data/data folder. It is possible to pull  the Shared Preference  xml file to PC. If we stuck in any problem related to Shared Preference then we can transfer xml file to PC for observation.


2. Implementation


Let's Create simple example of SharedPreference. SharedPreference is Interface. We do not need to create object of SharedPreference. It created with the Activity. I will explain how SharedPreference Object will crate in this tutorial. Activity has method named "getSharedPreference()" we can retrieve object like following.

2.1 Retrieving object of SharedPreference
SharedPreference pref = getSharedPreference("MyPRef",MODE_PRIVATE);
Method has two parameter Name and Mode, Name is used as XML file name. 

  • MODE_PRIVATE is the operating mode for the preferences. It is the default mode and means the created file will be accessed by only the calling application. 
  • MODE_WORLD_READABLE other application can read the created file but can not modify it. 
  • MODE_WORLD_WRITEABLE other applications also have write permissions for the created file. 
First mode is default we can implement in this example. but what about other two options.  I found following post in "StackOverFlow.com"


"As I checked in APIs description for getSharedPreferences(String, int),Second attribute is defining accessibility mode and can take 0 or MODE_PRIVATE for the default operation, MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE to control permissions.

But there is this small note in API description:

Note: currently this class (android.content.SharedPreferences) does not support use across multiple processes. This will be added later.

Moreover in Mark L. Murphy book "beginning Android 2" he mentioned:

(Eventually, preferences might be shareable across applications, but that is not supported as of the time of this writing)

Im so confused! does this mean that MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE of getSharedPrefrences is there but NOT SUPPORTED YET in latest API level???"
Source : Here

2.2 Create object of Editor

Editor is interface declared inside the SharedPreference class. so that To access Editor class we need to write following syntax, "pref" is object of SharedPreference.

SharedPreferences.Editor edit = pref.edit();


2.2 Put value in SharedPreference

The following data types are supported by the SharedPreferences class:
  • Boolean values
  • Float values
  • Integer values
  • Long values
  • String values
Putting value in SharedPreference using Editor object is very simple, It's same as we are using Map Collection class. Here I put one value of each data type. 

           edit.putBoolean("Boolean_Value", true);
        edit.putFloat("Float_value", 12.5F);
        edit.putInt("Int_value", 500);
        edit.putLong("Long_Value", 1234567890);
        edit.putString("String_Value", "Hello SharedPreference");

SharedPreference is not support to put object inside it but If you can convert your object in String then It is possible. Support you want to store small image in SharedPreference then It is possible using Base64. just convert your image in Base64 and put it as String. but same technique is not possible with object of any class.

2.3 Commit the values

Commit your preferences changes back from this Editor to the SharedPreferences object it is editing. This atomically performs the requested modifications, replacing whatever is currently in the SharedPreferences.

        edit.commit();

Note that when two editors are modifying preferences at the same time, the last one to call commit wins.

If you don't care about the return value and you're using this from your application's main thread, consider using apply() instead.

2.4 Retrieving values


You don’t need an Editor to simply read preferences. Instead, retrieve the SharedPreferences object and use the appropriate method to retrieve a preference by name:


        boolean b = pref.getBoolean("Boolean_Value",false);
        float f = pref.getFloat("Float_Value", 0);
        int i = pref.getInt("Int_Value", 0);
        long l = pref.getLong("Long_Value", 0);
        String s = pref.getString("String_Value", "");


Each of these methods has two parameters: the preference key string and a default value to return if the preference is undefined.

2.5 Remove And Clear

Editor class has two method remove and clear. as name suggest it is used to remove specific key and clear is used to remove all values.

       // Remove value
        edit.remove("Boolean_Value");
        edit.commit();
        
        // Clear All value
        edit.clear();
        edit.commit();

2.5. Full Source Code


package com.kpbird.mysp;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;

public class MySP extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        // fetch object of SharedPreference
        SharedPreferences pref = getSharedPreferences("MyPref", MODE_PRIVATE);
        // Create object of Editor
        SharedPreferences.Editor edit = pref.edit();
        // Put values 
        edit.putBoolean("Boolean_Value", true);
        edit.putFloat("Float_value", 12.5F);
        edit.putInt("Int_value", 500);
        edit.putLong("Long_Value", 1234567890);
        edit.putString("String_Value", "Hello SharedPreference");
        // Commit the data
        edit.commit();
        
        
        //Retreive 
        boolean b = pref.getBoolean("Boolean_Value",false);
        float f = pref.getFloat("Float_Value", 0);
        int i = pref.getInt("Int_Value", 0);
        long l = pref.getLong("Long_Value", 0);
        String s = pref.getString("String_Value", "");
        
    }
}


continue reading Android InDepth : SharedPreference