Wednesday, September 12, 2012

Download an Image or Any HTTP file to SDcard with progress notification


try {
        //set the download URL, a url that points to a file on the internet
        //this is the file to be downloaded
        URL url = new URL("http://somewhere.com/some/webhosted/file");

        //create the new connection
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        //set up some things on the connection
        urlConnection.setRequestMethod("GET");
        urlConnection.setDoOutput(true);

        //and connect!
        urlConnection.connect();

        //set the path where we want to save the file
        //in this case, going to save it on the root directory of the
        //sd card.
        File SDCardRoot = Environment.getExternalStorageDirectory();
        //create a new file, specifying the path, and the filename
        //which we want to save the file as.
        File file = new File(SDCardRoot,"somefile.ext");

        //this will be used to write the downloaded data into the file we created
        FileOutputStream fileOutput = new FileOutputStream(file);

        //this will be used in reading the data from the internet
        InputStream inputStream = urlConnection.getInputStream();

        //this is the total size of the file
        int totalSize = urlConnection.getContentLength();
        //variable to store total downloaded bytes
        int downloadedSize = 0;

        //create a buffer...
        byte[] buffer = new byte[1024];
        int bufferLength = 0; //used to store a temporary size of the buffer

        //now, read through the input buffer and write the contents to the file
        while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
                //add the data in the buffer to the file in the file output stream (the file on the sd card
                fileOutput.write(buffer, 0, bufferLength);
                //add up the size so we know how much is downloaded
                downloadedSize += bufferLength;
                //this is where you would do something to report the prgress, like this maybe
                updateProgress(downloadedSize, totalSize);

        }
        //close the output stream when done
        fileOutput.close();
//catch some possible errors...
} catch (MalformedURLException e) {
        e.printStackTrace();
} catch (IOException e) {
        e.printStackTrace();
}

Thursday, September 6, 2012

How to install Java in Ubuntu step by step

How to install java jdk on ubuntu (linux)

How to install java jdk on Ubuntu? here i provide few steps to demonstrate how it’s work.

Installation Setup

1. Issue following command to find out current jdk version in apt-get
 
apt-cache search jdk
 
2. Install java JDK and JRE with apt-get install

apt-get install sun-java6-jdk sun-java6-jre
 
3. Ubuntu will auto download necessary file from web for installation.


Do you want to continue [Y/n]? y
Get:1 http://my.archive.ubuntu.com hardy/main java-common 0.28ubuntu3 [78.2kB]
Get:2 http://my.archive.ubuntu.com hardy/multiverse sun-java6-jre 6-06-0ubuntu1 [6334kB]
Get:3 http://my.archive.ubuntu.com hardy/main odbcinst1debian1 2.2.11-16build1 [66.2kB]
Get:4 http://my.archive.ubuntu.com hardy/main unixodbc 2.2.11-16build1 [289kB]
Get:5 http://my.archive.ubuntu.com hardy/multiverse sun-java6-bin 6-06-0ubuntu1 [27.3MB] 
Get:6 http://my.archive.ubuntu.com hardy/multiverse sun-java6-jdk 6-06-0ubuntu1 [9625kB] 
85% [6 sun-java6-jdk 3208002/9625kB 33%]

4. After installation done, jdk and jre will install at /usr/lib/jvm/java-6-sun-1.6.0.06
5. Ubuntu help to create a java symbolic link and put in /usr/bin for shortcut access
4. type java -version, DONE !!

Post-Installation Setup

Set JAVA_HOME into environment variable
Copy following statement and append to /etc/profile or .bashrc file, make system set JAVA_HOME into system environment variable.
export JAVA_HOME="/usr/lib/jvm/java-6-sun-1.6.0.06"

Sunday, September 2, 2012

Implement Google Search (JSON) for Android, display in WebView.


Note:
- No layout file needed in this exercise.
- "android.permission.INTERNET" id needed in AndroidManifest.xml.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.webkit.WebView;

public class MainActivity extends Activity {
 
 String search_url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=";
 String search_item = "android";
 String search_query = search_url + search_item;

 WebView webView;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        webView = new WebView(this);
        setContentView(webView);
        
