Search This Blog

Monday 23 December 2013

Android Contact Content Provider API : Adding a contact to android phone using ContentProviderOperation

I have gone through tough time while adding contact to contact book in android Contact ContentProvider using new ContentProviderOperation. After doing some work around i found solution and made one go utility function for all android developer. This function allow to add name, address, Note, Photo and Number to Contact Book .

Following Permission is required for adding and modifying Contact


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

Now this is Utility Function , just copy and paste it anywhere. It will return Contact_ID of newly added Contact


      public String addContact(Activity mAcitvity, String name, String address, String number, String mNote,Bitmap mPhoto) {  
           int contactID = -1;  
           ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();  
           int rawContactID = ops.size();  
           // Adding insert operation to operations list  
           // to insert a new raw contact in the table ContactsContract.RawContacts  
           ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)  
                .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null).withValue(RawContacts.ACCOUNT_NAME, null).build());  
           // Adding insert operation to operations list  
           // to insert display name in the table ContactsContract.Data  
           ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)  
                .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)  
                .withValue(ContactsContract.Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE).withValue(StructuredName.DISPLAY_NAME, name).build());  
           // Adding insert operation to operations list  
           // to insert Mobile Number in the table ContactsContract.Data  
           ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)  
                .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)  
                .withValue(ContactsContract.Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE).withValue(Phone.NUMBER, number)  
                .withValue(Phone.TYPE, CommonDataKinds.Phone.TYPE_MOBILE).build());  
           // Adding insert operation to operations list  
           // to insert Mobile Number in the table ContactsContract.Data  
           ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)  
                .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)  
                .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)  
                .withValue(ContactsContract.CommonDataKinds.StructuredPostal.STREET, address).build());  
           // Adding insert operation to operations list  
           // to insert Mobile Number in the table ContactsContract.Data  
           ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)  
                .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)  
                .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)  
                .withValue(ContactsContract.CommonDataKinds.Note.NOTE, mNote).build());  
     ByteArrayOutputStream stream = new ByteArrayOutputStream();  
     mPhoto.compress(CompressFormat.JPEG, 100, stream);  
     byte[] bytes = stream.toByteArray();  
           // Adding insert operation to operations list  
           // to insert Mobile Number in the table ContactsContract.Data  
           ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)  
                .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)  
                .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)  
                .withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, bytes).build());  
           try {  
                ContentResolver mResolver = mAcitvity.getContentResolver();  
                ContentProviderResult[] mlist = mResolver.applyBatch(ContactsContract.AUTHORITY, ops);  
                Uri myContactUri = mlist[0].uri;  
                int lastSlash = myContactUri.toString().lastIndexOf("/");  
                int length = myContactUri.toString().length();  
                contactID = Integer.parseInt((String) myContactUri.toString().subSequence(lastSlash + 1, length));  
           } catch (Exception e) {  
                e.printStackTrace();  
           }  
           return String.valueOf(contactID);  
      }  

Now See you can call this function from anywhere with respective values. Pass your own values and Bitmap


 addContact(this, "Sammer", "Delhi", "11-9090909", "Going to Meeting", BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher));  

See the output of function, this function is tested so do not worry while using


Contact API

Tuesday 17 December 2013

Handler vs Timer : fixed-period execution and fixed-rate execution android development

In Android Timer and Handler are both can be used for repetitive call. We can do same piece of task using either Timer or Handler (With runnable). First going to pros and cos of each we should look what documentation says about both. Its very important to avoid memory leak in android application

Timer Recurring tasks are scheduled with either a fixed period or a fixed rate:
  • With the default fixed-period execution, each successive run of a task is scheduled relative to the start time of the previous run, so two runs are never fired closer together in time than the specified period.
   • With fixed-rate execution, the start time of each successive run of a task is scheduled without regard for when the previous run took place. This may result in a series of bunched-up runs (one launched immediately after another) if delays prevent the timer from starting tasks on time.

Handler  

  • to schedule messages and runnables to be executed as some point in the future; and 
  • to enqueue an action to be performed on a different thread than your own.


Handler Implementation


  • How to create repetitive task using Handler

  Handler mHandler;
  public void useHandler() {
    mHandler = new Handler();
    mHandler.postDelayed(mRunnable, 1000);
  }

  private Runnable mRunnable = new Runnable() {

    @Override
    public void run() {
      Log.e("Handlers", "Calls");
      /** Do something **/
      mHandler.postDelayed(mRunnable, 1000);
    }
  };

  • How to remove pending execution from Handler

       mHandler.removeCallbacks(mRunnable);

  • How to schedule it again

      mHandler.postDelayed(mRunnable, 1000);


  • Where to perform Task

      Runnable works under UI thread so you can update UserInterface in Handler respective Runnable


Timer Implementation


  • How to create repetitive task using Timer

  public void useTimer() {
    Timer mTimer = new Timer();
    mTimer.cancel();
    mTimer.schedule(new TimerTask() {

      @Override
      public void run() {
        Log.e("Timer", "Calls");
      }
    }, 1000, 1000);
  }


  • How to remove pending execution from Timer

      mTimer.cancel(); will cancel all the schedule task.

  • How to schedule it again

        You can not reschedule Timer again. So you to create object of timer again if you are trying to reschedule its task.


