Sunday 19 October 2014

Getting Address Using Latitude and Longitude




                                                  Getting Address Using Latitude and Longitude


public static JSONObject getLocationInfo(double lat, double lng) {
   
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                    .permitAll().build();

            StrictMode.setThreadPolicy(policy);

            HttpGet httpGet = new HttpGet(
                    "http://maps.googleapis.com/maps/api/geocode/json?latlng="
                            + lat + "," + lng + "&sensor=true");
            HttpClient client = new DefaultHttpClient();
            HttpResponse response;
            StringBuilder stringBuilder = new StringBuilder();

            try {
                response = client.execute(httpGet);
                HttpEntity entity = response.getEntity();
                InputStream stream = entity.getContent();
                int b;
                while ((b = stream.read()) != -1) {
                    stringBuilder.append((char) b);
                }
            } catch (ClientProtocolException e) {

            } catch (IOException e) {

            }

            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject = new JSONObject(stringBuilder.toString());
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return jsonObject;
        }
        return null;
    }

    public static String getCurrentLocationViaJSON(double lat, double lng) {

        JSONObject jsonObj = getLocationInfo(lat, lng);
        Log.i("JSON string =>", jsonObj.toString());

        String Address1 = "";
        String Address2 = "";
        String City = "";
        String State = "";
        String Country = "";
        String County = "";
        String PIN = "";

        String currentLocation = "";

        try {
            String status = jsonObj.getString("status").toString();
            Log.i("status", status);

            if (status.equalsIgnoreCase("OK")) {
                JSONArray Results = jsonObj.getJSONArray("results");
                JSONObject zero = Results.getJSONObject(0);
                JSONArray address_components = zero
                        .getJSONArray("address_components");

                for (int i = 0; i < address_components.length(); i++) {
                    JSONObject zero2 = address_components.getJSONObject(i);
                    String long_name = zero2.getString("long_name");
                    JSONArray mtypes = zero2.getJSONArray("types");
                    String Type = mtypes.getString(0);

                    if (Type.equalsIgnoreCase("street_number")) {
                        Address1 = long_name + " ";
                    } else if (Type.equalsIgnoreCase("route")) {
                        Address1 = Address1 + long_name;
                    } else if (Type.equalsIgnoreCase("sublocality")) {
                        Address2 = long_name;
                    } else if (Type.equalsIgnoreCase("locality")) {
                        // Address2 = Address2 + long_name + ", ";
                        City = long_name;
                    } else if (Type
                            .equalsIgnoreCase("administrative_area_level_2")) {
                        County = long_name;
                    } else if (Type
                            .equalsIgnoreCase("administrative_area_level_1")) {
                        State = long_name;
                    } else if (Type.equalsIgnoreCase("country")) {
                        Country = long_name;
                    } else if (Type.equalsIgnoreCase("postal_code")) {
                        PIN = long_name;
                    }

                }

                currentLocation = Address1 + "," + Address2 + "," + City + ","
                        + State + "," + Country + "," + PIN;

            }
        } catch (Exception e) {

        }
        return currentLocation;
    }

Interview Question - Photon Technologies Pvt Ltd

                             

                                 Interview Question - Photon Technologies Pvt Ltd......



1) What Is the Google Android SDK?
-->  The Google Android SDK is a toolset that developers need in order to write apps on Android enabled devices. It contains a graphical interface that emulates an Android driven handheld environment, allowing them to test and debug their codes.

2) What is the 
Android Architecture?
-->  Android Architecture is made up of 4 key components:
- Linux Kernel
- Libraries
- Android Framework
- Android Applications

3) Describe the 
Android Framework.
-->  The Android Framework is an important aspect of the Android Architecture. Here you can find all the classes and methods that developers would need in order to write applications on the Android environment.

4) What is 
AAPT?
-->  AAPT is short for Android Asset Packaging Tool. This tool provides developers with the ability to deal with zip-compatible archives, which includes creating, extracting as well as viewing its contents.


5) What is the importance of having an emulator within the Android environment?
-->  The emulator lets developers “play” around an interface that acts as if it were an actual mobile device. They can write and test codes, and even debug. Emulators are a safe place for testing codes especially if it is in the early design phase.


6) What are 
Intents?
-->  Intents displays notification messages to the user from within the Android enabled device. It can be used to alert the user of a particular state that occurred. Users can be made to respond to intents.

7) Differentiate Activities from Services.
-->  Activities can be closed, or terminated anytime the user wishes. On the other hand, services are designed to run behind the scenes, and can act independently. Most services run continuously, regardless of whether there are certain or no activities being executed.

8) What are containers?-->  Containers, as the name itself implies, holds objects and widgets together, depending on which specific items are needed and in what particular arrangement that is wanted. Containers may hold labels, fields, buttons, or even child containers, as examples.