        new JsonSearchTask().execute();
    }
    
    private class JsonSearchTask extends AsyncTask<Void, Void, Void>{

     String searchResult = "";
     
  @Override
  protected Void doInBackground(Void... arg0) {
   
   try {
    searchResult = ParseResult(sendQuery(search_query));
   } catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   
   return null;
  }

  @Override
  protected void onPostExecute(Void result) {

   webView.loadData(searchResult, 
         "text/html", 
         "UTF-8");
   
   super.onPostExecute(result);
  }
     
    }

    private String sendQuery(String query) throws IOException{
     String result = "";
     
     URL searchURL = new URL(query);
     
     HttpURLConnection httpURLConnection = (HttpURLConnection) searchURL.openConnection();
     
     if(httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK){
      InputStreamReader inputStreamReader = new InputStreamReader(httpURLConnection.getInputStream());
      BufferedReader bufferedReader = new BufferedReader(
        inputStreamReader,
        8192);
      
      String line = null;
      while((line = bufferedReader.readLine()) != null){
       result += line;
      }
      
      bufferedReader.close();
     }
     
     return result;
    }
    
    private String ParseResult(String json) throws JSONException{
     String parsedResult = "";
     
     JSONObject jsonObject = new JSONObject(json);
     JSONObject jsonObject_responseData = jsonObject.getJSONObject("responseData");
     JSONArray jsonArray_results = jsonObject_responseData.getJSONArray("results");
     
     parsedResult += "Google Search APIs (JSON) for : <b>" + search_item + "</b><br/>";
     parsedResult += "Number of results returned = <b>" + jsonArray_results.length() + "</b><br/><br/>";
     
     for(int i = 0; i < jsonArray_results.length(); i++){
      
      JSONObject jsonObject_i = jsonArray_results.getJSONObject(i);
      
      String iTitle = jsonObject_i.getString("title");
      String iContent = jsonObject_i.getString("content");
      String iUrl = jsonObject_i.getString("url");
      
      parsedResult += "<a href='" + iUrl + "'>" + iTitle + "</a><br/>";
      parsedResult += iContent + "<br/><br/>";
     }
     
     return parsedResult;
    }
}

Sunday, July 22, 2012

Android Interview Questions


Hi Friends I have Created the interview Questions On Android according to my experience 

I have an experience as an technical interviewer and as a person to attend an interview.

So that I have written many questions for those who are planning to attend the interview on Android .


Android Interview Questions


      1. What is Android ? Explain about the Android Architecture .


Ans:
Android is a software stack for mobile devices that includes an operating system, middleware and key applications. The Android SDK provides the tools and APIs necessary to begin developing applications on the Android platform using the Java programming language.
      • It is an operating system for mobile
      • It has an integrated Java Virtual Machine
      • System interfaces are exposed only through Java libraries
      • It is based on the Linux Kernel
The SDK includes
        • Android packages
        • sample files
        • Documentation
        • A Simulator
Architectuere Designed by the layers like
  1. Linux Kernel
  2. Android Runtime
  3. Libraries
  4. Application Framework
over which the core applications run as well as the applications developed by anyone using this framework

      1. How many ways are there for Android Programing.
Ans: It seems to be more than one way to program for the Android devices.

a.The first and the most common way is by using the Software Development Kit (SDK) using Java Syntax. This is what I have been talking about in all the earlier posts and tutorials.

The other 3 interesting ways, I believe, are:
b. Native Development Kit using C / C ++. This I am sure many are aware of and would be using to some extent. This is a little more closer to the OS, not running on top of the virtual Machine.

c. RenderScript using C99 - used to write faster graphics code like the Google Books page turn animation etc.
d. Android Scripting Layer using Python etc

      1. What are the fundamental components of android ? Explain
Ans:
The fundamental building blocks / components of Android are:
1. Activities
2. Services
3. Broadcast Receivers
4. Content Providers.
The communication between the above mentioned components is through 
1. Intents
2. Intent Filters

Activity is the basic building block of every visible android application. It provides the means to render a UI. Every screen in an application is an activity by itself. Though they work together to present an application sequence, each activity is an independent entity.


Service is another building block of android applications which does not provide a UI. It is a program that can run in the background for an indefinite period.


Broadcast Receiver is yet another type of component that can receive and respond to any broadcast announcements. 


Content Providers are a separate league of components that expose a specific set of data to applications.

      1. What is Activity ?Explain the Activity Lifecycle.
Ans:
Activity Life Cycle

5) What is an Intent?

A class (Intent) which describes what a caller desires to do. The caller will send this intent to Android's intent resolver, which finds the most suitable activity for the intent. E.g. opening a PDF document is an intent, and the Adobe Reader apps will be the perfect activity for that intent (class).

Wht is Intent, IntentFilter and IntentReceiver? and how many types of Intents are there in android ? Explain
Ans:
The platform designers have introduced a new conpect of communication through intents and intent filters.

Intents: Intent is a bundle of information, a passive data structure that holds an abstract description of the operation to be performed. (or in the case of broadcasts, a description of an event that has happened and is being announced).
IntentFilter :Intent filters are the means through which a component advertizes its own capabilities to handle specific job/operations to the android platform.
IntentReceiver:
An application class that listens for messagesbroadcosted by calling Context.broadcastintent

