Wednesday 13 March 2013

Android Interview Questions and Answer


1. Define Android?
Android is software stack for mobile devices that has middleware, operating system and specific key applications. The application must be implemented in its own process and Dalvik Virtual Machine interface. DVM device is used to effectively run several virtual machines. The byte code of java language is executed by DVM that is converted to .dex format files.

2. Define Activity?
Activity is nothing but application’s single screen that assists java code.

3. Define intent?
Intent is a class that depicts what caller has to do. Intent is send to intent resolver of Android by the caller which finds appropriate activity for intent. For example: intent is opening PDF doc and the perfect activity for intent is apps of Adobe Reader.

4. Define resource?
Resource is nothing but user defined XML, JSON or bitmap that is inserted in application build process which is later loaded from code.

5. Does Android assist profile of Bluetooth serial port?
Yes




 

6. Is it possible to start an application on powerup?
 
Yes


7. Define APK format?
APK file is compacted AndroidManifest.xml file that has .apk extension. Resource files, Application code and many other files are present in this format and are compressed to single file which has .apk extension.

8. Explain translation in Android?
The data of one language can be changed to other language by Google translator by making use of XMPP for data transmission. You can type English message and choose the language that is easily understood by your country people to reach message to them.

9. On which virtual machine Android runs?
Dalvik virtual machine

10. What is the latest version in android?
Android 4.2

12. Give the new Android platform for mobile phones?
Android 4.2 and the name given to this version is Ice-cream Sandwich. The versions that came before this are given below:
• 3. X.X Honeycomb
• 2.3. X Gingerbread
• 2.2 Froyo
• 2.0/2.1 Éclair
• 1.6 Donut
• 1.5 Cupcake

13. Give the languages that are supported by Android operating system for developing applications?
It supports all the languages that are written using java code.


14. In what ways data can be stored in Android?
• Internal storage
• Network connection
• Shared preferences
• Sqlite database
• External storage

15. What are user interface types?
• Notifications
• Views


16. Give notification types in Android?
• Dialog notification
• Status bar notification
• Tost notification

Tuesday 12 March 2013

Phone call history/log programmatically


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

    <TextView
        android:id="@+id/call"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_world" />

</RelativeLayout>

MainActivity.java

public class MainActivity extends Activity {

    private static final int MISSED_CALL_TYPE = 0;
    private TextView txtcall;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        txtcall = (TextView) findViewById(R.id.call);

        StringBuffer sb = new StringBuffer();
        Cursor managedCursor = managedQuery(CallLog.Calls.CONTENT_URI, null,
                null, null, null);
        int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
        int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
        int date = managedCursor.getColumnIndex(CallLog.Calls.DATE);
        int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
        sb.append("Call Details :");
        while (managedCursor.moveToNext()) {
            String phNumber = managedCursor.getString(number);
            String callType = managedCursor.getString(type);
            String callDate = managedCursor.getString(date);
            Date callDayTime = new Date(Long.valueOf(callDate));
            String callDuration = managedCursor.getString(duration);
            String dir = null;
            int dircode = Integer.parseInt(callType);
            switch (dircode) {

            case CallLog.Calls.OUTGOING_TYPE:
                dir = "OUTGOING";
                break;

            case CallLog.Calls.INCOMING_TYPE:
                dir = "INCOMING";
                break;

            case CallLog.Calls.MISSED_TYPE:
                dir = "MISSED";
                break;
            }
            sb.append("\nPhone Number:--- " + phNumber + " \nCall Type:--- "
                    + dir + " \nCall Date:--- " + callDayTime
                    + " \nCall duration in sec :--- " + callDuration);
            sb.append("\n----------------------------------");
        }
        managedCursor.close();
        txtcall.setText(sb);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

}

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



Friday 21 December 2012

Turn ON wifi programmatically

Android Turn ON wifi  programmatically

Coding for Enable WIFI programmatically.
Activity.class

import android.app.Activity;
import android.content.Context;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.widget.TextView;