Comparison Handler VS Timer


  • While rescheduling Handler is very easy, you can not reschedule Timer


  • In Handler you can attach to any Runnable but Timer schedule for only one TimerTask


  • TimerTask is purely background task so you can not update UserInterface, but that's not true for Handler's Runnables
Timer Cause Execption


  • Timer tends to leak more memory compare to Handler see the graph of object retains by timer and Handler. It will increase rapidly for Timer if you are creating and scheduling new task.

Handler Memory Graph

Timer Memory Graph
Which one to use Obviously i will recommend to use Handler with Runnable

Tuesday 3 December 2013

Showing pin radial progress bar during download android

This example is originally develop by Google Developer Roman Nurik and Nik Butcher. I lead to it more customization and make it easy to implement in android project.This Radial pin progress can be seen at Google play store in many project. This look very beautiful and classy.So lets develop it. Google developer create one custom class PinProgressButton which allows you some customization like color, theme according to your application.




PinProgressButton.Java which has attribute to customize it

 <resources>  
   <declare-styleable name="PinProgressButton">  
     <attr name="pinned" format="boolean" />  
     <attr name="progress" format="integer" />  
     <attr name="max" format="integer" />  
     <attr name="circleColor" format="color" />  
     <attr name="progressColor" format="color" />  
   </declare-styleable>  
 </resources>  

Pinpoint Progress Bar


Saturday 30 November 2013

Download file (Video/Audio/text) through android WebView

Android WebView happy go tool for cross development of android application like PhoneGap and jQuery mobile. Few days ago i found in situation where i need to download some file while clicking on button inside WebView . I search a lot on Google and found some solution which lead me to fix issue. StackOverflow plays an vital role in this. Now i upgrade my solution using download manager. DownloadManger will manage download automatically. Read communication between android and JavaScript

Permission required for this application

   <uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />  
   <uses-permission android:name="android.permission.INTERNET" />  
   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />  

You can download any kind of data through this code only you need to change your file extension.

Now create one WebView

           WebView webview = new WebView(this);  
           webview.setWebChromeClient(new WebChromeClient());  
           WebViewClient client = new ChildBrowserClient();  
           webview.setWebViewClient(client);  
           WebSettings settings = webview.getSettings();  
           settings.setJavaScriptEnabled(true);  
           webview.setInitialScale(1);  
           webview.getSettings().setUseWideViewPort(true);  
           settings.setJavaScriptCanOpenWindowsAutomatically(false);  
           settings.setBuiltInZoomControls(true);  
           settings.setPluginState(PluginState.ON);  
           settings.setDomStorageEnabled(true);  
           webview.loadUrl("yoursideurl");  
           webview.setId(5);  
           webview.setInitialScale(0);  
           webview.requestFocus();  
           webview.requestFocusFromTouch();  
           setContentView(webview);  

Most importantly WeViewClient allow you handle url and bypass them if they do not contain media(video/image)

      /**  
       * The webview client receives notifications about appView  
       */  
      public class ChildBrowserClient extends WebViewClient {  
           @SuppressLint("InlinedApi")  
           @Override  
           public boolean shouldOverrideUrlLoading(WebView view, String url) {  
                boolean value = true;  
                String extension = MimeTypeMap.getFileExtensionFromUrl(url);  
                if (extension != null) {  
                     MimeTypeMap mime = MimeTypeMap.getSingleton();  
                     String mimeType = mime.getMimeTypeFromExtension(extension);  
                     if (mimeType != null) {  
                          if (mimeType.toLowerCase().contains("video")  
                                    || extension.toLowerCase().contains("mov")  
                                    || extension.toLowerCase().contains("mp3")) {  
                               DownloadManager mdDownloadManager = (DownloadManager) DownloadWebview.this  
                                         .getSystemService(Context.DOWNLOAD_SERVICE);  
                               DownloadManager.Request request = new DownloadManager.Request(  
                                         Uri.parse(url));  
                               File destinationFile = new File(  
                                         Environment.getExternalStorageDirectory(),  
                                         getFileName(url));  
                               request.setDescription("Downloading via Your app name..");  
                               request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);  
                               request.setDestinationUri(Uri.fromFile(destinationFile));  
                               mdDownloadManager.enqueue(request);  
                               value = false;  
                          }  
                     }  
                     if (value) {  
                          view.loadUrl(url);  
                     }  
                }  
                return value;  
           }  
           @Override  
           public void onPageFinished(WebView view, String url) {  
                super.onPageFinished(view, url);  
           }  
           /**  
            * Notify the host application that a page has started loading.  
            *   
            * @param view  
            *      The webview initiating the callback.  
            * @param url  
            *      The url of the page.  
            */  
           @Override  
           public void onPageStarted(WebView view, String url, Bitmap favicon) {  
                super.onPageStarted(view, url, favicon);  
           }  
      }  
      /**  
       * File name from URL  
       *   
       * @param url  
       * @return  
       */  
      public String getFileName(String url) {  
           String filenameWithoutExtension = "";  
           filenameWithoutExtension = String.valueOf(System.currentTimeMillis()  
                     + ".mp4");  
           return filenameWithoutExtension;  
      }  

I had written the download Manage code their in above lines. In which you have to give your destination local file in which you want to save it.

