Showing posts with label Advance Android. Show all posts
Showing posts with label Advance Android. Show all posts

Monday, February 17, 2014

Android FTP client tutorial with example of uploading, downloading and authentication with FTP server

FTP protocol is standard network protocol for transferring file. It works on peer to peer base network. In recent days I had written few articles about file transfer protocol and comparison among them to choose best. After research, research shows that FTP outperformed everything in android. So I decide to write about FTP client implementation. This tutorial will teach you
  • Android FTP client Authentication - How to connect with FTP server?
  • Android FTP client Download - How to download a file from FTP server?
  • Android FTP client Upload -How to upload a file to FTP server?

Basic requirement for this tutorial is one simple FTP server setup at your desktop. You can use file-Zilla or IIS server for this requirement.

  • Android FTP client authentication and listing file from FTP server

      /**  
*
* @param ip
* @param userName
* @param pass
*/
public void connnectingwithFTP(String ip, String userName, String pass) {
boolean status = false;
try {
FTPClient mFtpClient = new FTPClient();
mFtpClient.setConnectTimeout(10 * 1000);
mFtpClient.connect(InetAddress.getByName(ip));
status = mFtpClient.login(userName, pass);
Log.e("isFTPConnected", String.valueOf(status));
if (FTPReply.isPositiveCompletion(mFtpClient.getReplyCode())) {
mFtpClient.setFileType(FTP.ASCII_FILE_TYPE);
mFtpClient.enterLocalPassiveMode();
FTPFile[] mFileArray = mFtpClient.listFiles();
Log.e("Size", String.valueOf(mFileArray.length));
}
} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

  • Android FTP client download a file from FTP server – you can browse through directory saved on FTP server and can download desired file or directory. I just write code here for downloading a single file and writing it to sdcard/phone memory.

      /**  
* @param ftpClient FTPclient object
* @param remoteFilePath FTP server file path
* @param downloadFile local file path where you want to save after download
* @return status of downloaded file
*/
public boolean downloadSingleFile(FTPClient ftpClient,
String remoteFilePath, File downloadFile) {
File parentDir = downloadFile.getParentFile();
if (!parentDir.exists())
parentDir.mkdir();
OutputStream outputStream = null;
try {
outputStream = new BufferedOutputStream(new FileOutputStream(
downloadFile));
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
return ftpClient.retrieveFile(remoteFilePath, outputStream);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return false;
}

For browsing through directory see this Browsing Nested Directory

  • Android FTP client uploading a file to FTP server – You can upload a file to server with object of FTPClient at desired path which you need to define.

      /**  
*
* @param ftpClient FTPclient object
* @param downloadFile local file which need to be uploaded.
*/
public void uploadFile(FTPClient ftpClient, File downloadFile,String serverfilePath) {
try {
FileInputStream srcFileStream = new FileInputStream(downloadFile);
boolean status = ftpClient.storeFile("remote ftp path",
srcFileStream);
Log.e("Status", String.valueOf(status));
srcFileStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}

Download Jar  

 

Note : Keep all methods inside background thread (i.e Asynchronous Task, Service)

 See Sambha file sharing client for android

Wednesday, February 12, 2014

Best file transfer protocol : Which to use among SMB, Socket (TCP/UDP) and FTP?



I had gone through the requirement of file transfer using peer to peer in a same network. I tried the case of server and client too because I had not any issue to run server script (in case of Socket Connection). Main purpose was to attain maximum transfer speed of data. So I tried with three most popular protocols for file transfers which are –
  • SMB – Server Message Protocols known also as sambha file sharing
  • Socket- Work on the base of client server concept
  • FTP- File transfer protocol

Comparison for performance –


Phone
Protocol
Data
Distance
Time
Max Speed
XOLO
Socket
1.3 GB
5 Meter
16 Min
1.3 MB/S
XOLO
SMB
0.7 GB
5 Meter
25 Min
0.5 MB/S
XOLO
FTP
1.3 GB
5 Meter
14 Min
1.6 MB/S

Notable Point about file transfer protocols –

  • Socket – Server scripting required for file transfer. This connection cannot be named as peer to peer
  • SMB – No scripting required for file transfer. It can read any file structure of peer computer
  • FTP FileZilla can do the trick for file transfer. No Server script required

Term and Condition – These all testing has been done between an android and a low configuration desktop (Windows 7). Both were connected to one dedicated wifi local network



Sunday, February 9, 2014

Android sambha/ JSIFS file sharing example and source code

Look at ES File explorer functionality of connecting to peer computer (either android or Desktop) and reading file structure of that device on your own device to copy content. I just implemented this functionality using SMB file sharing system in android. I will explain with source code and example. You can connect to any peer computer using its IP and password. It will allow you to read full directory of this computer. This process is called peer to peer connection.

  • Why to use Sambha File Sharing system


           For making file sharing system like ES Android file explorer which connect peer device on LAN

You will need IP and Password of that peer which you want to connect through SMB file transfer system.
Connecting android with peer using SMB file sharing -

      public void connectingWithSmbServer() {  
try {
String yourPeerPassword = "administrator";
String yourPeerName = "abcd1234";
String yourPeerIP = "192.168.1.3";
String path = "smb://" + yourPeerIP;
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(
null, yourPeerName, yourPeerPassword);
Log.e("Connected", "Yes");
SmbFile smbFile = new SmbFile(path, auth);
/** Printing Information about SMB file which belong to your Peer **/
String nameoffile = smbFile.getName();
String pathoffile = smbFile.getPath();
Log.e(nameoffile, pathoffile);
} catch (Exception e) {
e.printStackTrace();
Log.e("Connected", e.getMessage());
}
}

Once you connected you can browse through the file system easily and you can download any file from peer to android sdcards. Once see below code to download file from peer to android sdcard using SMB file sharing system -

      public void downloadFileFromPeerToSdcard(File mLocalFile, SmbFile mFile) {  
try {
SmbFileInputStream mFStream = new SmbFileInputStream(mFile);
mLocalFile = new File(Environment.getExternalStorageDirectory(),
mFile.getName());
FileOutputStream mFileOutputStream = new FileOutputStream(
mLocalFile);
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = mFStream.read(buffer)) > 0) {
mFileOutputStream.write(buffer, 0, len1);
}
mFileOutputStream.close();
mFStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
Log.e("MalformURL", e.getMessage());
} catch (SmbException e) {
e.printStackTrace();
Log.e("SMBException", e.getMessage());
} catch (Exception e) {
e.printStackTrace();
Log.e("Exception", e.getMessage());
}
}

Note : Keep all methods inside background thread (i.e Asynchronous Task, Service)


You need to add one JSIFS Sambha jar file. Enjoy


Friday, January 31, 2014

Starting Developing application with android Studio is fun or Pain !

Android launched new android development environment  few months ago, is known as android studio based on Intelli J IDEA. This development tool is in early stage of preview. You can make android application using this tool too.

What android studio right away offer -

  •         Gradle-based build support.
  •         Android-specific refactoring and quick fixes.
  •         Lint tools to catch performance, usability, version compatibility and other problems.
  •         ProGuard and app-signing capabilities.
  •         Template-based wizards to create common Android designs and components.
  •         A rich layout editor that allows you to drag-and-drop UI components, preview layouts on  multiple screen configurations, and much more.
  •         Built-in support for Google Cloud Platform, making it easy to integrate Google Cloud Messaging and App Engine as server-side components.
See android developer guide installing and setup environment. Android Studio is a promising tool which will going to be more stable and useful in coming release. I just goes through google and find out benefits and constraint of Intelli J IDEA, Android studio

Benefits 


  •   All benefit which you read in first heading, will get you right away
  •  You can import your existing android project inside android studio
  •   Look modern compare to eclipse, more responsive  and integrated plugin like ADB and sdk Manager.

 

Should we go for it?

 

Yes go for it and learn it, but do not use fully as its in early stage of development and little unstable. With few more release you can directly start development. There is no place in which android studio lack compare to eclipse

 

See some screenshot of android studio while creating an new project


Home Android Studio

First Project Screen


Wednesday, January 29, 2014

Super User Android : How to do changes in system app in rooted device

If you rooted your device than you have complete control on how it looks and works. You can modify setting look and feel, you can remove setting option completely. In rooted device you got access to system app which control whole android device.

This concept run around that every application (i.e Settings, Contact etc) has one apk installed in one specific directory called /system/app. What we need to do just grab the source code for which we want to modify and create your own apk and finally replace it with existing system apk. After rebooting device your new changes will reflect on android device.

Lets do it in steps. I did it for Setting.apk. I grab the source code of Setting application from Git Hub directory. and i did some change and then replace it.

Step 1) Grab source code of application in which you want to change. Make changes and prepare one APK.