public class WifiEnableActivity extends Activity {
    /** Called when the activity is first created. */
    private WifiManager wifiManager; 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE); 
       TextView text = (TextView)findViewById(R.id.txtWiFi);
          wifiManager.setWifiEnabled(true); 
          if(wifiManager.isWifiEnabled()){
              text.setText("Wifi State Enabled");
          }
        
    }
}
Then  some permission and user feature required in manifest file.
  <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission> 
    <uses-permission android:name="android.permission.UPDATE_DEVICE_STATS"></uses-permission> 
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission> 
    <uses-feature android:name="android.hardware.wifi.direct" />
    <uses-permission    android:name="android.permission.INTERNET" /> 
    <uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission> 
Download Source Code

Thursday 20 December 2012

Toast notification show Different Gravity

Toast notify we can show in different gravity like "TOP", "RIGHT", "LEFT", "BOTTOM",etc.

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
       
        Toast t = Toast.makeText(MainActivity.this, "TOP | RIGHT", Toast.LENGTH_LONG);
        t.setGravity(Gravity.TOP|Gravity.RIGHT, 0, 0);
        t.show();
       
        t = Toast.makeText(MainActivity.this, "CENTER", Toast.LENGTH_LONG);
        t.setGravity(Gravity.CENTER, 0, 0);
        t.show();
       
        t = Toast.makeText(MainActivity.this, "BOTTOM | LEFT", Toast.LENGTH_LONG);
        t.setGravity(Gravity.BOTTOM|Gravity.LEFT, 0, 0);
        t.show();
       
        t = Toast.makeText(MainActivity.this, "CENTER | LEFT", Toast.LENGTH_LONG);
        t.setGravity(Gravity.CENTER|Gravity.LEFT, 0, 0);
        t.show();
    
    }
   
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}

Monday 26 November 2012

Capture photo using camera

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="photo" >
    </Button>

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" >
    </ImageView>

</LinearLayout>

MainActivity.java

public class MainActivity  extends Activity {
    private static final int CAMERA_REQUEST = 1888;
    private ImageView imageView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        this.imageView = (ImageView)this.findViewById(R.id.imageView1);
        Button photoButton = (Button) this.findViewById(R.id.button1);
        photoButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(cameraIntent, CAMERA_REQUEST);
            }
        });
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
        if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) { 
            Bitmap photo = (Bitmap) data.getExtras().get("data");
            imageView.setImageBitmap(photo);
        } 
    }
}

AndroidManifest.xml

<uses-feature android:name="android.hardware.camera"></uses-feature>

Thursday 1 November 2012

Google Mapview

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
 
 
  <TextView android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Waiting for location..."
    android:id="@+id/lblLocationInfo"/>
  <!-- <1> -->
 
 
  
<com.google.android.maps.MapView android:id="@+id/mapview"
   android:apiKey="0dv9akiSW0I8Vvu5Ht_ScUSAEA6tngHm7Sta1ZA"      
    android:enabled="true"
   
    android:clickable="true"
    android:focusableInTouchMode="true"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    />

   
</LinearLayout>

map.java

public class map extends MapActivity implements LocationListener { //<1>
     
      private static final String TAG = "LocationActivity";

      LocationManager locationManager; //<2>
      Geocoder geocoder; //<3>
      TextView locationText;
      MapView map; 
      MapController mapController; //<4>
     
     
      public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        locationText = (TextView)this.findViewById(R.id.lblLocationInfo);
        map = (MapView)this.findViewById(R.id.mapview);
        map.setBuiltInZoomControls(true);
       
        mapController = map.getController(); //<4>
        mapController.setZoom(16);
       
        locationManager = (LocationManager)this.getSystemService(LOCATION_SERVICE); //<2>
       
        geocoder = new Geocoder(this); //<3>
       
        Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); //<5>
        if (location != null) {
          Log.d(TAG, location.toString());
          this.onLocationChanged(location); //<6>
        }
      }

     
      protected void onResume() {
        super.onResume();
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 10, this); //<7>
      }

     
      protected void onPause() {
        super.onPause();
        locationManager.removeUpdates(this); //<8>
      }

     
      public void onLocationChanged(Location location) { //<9>
        Log.d(TAG, "onLocationChanged with location " + location.toString());
        String text = String.format("Lat:\t %f\nLong:\t %f\nAlt:\t %f\nBearing:\t %f", location.getLatitude(),
                      location.getLongitude(), location.getAltitude(), location.getBearing());
        this.locationText.setText(text);
       
        try {
          List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 10); //<10>
          for (Address address : addresses) {
            this.locationText.append("\n" + address.getAddressLine(0));
          }
         
          int latitude = (int)(location.getLatitude() * 1000000);
          int longitude = (int)(location.getLongitude() * 1000000);

          GeoPoint point = new GeoPoint(latitude,longitude);
          mapController.animateTo(point); //<11>
         
        } catch (IOException e) {
          Log.e("LocateMe", "Could not get Geocoder data", e);
        }
      }

   
    protected boolean isRouteDisplayed() {
        // TODO Auto-generated method stub
        return false;
    }

   
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub
       
    }

   
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub
       
    }

   
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub
       
    }

    }