Now look at the whole class code

 import java.io.File;  
 import android.annotation.SuppressLint;  
 import android.app.Activity;  
 import android.app.DownloadManager;  
 import android.content.Context;  
 import android.graphics.Bitmap;  
 import android.net.Uri;  
 import android.os.Bundle;  
 import android.os.Environment;  
 import android.webkit.MimeTypeMap;  
 import android.webkit.WebChromeClient;  
 import android.webkit.WebSettings;  
 import android.webkit.WebSettings.PluginState;  
 import android.webkit.WebView;  
 import android.webkit.WebViewClient;  
 public class DownloadWebview extends Activity {  
      @SuppressWarnings("deprecation")  
      @SuppressLint("SetJavaScriptEnabled")  
      @Override  
      protected void onCreate(Bundle savedInstanceState) {  
           super.onCreate(savedInstanceState);  
           WebView webview = new WebView(this);  
           webview.setWebChromeClient(new WebChromeClient());  
           WebViewClient client = new ChildBrowserClient();  
           webview.setWebViewClient(client);  
           WebSettings settings = webview.getSettings();  
           settings.setJavaScriptEnabled(true);  
           webview.setInitialScale(1);  
           webview.getSettings().setUseWideViewPort(true);  
           settings.setJavaScriptCanOpenWindowsAutomatically(false);  
           settings.setBuiltInZoomControls(true);  
           settings.setPluginState(PluginState.ON);  
           settings.setDomStorageEnabled(true);  
           webview.loadUrl("yoursideurl");  
           webview.setId(5);  
           webview.setInitialScale(0);  
           webview.requestFocus();  
           webview.requestFocusFromTouch();  
           setContentView(webview);  
      }  
      /**  
       * The webview client receives notifications about appView  
       */  
      public class ChildBrowserClient extends WebViewClient {  
           @SuppressLint("InlinedApi")  
           @Override  
           public boolean shouldOverrideUrlLoading(WebView view, String url) {  
                boolean value = true;  
                String extension = MimeTypeMap.getFileExtensionFromUrl(url);  
                if (extension != null) {  
                     MimeTypeMap mime = MimeTypeMap.getSingleton();  
                     String mimeType = mime.getMimeTypeFromExtension(extension);  
                     if (mimeType != null) {  
                          if (mimeType.toLowerCase().contains("video")  
                                    || extension.toLowerCase().contains("mov")  
                                    || extension.toLowerCase().contains("mp3")) {  
                               DownloadManager mdDownloadManager = (DownloadManager) DownloadWebview.this  
                                         .getSystemService(Context.DOWNLOAD_SERVICE);  
                               DownloadManager.Request request = new DownloadManager.Request(  
                                         Uri.parse(url));  
                               File destinationFile = new File(  
                                         Environment.getExternalStorageDirectory(),  
                                         getFileName(url));  
                               request.setDescription("Downloading via Your app name..");  
                               request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);  
                               request.setDestinationUri(Uri.fromFile(destinationFile));  
                               mdDownloadManager.enqueue(request);  
                               value = false;  
                          }  
                     }  
                     if (value) {  
                          view.loadUrl(url);  
                     }  
                }  
                return value;  
           }  
           @Override  
           public void onPageFinished(WebView view, String url) {  
                super.onPageFinished(view, url);  
           }  
           /**  
            * Notify the host application that a page has started loading.  
            *   
            * @param view  
            *      The webview initiating the callback.  
            * @param url  
            *      The url of the page.  
            */  
           @Override  
           public void onPageStarted(WebView view, String url, Bitmap favicon) {  
                super.onPageStarted(view, url, favicon);  
           }  
      }  
      /**  
       * File name from URL  
       *   
       * @param url  
       * @return  
       */  
      public String getFileName(String url) {  
           String filenameWithoutExtension = "";  
           filenameWithoutExtension = String.valueOf(System.currentTimeMillis()  
                     + ".mp4");  
           return filenameWithoutExtension;  
      }  
 }  



Monday 25 November 2013

how to disable nested ViewGroup's (RelativeLayout,LinearLayout etc) childs android

This is tutorial is a part android Utility functions, ViewGroup, View disable and enable

I created one function for disabling all View of any child whether its LinearLayout, RelativeLayout or anything. It will go through complete View Hierarchy and will disable all View contains inside parent. This function call recursive and work even if ViewGroup contains another ViewGroup too.
Enjoy by running it

    public void disableAllSettings(ViewGroup mGroup) {

        int itotal = mGroup.getChildCount();
        for (int i = 0; i < itotal; i++) {
            if (mGroup.getChildAt(i) instanceof ViewGroup) {
                disableAllSettings((ViewGroup) mGroup.getChildAt(i));
            } else {
                mGroup.getChildAt(i).setEnabled(false);
            }
        }
    }

Wednesday 20 November 2013

Working with Android KitKat 4.4 : Creating and using Eumlator for android KitKat 4.4


Update your android SDK to latest version. If required then update ADT plugin also to make it compatible with SDK. Android KitKat 4.4 refers to sdk version 19. Once you update your android SDK to Latest android release. you will get all the sample code and sample application which is launched in latest real ease.
Create any sample application from Android KitKat 4.4 using existing source code.
And now the issue is how to create eumlator for android KitKat 4.4, answer is easy just like you are creating till date. 
But Main trick is Use host GPU to be selected.
Now our mind will think what is host GPU, its clearly started at android documentation use GPU for hardware acceleration for your emulator, you can do it using command line after creating emulator but for Android KitKat do it while creating emulator


"If you want to have graphics acceleration enabled by default for this AVD, in the Hardware section, click New, selectGPU emulation and set the value to Yes."