Step 2)  Now we need to install APK into system directory
  
  • Connect device with ADB command and push apk to  SD card
            $ adb push  /Setting.apk  /sdcard/  
  • Enter into shell
            $ adb shell
  • Now switch to super user
             $ su
  • Grab write permission to push apk
             $ mount -o remount,rw -t yaffs2 /dev/block/mtdblock3 /system
  • push your apk to root
             $ cat /sdcard/Setting.apk > /system/app/Setting.apk
  • Remount /system partition back to READ-ONLY and reboot device
             $ mount -o remount,ro -t yaffs2 /dev/block/mtdblock3 /system
             $ exit


Done !! you had changes in to android o.s configuration. Leave your comments


 

Tuesday, January 28, 2014

Google Glass application development : How and why to start being an android developer


Google Glass is a wearable computer with an optical head-mounted display (OHMD) that is being developed by Google in the Project Glass research and development project, with a mission of producing a mass-market ubiquitous computer.Google Glass displays information in a smartphone-like hands-free format, that can communicate with the Internet via natural language voice commands.

How to start development of Google Glass application

This is ambitious project of Google and Google has marketed well among user. The best thing about Google is it kept as simple as possible for developer. Existing android developer can male Google Glass application easily. Google Android provide GDK(Glass Development Kit) which can be added as add-on  to Android SDK.