9) What is 
Orientation?-->  Orientation, which can be set using setOrientation(), dictates if the LinearLayout is represented as a row or as a column. Values are set as either HORIZONTAL or VERTICAL.

10) What is the importance of Android in the mobile market?-->  Developers can write and register apps that will specifically run under the Android environment. This means that every mobile device that is Android enabled will be able to support and run these apps. With the growing popularity of Android mobile devices, developers can take advantage of this trend by creating and uploading their apps on the Android Market for distribution to anyone who wants to download it.

11) What do you think are some 
disadvantages of Android?-->  Given that Android is an open-source platform, and the fact that different Android operating systems have been released on different mobile devices, there’s no clear cut policy to how applications can adapt with various OS versions and upgrades.
-->  One app that runs on this particular version of Android OS may or may not run on another version.
-->  Another disadvantage is that since mobile devices such as phones and tabs come in different sizes and forms, it poses a challenge for developers to create apps that can adjust correctly to the right screen size and other varying features and specs.

12 *) What is 
adb?-->  Adb is short for Android Debug Bridge. It allows developers the power to execute remote shell commands. Its basic function is to allow and control communication towards and from the emulator port.

13 *) What is the function of an intent filter?-->  Because every component needs to indicate which intents they can respond to, intent filters are used to filter out intents that these components are willing to receive. One or more intent filters are possible, depending on the services and activities that is going to make use of it.

14) Enumerate the three key loops when monitoring an activity?- Entire lifetime – activity happens between onCreate and onDestroy
- Visible lifetime – activity happens between onStart and onStop
- Foreground lifetime – activity happens between onResume and onPause

15 *) When is the 
onStop() method invoked?-->  A call to onStop method happens when an activity is no longer visible to the user, either because another activity has taken over or if in front of that activity.

16) Is there a case wherein other qualifiers in multiple resources take precedence over locale?-->  Yes, there are actually instances wherein some qualifiers can take precedence over locale. There are two known exceptions, which are the MCC (mobile country code) and MNC (mobile network code) qualifiers.

17) What are the different states wherein a process is based?-->  There are 4 possible states:
- foreground activity
- visible activity
- background activity
- empty process

18) How can the ANR be prevented?-->  One technique that prevents the Android system from concluding a code that has been responsive for a long period of time is to create a child thread. Within the child thread, most of the actual workings of the codes can be placed, so that the main thread runs with minimal periods of unresponsive times.
19) What is the AndroidManifest.xml?-->  This file is essential in every application. It is declared in the root directory and contains information about the application that the Android system must know before the codes can be executed.


20) Enumerate the steps in creating a bounded service through AIDL.1. create the .aidl file, which defines the programming interface
2. implement the interface, which involves extending the inner abstract Stub class as well as implanting its methods.
3. expose the interface, which involves implementing the service to the clients.

21) What is the importance of 
Default Resources?-->  When default resources, which contain default strings and files, are not present, an error will occur and the app will not run. Resources are placed in specially named subdirectories under the project res/ directory.


22) When does
 ANR occur?-->  The ANR dialog is displayed to the user based on two possible conditions. One is when there is no response to an input event within 5 seconds, and the other is when a broadcast receiver is not done executing within 10 seconds.

23) What is AIDL?-->  AIDL, or Android Interface Definition Language, handles the interface requirements between a client and a service so both can communicate at the same level through interprocess communication or IPC. This process involves breaking down objects into primitives that Android can understand. This part is required simply because a process cannot access the memory of the other process.

24) What data types are 
supported by AIDL?-->  AIDL has support for the following data types:
-string
-charSequence
-List
-Map
-all native Java data types like int,long, char and Boolean

25) What is a 
Fragment?-->  A fragment is a part or portion of an activity. It is modular in a sense that you can move around or combine with other fragments in a single activity. Fragments are also reusable.

26) What is a 
visible activity?-->  A visible activity is one that sits behind a foreground dialog. It is actually visible to the user, but not necessarily being in the foreground itself.

27) What are the 
core components under the Android application architecture?-->  There are 5 key components under the Android application architecture:
- services
- intent
- resource externalization
- notifications
- content providers


28 *) What is a 
Sticky Intent?-->  A Sticky Intent is a broadcast from sendStickyBroadcast() method such that the intent floats around even after the broadcast, allowing others to collect data from it.


29 *) What is an 
action?-->  In Android development, an action is what the intent sender wants to do or expected to get as a response. Most application functionality is based on the intended action.


30) What 
language is supported by Android for application development?-->  The main language supported is Java programming language. Java is the most popular language for app development, which makes it ideal even for new Android developers to quickly learn to create and deploy applications in the Android environment.