Sunday 3 November 2013

Google Android KitKat 4.4 exploring new feature and update for developer in latest release



Google bring more powerful, more innovative android version KitKat 4.4. It went for release after many rumor and speculation.  Read Android KitKat 4.4’s feature forConsumers.

  • Google attempt to reach to billion in faster, smoother and responsive way


Keeping minimum requirement of RAM for 512 MB, was challenge for Google Android KitKat for running smoothly on lower memory devices. That lead to many memory optimization technique and process. Google Android KitKat 4.4 help you to create innovative, responsive and memory efficient application. Dalvik JIT code cache tuning, kernel samepage merging (KSM), swap to zRAM, and other optimizations help manage memory. New configuration options let OEMs tune out-of-memory levels for processes, set graphics cache sizes, control memory reclaim, and more.

“A new API, ActivityManager.isLowRamDevice(), lets you tune your app's behavior to match the device's memory configuration”  Google Android stated in documentation of KitKat

Protocol Tool and Meminfo tool is used to enhanced application memory utilization

  • Android 4.4 introduces new  platform  for secure NFC-based  transaction through  Host Card Emulation (HCE)


  •          New Framework for Printer  and storage  files

Printer cloud System
Android can print now any kind of content over Wi-Fi or cloud hosted service such Google cloud Print. Google gives manufacture as well as developer to add printing API. Client apps can use new APIs to add printing capabilities to their apps with minimal code changes. In most cases, you would add a print action to your Action Bar and a UI for choosing items to print.
New storage Framework allow you develop a client app that manages files or documents, you can integrate with the storage access framework just by using new CREATE_DOCUMENT or OPEN_DOCUMENT intents to open or create files — the system automatically displays the standard UI for browsing documents, including all available document providers. 

  • Low power sensors 

Android KitKat 4.4 introduces hardware sensor batching which is new optimization technique  which reduce power consumption.

Tools to beautification your app in new way :)

Full screen immerse mode to give user more space by disabling status bar notification and hardware button introduces in KitKat
Transitions framework will allow you to animate changes to your UI on the fly, without needing to define scenes. For example, you can make a series of changes to a view hierarchy and then have the TransitionManager automatically run a delayed transition on those changes. 
Translucent system UI styling and enhance notification access will help you to beautify your app and later will help you to enhance notification access

Graphics and render script  improve the performance compare to previous version

Just see comparison chart your self.
Now you can take advantage of RenderScript directly from your native code. A new C++ API in the Android Native Development Kit (NDK) lets you access the same RenderScript functionality available through the framework APIs, including script intrinsics, custom kernels, and more.




New type of connectivity and accessibility are other part which are introduces and improved.

New Media support and Memory analyzer tool are the other. New tool called procstats will help developer to analyze the memory resources your app uses, as well as the resources used by other apps and services running on the system.

Friday 1 November 2013

Android update : Android 4.4 Kitkat's release with new feature for android user

The buzz and rumors around the corner for Android, comes to and end and android 4.4 KitKat is available for android users. Google provide more polish design and improved performance(i.e part of every update) and new features. Some feature are exceptionally good for android users. Google giant speed up the process of bringing all android device to one O.S version.

Android KitKat has minimum hardware support to run with most of the android devices. Its support device with minimum of 512 MB of RAM memory, which make inclusion of 96 % of device in new android O.S version. Just few week ago iOS new version launched, its buggy reviews, increase the speculation about android awaited launch of KitKat 4.4.But like every time, Google delivered this time too :).

Android KitKat had some really nice feature for android user, Before discussing what's new for developer, i prefer android user first. After all they are our fate decider :).

Easy search Just say "OK Google" to start Google search API. Now you do not need to touch it. "OK Google" will launch the voice search, send text, get direction or play a song.

Go Google

Redefine Music "a work of art" While playing music or movies with chrome cast, user will see beautiful full screen album and movie art when device is locked. You can perform play, pause and seek.


Immerse yourself and improved multitasking while reading book, playing music, Google android KitKat provide you center stage with new immerse Mode with Notification bar and Navigation Button. Android KitKat take system performance to all time high to respond it without a hitch.


Contact, Calling and Messaging updates Android will work smartly to automatically prioritizes your contacts based on the people you talk to the most. You can also search for nearby places and businesses, your contacts, or people in your Google. All message are on one place and smaller caller ID are other features to look for. New Emoji are available for Google keyboard


Feature will force you to switch to KitKat


  • Printing from your device using any printer connected to Google Cloud Print, to HP ePrint and other printer that have apps in Google play
  • New file system which allow to save and open Google Drive files.


    New Android File Systen

  •  Create and Edit your document, spreadsheet and presentation using QuickOffice from any where

Statistics and fun fact About Android KitKat


- Nexus 5 is preloaded with Android KitKat, and will be the first device with android 4.4 KitKat
- Android KitKat expected to reach up to 1 billion android phones
- Android KitKat 4.0 will run on phone with RAM more than or equal to 512 MB


Source Of Information Android Official Website 

Monday 28 October 2013

ViewPager android Fact and constraint about offscreen page limit

ViewPager inbuilt swipe animation is very good. ViewPager exist for a reason with HorizontalScrollView(Which scroll the content in same manner but different methodologies). ViewPager used for swiping content on the base of keep ready next content to be swipe. And its whole limitation and strength, which developer feels some times, lie in that.