You will feel like working for android in same environment for Google Glasses. Its exceptionally similar until you go for testing your application.


Developer need Google Glasses in real to test and deploy. First link to start development is Start Google Glass Development

How to distribute Google Glass application

Google provide Glass Play Store  to deploy and upload Google Glass application for commercially and non commercially uses.

Why to work Google Glass application? What is scope ?

Even being criticize by some, Google Glasses have tremendous  opportunity in Medical, Education and Gaming. Virtual Reality and Augmented Reality are concept which can be best capitalize in real life using Google Glass so called wearable computer. For developer, Its a new challenge with full of scope. If you are already develop android application then jump to make an application for Google Glasses.

Friday, January 24, 2014

Hack trick : Endless ViewPager example in android

I was trying to implement endless ViewPager, Suddenly a thought strike my mind and develop this tutorial which damn simple to integrate with any kind of adapter. I just showed here with ViewPager.

MainConcept


Return infinite value in getCount() and then take your own position to display values.


Support


Its support in every version of android. Look at output



So lets have a look of code which lead to an endless ViewPager in android application

Step 1) Take one array of Image which will be show in ViewPager elements. Change your MainActivity code to as follows

package com.fragmentpageradapter;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;

public class MainActivity extends FragmentActivity {
ViewPager mPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPager = (ViewPager) findViewById(R.id.frame);
mPager.setOffscreenPageLimit(1);
mPager.setAdapter(new EndLessAdapter(this, mImageArray));
}

private int[] mImageArray = { R.drawable.a, R.drawable.a1, R.drawable.a2,
R.drawable.a3 };
}


Step 2) Create one simple layout for MainActivity which contain one ViewPager

<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=".MainActivity" >

<android.support.v4.view.ViewPager
android:id="@+id/frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true" >
</android.support.v4.view.ViewPager>

</RelativeLayout>

Step 3) Create one PagerAdapter name EndLessAdapter

package com.fragmentpageradapter;

import android.os.Parcelable;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;

public class EndLessAdapter extends PagerAdapter {

FragmentActivity activity;
int imageArray[];

public EndLessAdapter(FragmentActivity act, int[] imgArra) {
imageArray = imgArra;
activity = act;
}

public int getCount() {
return Integer.MAX_VALUE;
}

private int pos = 0;

public Object instantiateItem(View collection, int position) {

ImageView mwebView = new ImageView(activity);
((ViewPager) collection).addView(mwebView, 0);
mwebView.setScaleType(ScaleType.FIT_XY);
mwebView.setImageResource(imageArray[pos]);

if (pos >= imageArray.length - 1)
pos = 0;
else
++pos;

return mwebView;
}

@Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}

@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}

@Override
public Parcelable saveState() {
return null;
}

}

What make it endless

    public int getCount() {
return Integer.MAX_VALUE;
}

Now you will start unrelated position so implement your own way of attaching data to ViewPager child.

    private int pos = 0;

public Object instantiateItem(View collection, int position) {

ImageView mwebView = new ImageView(activity);
((ViewPager) collection).addView(mwebView, 0);
mwebView.setScaleType(ScaleType.FIT_XY);
mwebView.setImageResource(imageArray[pos]);

if (pos >= imageArray.length - 1)
pos = 0;
else
++pos;

return mwebView;
}


Memory Issue : Because ViewPager keep one child at each side so this solution work without any memory issue. If you are going to implement same solution for ListView then you may get memory issue as all row kept inside memory


Monday, December 23, 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, December 17, 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, December 3, 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, November 30, 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;
}
}



Sunday, November 3, 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.
Posting Lama ►
 

Copyright 2013 Tutorials For Newbie: Advance Android Template by CB Blogger Template. Powered by Blogger