AndroidManifest.xml

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

<uses-library android:name="com.google.android.maps" />

Upload Video in server

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text=""
    android:id="@+id/tv"
    />
    <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
<Button android:text="Browse gallery"
    android:id="@+id/Button01"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
</Button>
<ImageView android:id="@+id/ImageView01"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
</ImageView>
</LinearLayout>

uploadfile.java

public class uploadfile extends Activity {
    TextView tv = null;
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tv = (TextView) findViewById(R.id.tv);
        doFileUpload();
    }
   
    private void doFileUpload(){

          HttpURLConnection conn = null;
          DataOutputStream dos = null;
          DataInputStream inStream = null;

       
          String exsistingFileName = "/sdcard/six.3gp";
          // Is this the place are you doing something wrong.

          String lineEnd = "\r\n";
          String twoHyphens = "--";
          String boundary =  "*****";


          int bytesRead, bytesAvailable, bufferSize;

          byte[] buffer;

          int maxBufferSize = 1*1024*1024;
 
          String urlString = "http://192.168.1.5/upload.php";
         
         
         
          try
          {
          
       
          Log.e("MediaPlayer","Inside second Method");

          FileInputStream fileInputStream = new FileInputStream(new File(exsistingFileName) );



           URL url = new URL(urlString);

           conn = (HttpURLConnection) url.openConnection();

           conn.setDoInput(true);

           // Allow Outputs
           conn.setDoOutput(true);

           // Don't use a cached copy.
           conn.setUseCaches(false);

           // Use a post method.
           conn.setRequestMethod("POST");

           conn.setRequestProperty("Connection", "Keep-Alive");
       
           conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

          
           dos = new DataOutputStream( conn.getOutputStream() );

           dos.writeBytes(twoHyphens + boundary + lineEnd);
           dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + exsistingFileName +"\"" + lineEnd);
           dos.writeBytes(lineEnd);

           Log.e("MediaPlayer","Headers are written");



           bytesAvailable = fileInputStream.available();
           bufferSize = Math.min(bytesAvailable, maxBufferSize);
           buffer = new byte[bufferSize];



           bytesRead = fileInputStream.read(buffer, 0, bufferSize);

           while (bytesRead > 0)
           {
            dos.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
           }

          

           dos.writeBytes(lineEnd);
          
           dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

           BufferedReader in = new BufferedReader(
                           new InputStreamReader(
                           conn.getInputStream()));
                String inputLine;
               
                while ((inputLine = in.readLine()) != null)
                    tv.append(inputLine);

          
          
          
           // close streams
           Log.e("MediaPlayer","File is written");
           fileInputStream.close();
           dos.flush();
           dos.close();


          }
          catch (MalformedURLException ex)
          {
               Log.e("MediaPlayer", "error: " + ex.getMessage(), ex);
          }

          catch (IOException ioe)
          {
               Log.e("MediaPlayer", "error: " + ioe.getMessage(), ioe);
          }


          //------------------ read the SERVER RESPONSE


          try {
                inStream = new DataInputStream ( conn.getInputStream() );
                String str;
              
                while (( str = inStream.readLine()) != null)
                {
                     Log.e("MediaPlayer","Server Response"+str);
                }
                /*while((str = inStream.readLine()) !=null ){
                   
                }*/
                inStream.close();

          }
          catch (IOException ioex){
               Log.e("MediaPlayer", "error: " + ioex.getMessage(), ioex);
          }
         
         

        }
}

AndroidManifest.xml

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

upload.php

<?php

move_uploaded_file($_FILES['uploadedfile']['tmp_name'], "./".$_FILES["uploadedfile"]["name"]);

?>