How many (i.e Minimum and Maximum) page of ViewPager may be preloaded?

setOffscreenPageLimit(1); decide how many page to be preloaded. As i am not sure about what is the maximum limit for it but minimum is 1. setting off screen page limit to 0 does nothing except throwing  warning in LogCat Requested offscreen page limit 0 too small; defaulting to 1Its because ViewPager is based on concept of keep ready next page to be loaded. ViewPager can not the page which not exist still. Android documentation of ViewPager clearly. But most developer feels its not what they required. Then you have option with some work around there but you can not change ViewPager behavior.

Some people argue that they want to load empty instance of fragment as part of child of ViewPager then later on full content. You are free to do  but you will be solely responsible to handle its complications.

onPageListner gives you a way but its bit of tricky to handle.


I absolutely agree with ViewPager's documentation. There must be some content exist before swiping it down. You can use an in out animation if you do not want to customize ViewPager. But being with Adapter, ViewPager allow you to recyling of View

Thursday 24 October 2013

Volley Android Networking Library : How to use Volley in your application and why?

In 2013 I/O Android session Ficus Kirkpatrick launched a new support for android developer. This is really cool library for networking operation.
If being android developer you stuck and searching for many question's answer related networking connection. Volley android sdk Gives the answer

Volley fixed these problems

1) All network requests happen serially
2) Rotating the screen will reload everything from the network
3) AsyncTasks stomp on recycled views
4) Compatibility problems on Froyo

Then curiously how's the documentation of android volley going to be !!Answer is Very simple

Volley Android library Implementation


Initializing Volley android before use anywhere in Constructer which called very first time


 // Somewhere common; app startup or adapter constructor  
 mRequestQueue = Volley.newRequestQueue(context);  
 mImageLoader = new ImageLoader(mRequestQueue, new BitmapLruCache());  

Making request to URL which gives Json Response


 mRequestQueue.add(new JsonObjectRequest(Method.GET, url, null,  
 new Listener<JSONObject>() {  
 public void onResponse(JSONObject jsonRoot) {  
 mNextPageToken = jsonGet(jsonRoot, "next", null);  
 List<Items> items = parseJson(jsonRoot);  
 appendItemsToList(item);  
 notifyDataSetChanged();  
 }  
 }  
 }  

Image Loading through volley contain two way

  •  Using ImageLoader class
 mImageLoader.get(image_url,imageView, R.drawable.loading, R.drawable.error);  
  • Using Volley Android Custom ImageView
 - <ImageView  
 + <com.android.volley.NetworkImageView  
 Java mImageView.setImageUrl(BASE_URL + item.image_url, mImageLoader);  

There are a lot more in Volley android. Download Sample and check them out

Monday 2 September 2013

Effective User experience Technique : Perfecting of data from online in android


Its just normal but effective technique based on a simple concept. While User listening song one, start fetching song two from server so that use do not need to for buffering of song two. It increase the data availability and application seems very fast.

Dev byte publish a video talk about this concept. Let have an example of NewsReader.
Developer can download news text, title etc to show to the user on instant base and shows to user. The sooner you provide the content to user, the more he will feel .


See this video and get the depth of Pre fetching technique, find out where it works best.




Android Battery Management API : Getting Battery Level and monitoring/determining its state programmatically using Battery Receiver

BatteryManager API exists in android to provide battery related function. It allow developer to develop application without draining battery of android user. Smart Developer never waste battery of android phone.
This tutorial teach you how to get current battery level of android phone and notify every time when battery level changes

Getting Current Battery Level

                IntentFilter mIntentFilter = new IntentFilter();  
                mIntentFilter.addAction(Intent.ACTION_BATTERY_LOW);  
                mIntentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);  
                mIntentFilter.addAction(Intent.ACTION_BATTERY_OKAY);  
                Intent batteryIntent = registerReceiver(null, mIntentFilter);  
                float batteryLevel = getBatteryLevel(batteryIntent);  
                Log.e("Battery Level", String.valueOf(batteryLevel));  

Creating Receiver for Observing/Monitoring Battery level changes


1) Create one Receiver and Register it with

      private class BatteryReceiver extends BroadcastReceiver {  
           @Override  
           public void onReceive(Context arg0, Intent arg1) {  
                if (arg1.getAction().equalsIgnoreCase(Intent.ACTION_BATTERY_LOW)  
                          || arg1.getAction().equalsIgnoreCase(  
                                    Intent.ACTION_BATTERY_CHANGED)  
                          || arg1.getAction().equalsIgnoreCase(  
                                    Intent.ACTION_BATTERY_OKAY)) {  
                     int level = arg1.getIntExtra("level", 0);  
                     Toast.makeText(BatteryManagerC.this,  
                               "Current Battery " + level + " %", Toast.LENGTH_LONG)  
                               .show();  
                     mTextView  
                               .setText(String  
                                         .valueOf("Battery Level Change Detect through Receiver = "  
                                                   + level));  
                }  
           }  
      }  

2) Register it for Significant changes of battery level


      BatteryReceiver mArrow;  
      private class ThreadM implements Runnable {  
           @Override  
           public void run() {  
                mArrow = new BatteryReceiver();  
                IntentFilter mIntentFilter = new IntentFilter();  
                mIntentFilter.addAction(Intent.ACTION_BATTERY_LOW);  
                mIntentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);  
                mIntentFilter.addAction(Intent.ACTION_BATTERY_OKAY);  
                Intent batteryIntent = registerReceiver(mArrow, mIntentFilter);  
                batteryLevel = getBatteryLevel(batteryIntent);  
                Log.e("Battery Level", String.valueOf(batteryLevel));  
           }  
      }  