Thursday 16 October 2014

current running application package name


                                                 You can get current name package


To check the curreent running package name

ActivityManager am = (ActivityManager) mContext
                .getSystemService(Activity.ACTIVITY_SERVICE);
        String packageName = am.getRunningTasks(1).get(0).topActivity
                .getPackageName();


Requires permission: 
                              android.permission.GET_TASKS 

Reading inbox SMS



                                               Reading inbox SMS using Activity


Android Reading Inbox SMS



import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.widget.TextView;

public class SMSRead extends Activity {

  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      TextView view = new TextView(this);
      Uri uriSMSURI = Uri.parse("content://sms/inbox");
      Cursor cur = getContentResolver().query(uriSMSURI, null, null, null,null);
      String sms = "";
      while (cur.moveToNext()) {
          sms += "From :" + cur.getString(2) + " : " + cur.getString(11)+"\n";        
      }
      view.setText(sms);
      setContentView(view);
  }
}


Add below permission to AndroidManifest.xml

 
<uses-permission name="android.permission.READ_SMS" />



Receing and Diplay for incoming sms using broadcastreceiver


                                            Read and Display an Incoming SMS-Android Phones

User Define in Manifest :-
    Declare receiver in AndroidManifest

<receiver android:name=".IncomingSms">  
     <intent-filter>
         <action android:name="android.provider.Telephony.SMS_RECEIVED" />
     </intent-filter>
 </receiver>

   SMS permission in AndroidManifest

<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS"></uses-permission>

Complete code for AndroidManifest.xml File :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidexample.broadcastreceiver"
    android:versionCode="1"
    android:versionName="1.0" >
       
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.androidexample.broadcastreceiver.BroadcastNewSms"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
       
        <receiver android:name="com.androidexample.broadcastreceiver.IncomingSms">  
            <intent-filter>
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
        </receiver>
       
    </application>
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
   
    <uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
    <uses-permission android:name="android.permission.READ_SMS" />
    <uses-permission android:name="android.permission.SEND_SMS"></uses-permission>
   
</manifest>
===================================================================

IncomingSms.java file details :
    I have made broadcast event reciever in this file
     1. Created class IncomingSms with extends BroadcastReceiver class

public class IncomingSms extends BroadcastReceiver

      2. Get the object of SmsManager to find out received sms details

// Get the object of SmsManager
final SmsManager sms = SmsManager.getDefault();

      3.  Create method receiver()

public void onReceive(Context context, Intent intent)

        4. Get / Read current Incomming SMS data

// Retrieves a map of extended data from the intent.
final Bundle bundle = intent.getExtras();

try {
   
    if (bundle != null) {
       
        final Object[] pdusObj = (Object[]) bundle.get("pdus");
       
        for (int i = 0; i < pdusObj.length; i++) {
           
            SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
            String phoneNumber = currentMessage.getDisplayOriginatingAddress();
           
            String senderNum = phoneNumber;
            String message = currentMessage.getDisplayMessageBody();

            Log.i("SmsReceiver", "senderNum: "+ senderNum + "; message: " + message);
           

           // Show alert
            int duration = Toast.LENGTH_LONG;
            Toast toast = Toast.makeText(context, "senderNum: "+ senderNum + ", message: " + message, duration);
            toast.show();
           
        } // end for loop
      } // bundle is null

} catch (Exception e) {
    Log.e("SmsReceiver", "Exception smsReceiver" +e);
   
}
========================================================================
     Complete code for  IncomingSms.java file :

public class IncomingSms extends BroadcastReceiver {
   
    // Get the object of SmsManager
    final SmsManager sms = SmsManager.getDefault();
   
    public void onReceive(Context context, Intent intent) {
   
        // Retrieves a map of extended data from the intent.
        final Bundle bundle = intent.getExtras();

        try {
           
            if (bundle != null) {
               
                final Object[] pdusObj = (Object[]) bundle.get("pdus");
               
                for (int i = 0; i < pdusObj.length; i++) {
                   
                    SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
                    String phoneNumber = currentMessage.getDisplayOriginatingAddress();
                   
                    String senderNum = phoneNumber;
                    String message = currentMessage.getDisplayMessageBody();

                    Log.i("SmsReceiver", "senderNum: "+ senderNum + "; message: " + message);
                   

                   // Show Alert
                    int duration = Toast.LENGTH_LONG;
                    Toast toast = Toast.makeText(context,
                                 "senderNum: "+ senderNum + ", message: " + message, duration);
                    toast.show();
                   
                } // end for loop
              } // bundle is null

        } catch (Exception e) {
            Log.e("SmsReceiver", "Exception smsReceiver" +e);
           
        }
    }  
}