Search This Blog

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 

Android News and source code