Complete code for listening and getting Battery level will be like this


 package com.test;  
 import android.app.Activity;  
 import android.content.BroadcastReceiver;  
 import android.content.Context;  
 import android.content.Intent;  
 import android.content.IntentFilter;  
 import android.os.BatteryManager;  
 import android.os.Bundle;  
 import android.util.Log;  
 import android.view.View;  
 import android.view.View.OnClickListener;  
 import android.widget.TextView;  
 import android.widget.Toast;  
 public class BatteryManagerC extends Activity {  
      TextView mTextView;  
      @Override  
      protected void onCreate(Bundle savedInstanceState) {  
           super.onCreate(savedInstanceState);  
           setContentView(R.layout.main);  
           mTextView = (TextView) findViewById(R.id.batterTest);  
           findViewById(R.id.getBattery).setOnClickListener(new OnClickListener() {  
                @Override  
                public void onClick(View v) {  
                     mTextView.setText(String.valueOf(batteryLevel));  
                }  
           });  
           new Thread(new ThreadM()).start();  
      }  
      @Override  
      protected void onDestroy() {  
           super.onDestroy();  
           unregisterReceiver(mArrow);  
      }  
      BatteryReceiver mArrow;  
      private class ThreadM implements Runnable {  
           @Override  
           public void run() {  
                mArrow = new BatteryReceiver();  
                IntentFilter mIntentFilter = new IntentFilter();  
                mIntentFilter.addAction(Intent.ACTION_BATTERY_LOW);  
                mIntentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);  
                mIntentFilter.addAction(Intent.ACTION_BATTERY_OKAY);  
                Intent batteryIntent = registerReceiver(mArrow, mIntentFilter);  
                batteryLevel = getBatteryLevel(batteryIntent);  
                Log.e("Battery Level", String.valueOf(batteryLevel));  
           }  
      }  
      float batteryLevel;  
      private class BatteryReceiver extends BroadcastReceiver {  
           @Override  
           public void onReceive(Context arg0, Intent arg1) {  
                if (arg1.getAction().equalsIgnoreCase(Intent.ACTION_BATTERY_LOW)  
                          || arg1.getAction().equalsIgnoreCase(  
                                    Intent.ACTION_BATTERY_CHANGED)  
                          || arg1.getAction().equalsIgnoreCase(  
                                    Intent.ACTION_BATTERY_OKAY)) {  
                     int level = arg1.getIntExtra("level", 0);  
                     Toast.makeText(BatteryManagerC.this,  
                               "Current Battery " + level + " %", Toast.LENGTH_LONG)  
                               .show();  
                     mTextView  
                               .setText(String  
                                         .valueOf("Battery Level Change Detect through Receiver = "  
                                                   + level));  
                }  
           }  
      }  
      public float getBatteryLevel(Intent batteryIntent) {  
           int level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);  
           int scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);  
           if (level == -1 || scale == -1) {  
                return 50.0f;  
           }  
           return ((float) level / (float) scale) * 100.0f;  
      }  
 }  

Finding the Charging State of Battery

      public void determineChargingState() {  
           IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);  
           Intent batteryStatus = registerReceiver(null, ifilter);  
           // Are we charging / charged?  
           int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);  
           boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING  
                     || status == BatteryManager.BATTERY_STATUS_FULL;  
           // How are we charging?  
           int chargePlug = batteryStatus.getIntExtra(  
                     BatteryManager.EXTRA_PLUGGED, -1);  
           boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;  
           boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;  
      }  

Monday 26 August 2013

ShareActionProvider implementation in android newest version

Action Bar comes under standard design pattern of Android. ShareActionProvider is another easy step to implement Action Bar if we need to share some Intent with other application installed in the device.
ShareActionProvider introduce by android team in Android version 4.0 and above and this does not support any backward compatibility.
So lets create one simple demo of ShareActionProvider.

1) Update you menu file to create ShareActionProvider

 <menu xmlns:android="http://schemas.android.com/apk/res/android" >  
   <item  
     android:id="@+id/menu_item_share"  
     android:actionProviderClass="android.widget.ShareActionProvider"  
     android:showAsAction="ifRoom"  
     android:title="Share"/>  
 </menu>  

2) Update your MainActivity to create ShareActionProvider

 public class MainActivity extends Activity {  
      @Override  
      protected void onCreate(Bundle savedInstanceState) {  
           super.onCreate(savedInstanceState);  
           setContentView(R.layout.activity_main);  
      }  
      private ShareActionProvider mShareActionProvider;  
      @Override  
      public boolean onCreateOptionsMenu(Menu menu) {  
           // Inflate menu resource file.  
           getMenuInflater().inflate(R.menu.main, menu);  
           // Locate MenuItem with ShareActionProvider  
           MenuItem item = menu.findItem(R.id.menu_item_share);  
           // Fetch and store ShareActionProvider  
           mShareActionProvider = (ShareActionProvider) item.getActionProvider();  
           setShareIntent(createShareIntent());  
           // Return true to display menu  
           return true;  
      }  
      // Call to update the share intent  
      private void setShareIntent(Intent shareIntent) {  
           if (mShareActionProvider != null) {  
                mShareActionProvider.setShareIntent(shareIntent);  
           }  
      }  
      private Intent createShareIntent() {  
           Intent shareIntent = new Intent(Intent.ACTION_SEND);  
           shareIntent.setType("text/plain");  
           shareIntent.putExtra(Intent.EXTRA_TEXT,  
                     "http://androidtrainningcenter.blogspot.in");  
           return shareIntent;  
      }  
 }  