Intents are 3 Types
              1. Implicit Intents
              2. Explicit Intents
              3. Pending Intents

      1. What is a Resourse and Layout Resourse.
Ans:
A Resourse is nothing but user supplied XML,Bitmap or other file entered into the application build process which can later be loaded from code.
A Layout Resourse is an XML fine that describes an Activity screen.

      1. Difference between AsyncTask ,Threads and Handlers.
The main difference between Thread and AsynkTask is
A Thread can not change/update the UI Thread(Main Thread) directly. This can result in undefined and unexpected behavior, which can be difficult and time- consuming to track down.

Where as using Asynktask allows you to perform asynchronous work on your user interface. It performs the blocking operations in a worker thread and then publishes the results on the UI thread, without requiring you to handle threads and/or handlers yourself.

A Handler allows you to send and processm Message and Runnable objects associated with a thread's MessageQueues Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.

There are two main uses for a Handler:
(1) to schedule messages and runnables to be executed as some point in the future;
(2) to enqueue an action to be performed on a different thread than your own.




      1. Difference between ActivityContext and ApplicationContext.
Ans:
They are both instances of Context but the application instance is tied to the lifecycle of the application, while the Activity instance is tied to the lifecycle of an Activity. Thus, they have access to different information about the application environment.

      1. What is Context in Android ?
Ans:
Context is anInterface to global information about an application environment. This is an abstract class whose implementation is provided by the Android system. It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc.

      1. How many States are there for Call in Telephony API .
Ans:
Three states
1)RINGING
2)OFF-HOOK
3)IDLE

      1. How many ways are there to store Data in Android application?Explain a real time situation for using those idividually?
Ans:
There are 4 ways of storing data on the android platform:
  • 1.Preferences
  • 2.SQLite Database
  • 3.Files
  • 4.Network
Preferences :
Basically used for storing user preferences for a single application or across applications for a mobile. This is typically name-value pairs accessible to the context.
DataBases :
Android supports creating of databases based on SQLite db. Each database is private to the applications that creates it
Files –
Files can be directly stored on the mobile or on to an extended storage medium. By default other applications cannot access it.
Network –
Data can be stored and retrieved from the network too depending on the availability.
      1. What do you mean by the ContentResolver?
Ans:
To work with Content Providers, the following classes are important:
- ContentResolver
- Cursor
- ContentObserver

ContentResolver
ContentResolver is important here to interact with ContentProvider. All the inserting, updating, and deleting data are through ContentProvider.


      1. Explain the ViewHierarchy in android UserInterface development.
Ans:
All ViewGroups ,Views and Widgets

      1. How to kill your Application in android.
/* Way one */
          android.os.Process.killProcess(android.os.Process.myPid())
          /* Way Two */
          System.exit(0);



      1. What is Bundle? Explian the purpose of Bundle Object in Android.
Ans:
Bundle is an object used in android,When an activity is instantiating then the state of that activity is goin to save in Bundle object while calling super method. this object can be used in an application with the all info of that activity .

Whenever a user change the mobile portrait mode to landscape or vice versa then the activity going to restarts ,so there is a chance to loss previous info. To overcome that bundle object saves the previous state and provides it agin to that activity.
And to pass the datatypes,objects from one activity to another activity through the Intents bundle object is used.

      1. How many types of Notifications presents in android.?
Ans:
Notification on Android can be done in any of the following ways:

  • Status Bar Notification
  • Vibrate
  • Flash lights
  • Play a sound
From the Notification, you can allow the user to launch a new activity as well.



      1. Explain Manifest.xml in Android Application.
Ans:
The manifest presents essential information about the application to the Android system, information the system must have before it can run any of the application's code. Among other things, the manifest does the following:
      • It names the Java package for the application
      • It describes the components of the application
      • It determines which processes will host application components.
      • It declares which permissions the application must have in order to access protected parts of the API and interact with other applications.
      • It declares the minimum level of the Android API that the application requires.
      • It lists the libraries that the application must be linked against.


      1. Can we share Data between Applications using sharedpreferences?
Ans:
Yes we can share but we need to specify the MODE of the preference should be MODE_WORLD_READABLE

      1. Can we Broadcast if Networkprovider changed in android.
Ans:
Yes we can.

      1. Is android supports Multitouch ?
Ans:

Android supports multi touch from 2.3 onwords ,it partially supports from 2.0 onwords.

      1. What is ANR dialog in android ? When it raises .
Ans:
ANR(Application Not Responding) is a dilog which raises when the process becoming delay for 5 seconds by the application code not support by the android system.

      1. What are services and explain about Local service and Remote Services.