3) Let see how we create an intent to share with other application

      private Intent createShareIntent() {  
           Intent shareIntent = new Intent(Intent.ACTION_SEND);  
           shareIntent.setType("text/plain");  
           shareIntent.putExtra(Intent.EXTRA_TEXT,  
                     "http://androidtrainningcenter.blogspot.in");  
           return shareIntent;  
      }  




Source

http://developer.android.com/training/sharing/shareaction.html

Monday 19 August 2013

Getting List of non system application from Android phone

Getting all application list from android phone is quite easy. PackageManger gives the list of all installed application. But main concern remain how to avoid system from the list. I have done this job and prepare a piece of code to implement this functionality in an easiest way.
I keep filter to avoid non system application.

Filter to avoid Non System Application
           private boolean isSystemPackage(ApplicationInfo pkgInfo) {  
                int mask = ApplicationInfo.FLAG_SYSTEM  
                          | ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;  
                return (pkgInfo.flags & mask) == 0;  
           }  

GetallApTest .Java will find all system app in background and will give you the list
 import java.util.ArrayList;  
 import java.util.List;  
 import android.app.Activity;  
 import android.app.ProgressDialog;  
 import android.content.pm.ApplicationInfo;  
 import android.content.pm.PackageInfo;  
 import android.content.pm.PackageManager.NameNotFoundException;  
 import android.os.AsyncTask;  
 import android.os.Bundle;  
 import android.util.Log;  
 import com.eurotronik.isenior.myMenu.MyAppData;  
 public class GetallApTest extends Activity {  
      @Override  
      protected void onCreate(Bundle savedInstanceState) {  
           super.onCreate(savedInstanceState);  
           AndroidApplication mAsAndroidApplication = new AndroidApplication();  
           mAsAndroidApplication.execute();  
      }  
      private class AndroidApplication extends  
                AsyncTask<Void, ArrayList<MyAppData>, ArrayList<MyAppData>> {  
           ProgressDialog pd;  
           @Override  
           protected void onPreExecute() {  
                super.onPreExecute();  
                pd = new ProgressDialog(GetallApTest.this);  
                pd.setMessage("Loadin...");  
                pd.setCancelable(false);  
                pd.show();  
           }  
           @Override  
           protected ArrayList<MyAppData> doInBackground(Void... params) {  
                ArrayList<MyAppData> res = new ArrayList<MyAppData>();  
                List<PackageInfo> packs = getPackageManager().getInstalledPackages(  
                          0);  
                for (int i = 0; i < packs.size(); i++) {  
                     PackageInfo p = packs.get(i);  
                     try {  
                          ApplicationInfo ai = getPackageManager()  
                                    .getApplicationInfo(p.packageName, 0);  
                          if ((!isSystemPackage(ai))) {  
                               Log.e("Skip", "App");  
                               continue;  
                          }  
                     } catch (NameNotFoundException e) {  
                          e.printStackTrace();  
                     }  
                     MyAppData newInfo = new MyAppData();  
                     newInfo.setName(p.applicationInfo  
                               .loadLabel(getPackageManager()).toString());  
                     newInfo.setImage(p.applicationInfo  
                               .loadIcon(getPackageManager()));  
                     res.add(newInfo);  
                }  
                return res;  
           }  
           private boolean isSystemPackage(ApplicationInfo pkgInfo) {  
                int mask = ApplicationInfo.FLAG_SYSTEM  
                          | ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;  
                return (pkgInfo.flags & mask) == 0;  
           }  
           @Override  
           protected void onProgressUpdate(ArrayList<MyAppData>... values) {  
                super.onProgressUpdate(values);  
                pd.dismiss();  
                /**  
                 * List OF app  
                 */  
                ArrayList<MyAppData> mList = values[0];  
           }  
      }  
 }  

Thursday 25 July 2013

Android Action Bar backward compatibility support in lower version of android O.S

While following android design patterns, Action bar is an important factor in it. Unfortunately Action bar was not supported in lower version than 3.0. Which was very painful for developer because still android 2.3.3 has fair amount of share in android market. So developers were forced to use Sherlock ActionBar and others
But Good news is , we no more need to rely on third party library for support of Action Bar in lower version from July 2013.
Google Android has provided their native support for backward android version as part of new latest update.
Even Though i  have not gone through this API but seems very very helpful.

Android Support Library, revision 18 (July 2013)


This library will remove the developer pain of Action bar support. I feels that because of its limited support developer can not use Action Bar in latest version also. As using Action Bar and third party Action Bar was very hectic and it lead to great effort with no good result.
Upto now We should thank Sherlock Actionbar. They made one excellent productive library

Soon i am going to post of using this library in our own application. 

New features in Android 4.3 Jelly Bean for developer perspective

Yesterday the most awaited update goes on public of android Jelly bean. Everyone was anticipating new update from Google android. Even next version Key Pie Lime also seems to be in Queue. But having this strong update helps a lot for developer and end of day to user
Lets have a look on some new  feature

Faster smoother and More Responsive
Every android update start from this. But really google worked hard to improve the responsiveness of android which already very good. Actual effect will be realize after update only.  Google says Android 3.0 build on a performance improvement included in Jelly Bean - Vsync timing, triple buffering and reduce latency, CPU input boost. 
4.3 improved windows buffer allocation which result in faster image buffer allocation and reduce time in rendering 

Your application May misbehave 
if your app uses implicit intents..
  Because of restricted profile update environment, your application may mis behave so go to android     developer to make it correct.
if your app depends on accounts for the same above reason


Restricted Profile environment 
Any accounts added to the primary user are available to a restricted profile, but the accounts are not accessible from the Account Manager APIs by default. If you attempt to add an account with Account Manager while in a restricted profile, you will get a failure result

Wireless and Connectivity Update
4.3 version allow many wireless and connectivity updates. Android now supports Bluetooth Blow Energy with new API. Wifi Scan only mode allow user to obtain correct location without draining 
battery.


Multimedia Updates

MediaExtractor and MediaCodec has been enhance on great level to support developer. Media DRM is another update from android 4.3 Jelly Bean. Video encoding from a surface  are the topic need to be explore by android developer

Some User interface has been added like ViewGroupOver and Optical bound layout. Some screen orientation has been added. TV scan support are excellent now. Improved support of accessibility services and Notification manager

Some new language are added in localization like Hindi etc

Reference for Information and Images


Monday 22 July 2013

Sound Pool Tutorial in Android : changing pitch of an sound file

SoundPool provide a frequency range to change the pitch of voice. This tutorial address the sound pool features. After reading this tutorial you will be able to answer these question

1) What is soundPool?
2) Why we use it?
3) How to change pitch of sound file through frequency?

How to prepare a simple sound Pool?


Sound Pool : A SoundPool is a collection of samples that can be loaded into memory from a resource inside the APK or from a file in the file system. The SoundPool library uses the MediaPlayer service to decode the audio into a raw 16-bit PCM mono or stereo stream. This allows applications to ship with compressed streams without having to suffer the CPU load and latency of decompressing during playback.

Creating simple sound pool with one sound file. Keep your sound file inside raw folder

SoundPool soundPool = new SoundPool(50, AudioManager.STREAM_MUSIC, 0);

50 is the number of repeat cycle, 0 is srcquality

Now load one sound file and wait until load finish using OnLoadCompleteListener.

        /** Sound ID for Later handling of sound pool **/
        soundId = soundPool.load(this, R.raw.sounds, 1);
        soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
            @Override
            public void onLoadComplete(SoundPool arg0, int arg1, int arg2) {
                streamId = soundPool.play(soundId, 1, 1, 1, 3, pitch);
                soundPool.setLoop(streamId, -1);
                Log.e("TAG", String.valueOf(streamId));
            }
        });

This tutorial has two button two increase and decrease frequency rate. Just See the complete code

XML


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".PitchActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="147dp"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/plus"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_marginLeft="147dp"
        android:layout_marginTop="35dp"
        android:text="+" />

    <Button
        android:id="@+id/minus"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/plus"
        android:layout_below="@+id/plus"
        android:layout_marginTop="41dp"
        android:text="-" />

</RelativeLayout>

Activity


package com.pitch;

import android.app.Activity;
import android.media.AudioManager;
import android.media.SoundPool;
import android.media.SoundPool.OnLoadCompleteListener;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

public class PitchActivity extends Activity implements OnClickListener {
    TextView mtxView;
    SoundPool soundPool;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pitch);
        mtxView = (TextView) findViewById(R.id.textView1);
        mtxView.setText("Current Pitch=0.5");
        findViewById(R.id.plus).setOnClickListener(this);
        findViewById(R.id.minus).setOnClickListener(this);
        setVolumeControlStream(AudioManager.STREAM_MUSIC);
        soundPool = new SoundPool(50, AudioManager.STREAM_MUSIC, 0);
        /** Sound ID for Later handling of sound pool **/
        soundId = soundPool.load(this, R.raw.sounds, 1);
        soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
            @Override
            public void onLoadComplete(SoundPool arg0, int arg1, int arg2) {
                streamId = soundPool.play(soundId, 1, 1, 1, 3, pitch);
                soundPool.setLoop(streamId, -1);
                Log.e("TAG", String.valueOf(streamId));
            }
        });
    }

    int streamId = 0;
    int soundId = -1;
    float pitch = 01f;

    @Override
    public void onClick(View arg0) {
        switch (arg0.getId()) {
        case R.id.minus:
            pitch -= 0.5;
            mtxView.setText("Current Pitch=" + pitch);
            soundPool.setRate(streamId, pitch);
            break;
        case R.id.plus:
            pitch += 0.5;
            mtxView.setText("Current Pitch=" + pitch);
            soundPool.setRate(streamId, pitch);
            break;
        default:
            break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            soundPool.pause(streamId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}



Important Points : your file not be bigger than 32 because Android Audio Framework allows only 32 tracks(includes playing/stopped/paused/...) per mixer thread at the same time. If it exceed then you will get error code -12

AudioFlinger could not create track, status: -12
Error creating AudioTrack

Reference Link

Android Developer

Android News and source code