Ans:
Service is a fundamental component in android. Many a time, applications will need to run processes for a long time without any intervention from the user, or very rare interventions. These background processes need to keep running even when the phone is being used for other activities / tasks.

And It is a long lived component and does not implement any user interface of its own.

The local service runs in the same process as the application that started it and hence the life of the local service is dependent on the life of the said application

remote service can run in its own process. This causes a challenge of inter-process communication. If one process wants to communicate with another process, the object that is passed between the two needs to be marshaled.

For this purpose, Android provides the AIDL (Android Interface Definition Language) tool that handles the marshaling as well as the communication.


  1. What is a Sticky Intent?
Ans:
sendStickyBroadcast() performs a sendBroadcast(Intent) known as sticky, i.e. the Intent you are sending stays around after the broadcast is complete, so that others can quickly retrieve that data through the return value ofregisterReceiver(BroadcastReceiver, IntentFilter). In all other ways, this behaves the same as sendBroadcast(Intent). One example of a sticky broadcast sent via the operating system is ACTION_BATTERY_CHANGED. When you callregisterReceiver() for that action -- even with a null BroadcastReceiver -- you get the Intent that was last broadcast for that action. Hence, you can use this to find the state of the battery without necessarily registering for all future state changes in the battery.

23) How the nine-patch Image different from a regular bitmap? Alternatively, what is the difference between nine-patch Image vs regular Bitmap Image?
It is one of a resizable bitmap resource which is being used as backgrounds or other images on the device. TheNinePatch class allows drawing a bitmap in nine sections. The four corners are unscaled; the middle of the image is scaled in both axes, the four edges are scaled into one axis.

24) What is a resource?
A user defined JSON, XML, bitmap, or other file, injected into the application build process, which can later be loaded from code.

25) How will you record a phone call in Android? or How to handle an Audio Stream for a call in Android?
Permission.PROCESS_OUTGOING_CALLS: Will Allow an application to monitor, modify, or abort outgoing calls. So using that permission we can monitor the Phone calls.

26) Does Android support the Bluetooth serial port profile?
Yes.

27) Can an application be started on powerup?
Yes.  

28) What is the APK format?
The APK file is compressed AndroidManifest.xml file with extension .apk. It also includes the application code (.dex files), resource files, and other files which are compressed into a single .apk file.

29) How to Translate in Android?
The Google translator translates the data of one language into another language by using XMPP to transmit data. You can type the message in English and select the language which is understood by the citizens of the country in order to reach the message to the citizens.

30) vDescribe Briefly the Android Application Architecture
Android Application Architecture has the following components:
  • Services like Network Operation
    Intent - To perform inter-communication between activities or services
  • Resource Externalization - such as strings and graphics
    Notification signaling users - light, sound, icon, notification, dialog etc.
  • Content Providers - They share data between applications

31) What is needed to make a multiple choice list with a custom view for each row?
Multiple choice list can be viewed by making the CheckBox android:id value be “@android:id /text1". That is the ID used by Android for the CheckedTextView in simple_list_item_multiple_choice.

32) What dialog boxes are supported in android?Android supports 4 dialog boxes:
  • AlertDialog: An alert dialog box supports 0 to 3 buttons and a list of selectable elements, including check boxes and radio buttons. Among the other dialog boxes, the most suggested dialog box is the alert dialog box.
  • ProgressDialog: This dialog box displays a progress wheel or a progress bar. It is an extension of AlertDialog and supports adding buttons.
  • DatePickerDialog: This dialog box is used for selecting a date by the user.
  • TimePickerDialog: This dialog box is used for selecting time by the user.


33) General Android questions
  • The Activity life cycle is must. Different phases of Activity Life cycle. For example: when and how the activity comes to foreground?
  • Knowledge on AndroidManifest file, For example: Why do we need this file, What is the role of this file in Android app development.
  • Different Kinds of Intents
  • Different Kinds of Context
  • Different Storage Methods in android
  • Kinds of Log debugger and Debugger Configuration
  • How do you ensure that the app design will be consistent across the different screen resolutions
  • Thread concepts also plus points as we deal with the treads more.
  • Can you able to build custom views and how?
  • How to create flexible layouts, For example to place English, Chinese fonts.
  • What is localization and how to achieve?
  • What are 9-patch images
  • How to do Memory management
  • What is onCreate(Bundle savedInstanceState), Have you used savedInstanceState when and why?
  • When to use a service
  • How to use a broadcast receiver and register it both in the manifest and in code
  • Intent filters
  • The types of flags to run an application
  • How to do data intensive calculations using threads
  • Passing large objects (that can't be passed via intents and shouldn't be serialized) via a service
  • Binding to a service and the service lifecycle
  • How to persist data (both savedInstanceState and more permanent ways)