Monday, April 25, 2016

Get GPS current location coordinates and city name

 Get Current Location coordinates/GPS coordinates and get City name


I have already tested this app on my android phone and one more thing when you move line 10-20 meter you will get the new coordinates.

What is app does?

  • check gps is enable or disable
  • Get gps coordinates
  • Get the current city name.


 -------------------------------------------
App Name: GetMyCurrentLocation
Package Name: com.example.hemant.may_i_help_u

Android SDK: Android SDK 2.3.3 / API 10
Default Activity Name: MainActivity 

-------------------------------------------

package com.example.hemant.may_i_help_u;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

public class MainActivity extends Activity implements OnClickListener {

private LocationManager locationMangaer=null;

private LocationListener locationListener=null;

private Button btnGetLocation = null;
private EditText editLocation = null;
private ProgressBar pb =null;

private static final String TAG = "Debug";
private Boolean flag = false;

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


//if you want to lock screen for always Portrait mode
setRequestedOrientation(ActivityInfo
.SCREEN_ORIENTATION_PORTRAIT);

pb = (ProgressBar) findViewById(R.id.progressBar1);
pb.setVisibility(View.INVISIBLE);

editLocation = (EditText) findViewById(R.id.editTextLocation);

btnGetLocation = (Button) findViewById(R.id.btnLocation);
btnGetLocation.setOnClickListener(this);

locationMangaer = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);

}

@Override
public void onClick(View v) {
flag = displayGpsStatus();
if (flag) {

Log.v(TAG, "onClick");

editLocation.setText("Please!! move your device to"+
" see the changes in coordinates."+"\nWait..");

pb.setVisibility(View.VISIBLE);
locationListener = new MyLocationListener();

if ( Build.VERSION.SDK_INT >= 23 &&
ContextCompat.checkSelfPermission( MainActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission( MainActivity.this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return ;
}
locationMangaer.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, locationListener);


} else {
alertbox("Gps Status!!", "Your GPS is: OFF");
}

}

/*----Method to Check GPS is enable or disable ----- */
private Boolean displayGpsStatus() {

LocationManager lm = (LocationManager)MainActivity.this.getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = false;

try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);

} catch(Exception ex) {}
return gps_enabled;
}

/*----------Method to create an AlertBox ------------- */
protected void alertbox(String title, String mymessage) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your Device's GPS is Disable")
.setCancelable(false)
.setTitle("** Gps Status **")
.setPositiveButton("Gps On",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// finish the current activity
// AlertBoxAdvance.this.finish();
Intent myIntent = new Intent(
Settings.ACTION_SECURITY_SETTINGS);
startActivity(myIntent);
dialog.cancel();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// cancel the dialog box
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}

/*----------Listener class to get coordinates ------------- */
private class MyLocationListener implements LocationListener {
@Override
public void onLocationChanged(Location loc) {

editLocation.setText("");
pb.setVisibility(View.INVISIBLE);
Toast.makeText(getBaseContext(),"Location changed : Lat: " +
loc.getLatitude()+ " Lng: " + loc.getLongitude(),
Toast.LENGTH_SHORT).show();
String longitude = "Longitude: " +loc.getLongitude();
Log.v(TAG, longitude);
String latitude = "Latitude: " +loc.getLatitude();
Log.v(TAG, latitude);

/*----------to get City-Name from coordinates ------------- */
String cityName=null;
Geocoder gcd = new Geocoder(getBaseContext(),
Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(loc.getLatitude(), loc
.getLongitude(), 1);
if (addresses.size() > 0)
System.out.println(addresses.get(0).getLocality());
cityName=addresses.get(0).getLocality();
} catch (IOException e) {
e.printStackTrace();
}

String s = longitude+"\n"+latitude +
"\n\nMy Currrent City is: "+cityName;
editLocation.setText(s);
}

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

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

@Override
public void onStatusChanged(String provider,
int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}
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"
 android:weightSum="1">
 <TextView
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="Get Current Location and City Name"
  android:layout_weight="0.20"
  android:gravity="center"
  android:textSize="20sp" />
 <EditText
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_weight="0.33"
  android:id="@+id/editTextLocation"
  android:editable="false">
  <requestFocus></requestFocus>
 </EditText>
 <LinearLayout
  android:id="@+id/layButtonH"
  android:layout_height="wrap_content"
  android:layout_width="fill_parent"
  android:gravity="center"
  android:layout_weight="0.15">
  <Button
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="Get Location"
   android:id="@+id/btnLocation"></Button>
 </LinearLayout>
 <LinearLayout
  android:id="@+id/layloadingH"
  android:layout_height="wrap_content"
  android:layout_weight="0.20"
  android:layout_width="fill_parent"
  android:gravity="center">
  <ProgressBar
   android:layout_width="wrap_content"
   android:id="@+id/progressBar1"
   android:layout_height="wrap_content"></ProgressBar>
 </LinearLayout>
</LinearLayout>

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest
 xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.rdc"
 android:versionCode="1"
 android:versionName="1.0">
 <uses-sdk android:minSdkVersion="10" />

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

 <application
  android:icon="@drawable/icon"
  android:label="@string/app_name">
  <activity
   android:name=".GetCurrentLocation"
   android:label="@string/app_name">
   <intent-filter>
   <action android:name="android.intent.action.MAIN" />
   <category android:name="android.intent.category.LAUNCHER" />
   </intent-filter>
  </activity>

 </application>
</manifest>

The output Screen will be like this..



Check if GPS/Network Provider Services are enabled or not?


How to check if GPS/Network Provider Services are enabled?


LocationManager lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;

try {
    gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch(Exception ex) {}

try {
    network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch(Exception ex) {}

if(!gps_enabled && !network_enabled) {
    // notify user
 AlertDialog.Builder dialog = new AlertDialog.Builder(context);
 dialog.setMessage(context.getResources().getString(R.string.gps_network_not_enabled));
 dialog.setPositiveButton(context.getResources().getString(R.string.open_location_settings), 
new DialogInterface.OnClickListener() {
       @Override
       public void onClick(DialogInterface paramDialogInterface, int paramInt) {
           // TODO Auto-generated method stub
           Intent myIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS);
           context.startActivity(myIntent);
             //get gps
            }
        });
    dialog.setNegativeButton(context.getString(R.string.Cancel), new DialogInterface.
OnClickListener()
   {

            @Override
            public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                // TODO Auto-generated method stub

            }
        });
    dialog.show();      
}


Add below permissions in androidManifest.xml 

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

//-----------------------------------------------------------------------
NOTE:-if you got any warning message like "Call requires permission which may be rejected
 by user. Code should explicitly check to see if permission is available." then you can 
try one by one of below step.


1) Ensure you have your permissions listed in the Manifest:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
(2) Ensure you use ContextCompat as this has compatibility with older API levels.
(3) In your location service, or class that initializes your LocationManager and gets the last known location, we need to check the permissions:
if ( Build.VERSION.SDK_INT >= 23 &&
             ContextCompat.checkSelfPermission( context, android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED &&
             ContextCompat.checkSelfPermission( context, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return  ;
        }

(4) Ensure you request permissions from the user: 
if ( ContextCompat.checkSelfPermission( this, android.Manifest.permission.ACCESS_COARSE_
LOCATION ) != PackageManager.PERMISSION_GRANTED ) {

     ActivityCompat.requestPermissions( this, new String[] {  android.Manifest.permission.ACCESS_COARSE_LOCATION  },
                                                LocationService.MY_PERMISSION_ACCESS_COURSE_LOCATION );
 }



Friday, November 16, 2012

Android Interviews


Android interview questions

What is an action?
The Intent Sender desires something or doing some task

What is activity?
A single screen in an application, with supporting Java code.

What is intent in Android?
A class (Intent) will 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).

What is a Sticky Intent?
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 of registerReceiver (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 call registerReceiver() 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.
Is there anyway to determine if an Intent passed into a BroadcastReceiver's onReceive is the result of a sticky Boradcast Intent, or if it was just sent?

Example for sticky broadcast
When you call registerReceiver() 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.

How the nine-patch Image different from a regular bitmap? or Different 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. The NinePatch 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.

What Programming languages does Android support for applicationdevelopment?
Android applications supports using Java Programming Language. which is coded in Java and complied using Android SDK.

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.

How will you record a phone call in Android? or How to handle on Audio Stream for a call in Android?
Permissions.PROCESS_OUTGOING_CALLS: Will Allows an application to monitor, modify, or abort outgoing calls. So through that we can monitor the Phone calls.

What's the difference between class, file and activity in android?
Class - The Class file is complied from .java file. Android will use this .class fileto produce the executable apk.
File - It is a block of resources, srbitrary information. It can be any file type.
Activity - An activity is the equivalent of a Frame/Window in GUI toolkits. It is not a file or a file type it is just a class that can be extended in Android for loading UI elements on view.

Does Android support the Bluetooth serial port profile?
A. Yes.
Can an application be started on powerup?
A. Yes.

What is APK format.
The APK file is compressed AndroidManifest.xml file with extension .apk, Which have application code (.dex files), resource files, and other files which is compressed into single .apk file.

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.

What is an action?
A description of something that an Intent sender desires.

What are the advantages of Android?
The following are the advantages of Android:

* The customer will be benefited from wide range of mobile applications to choose, since the monopoly of wireless carriers like Orange and AT&T will be broken by Google Android.
* Features like weather details, live RSS feeds, opening screen, icon on the opening screen can be customized
* Innovative products like the location-aware services, location of a nearby convenience store etc., are some of the additive facilities in Android.
What is the TTL (Time to Live)? Why is it required?
TTL is a value in data packet of Internet Protocol. It communicates to the network router whether or not the packet should be in the network for too long or discarded. Usually, data packets might not be transmitted to their intended destination within a stipulated period of time. The TTL value is set by a system default value which is an 8-bit binary digit field in the header of the packet. The purpose of TTL is, it would specify certain time limit in seconds, for transmitting the packet header. When the time is exhausted, the packet would be discarded. Each router receives the subtracts count, when the packet is discarded, and when it becomes zero, the router detects the discarded packets and sends a message, Internet Control Message Protocol message back to the originating host.
How is nine-patch image different from a regular bitmap?
It is a resizable bitmap resource that can be used for backgrounds or other images on the device. The NinePatch class permits drawing a bitmap in nine sections. The four corners are unscaled; the four edges are scaled in one axis, and the middle is scaled in both axes.
Explain IP datagram, Fragmentation and MTU ?
IP datagram can be used to describe a portion of IP data. Each IP datagram has set of fields arranged in an order. The order is specific which helps to decode and read the stream easily. IP datagram has fields like Version, header length, Type of service, Total length, checksum, flag, protocol, Time to live, Identification, source and destination ip address, padding, options and payload.
MTU:- Maximum Transmission Unit is the size of the largest packet that a communication protocol can pass. The size can be fixed by some standard or decided at the time of connection
Fragmentation is a process of breaking the IP packets into smaller pieces. Fragmentation is needed when the datagram is larger than the MTU. Each fragment becomes a datagram in itself and transmitted independently from source. When received by destination they are reassembled.
Explain about the exceptions of Android?
The following are the exceptions that are supported by Android
* InflateException : When an error conditions are occurred, this exception is thrown
* Surface.OutOfResourceException: When a surface is not created or resized, this exception is thrown
* SurfaceHolder.BadSurfaceTypeException: This exception is thrown from the lockCanvas() method, when invoked on a Surface whose is SURFACE_TYPE_PUSH_BUFFERS
* WindowManager.BadTokenException: This exception is thrown at the time of trying to add view an invalid WindowManager.LayoutParamstoken.
Describe 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
What are the advantages of Android?
The following are the advantages of Android:
* The customer will be benefited from wide range of mobile applications to choose, since the monopoly of wireless carriers like AT&T and Orange will be broken by Google Android.
* Features like weather details, live RSS feeds, opening screen, icon on the opening screen can be customized
* Innovative products like the location-aware services, location of a nearby convenience store etc., are some of the additive facilities in Android.
How to select more than one option from list in android xml file? Give an example.
Specify android id, layout height and width as depicted in the following example.

Explain about the exceptions of Android?
The following are the exceptions that are supported by Android
* InflateException : When an error conditions are occurred, this exception is thrown
* Surface.OutOfResourceException: When a surface is not created or resized, this exception is thrown
* SurfaceHolder.BadSurfaceTypeException: This exception is thrown from the lockCanvas() method, when invoked on a Surface whose is SURFACE_TYPE_PUSH_BUFFERS
* WindowManager.BadTokenException: This exception is thrown at the time of trying to add view an invalid WindowManager.LayoutParamstoken.
What are the features of Android?
*Components can be reused and replaced by the application framework.
*Optimized DVM for mobile devices
*SQLite enables to store the data in a structured manner.
*Supports GSM telephone and Bluetooth, WiFi, 3G and EDGE technologies
*The development is a combination of a device emulator, debugging tools, memory profiling and plug-in for Eclipse IDE.
What are the differences between a domain and a workgroup?
In a domain, one or more computer can be a server to manage the network. On the other hand in a workgroup all computers are peers having no control on each other. In a domain, user doesn?t need an account to logon on a specific computer if an account is available on the domain. In a work group user needs to have an account for every computer.
In a domain, Computers can be on different local networks. In a work group all computers needs to be a part of the same local network.
What is android?
Android is a stack of software for mobile devices which has Operating System,middleware and some key applications. The application executes within its own process and its own instance of Dalvik Virtual Machine. Many Virtual Machines run efficiently by a DVM device. DVM executes Java languages byte code which later transforms into .dex format files.
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.
What are the dialog boxes that are supported in android? Explain.
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.
How to Remove Desktop icons and Widgets?
Press and Hold the icon or widget. The phone will vibrate and on the bottom of the phone you will see an option to remove. While still holding the icon or widget drag it to the remove button. Once remove turns red drop the item and it is gone
Common Tricky questions
  • Remember that the GUI layer doesn't request data directly from the web; data is always loaded from a local database.
  • The service layer periodically updates the local database.
  • What is the risk in blocking the Main thread when performing a lengthy operation such as web access or heavy computation? Application_Not_Responding exception will be thrown which will crash and restart the application.
  • Why is List View not recommended to have active components? Clicking on the active text box will pop up the software keyboard but this will resize the list, removing focus from the clicked element.
For senior employees
Beyond a certain level of experience, the job interview questions cease to be "difference between abstract class and interface", and focus more on testing your technical acumen, collaboration and communication skills. A list of such questions, typically asked during interviews for senior positions is given below:
  • Explain the life cycle of an application development process you worked on previously.
    What the interviewer looks for is communication of requirements, planning, modeling, construction and deployment on the back end.
  • Here's a hypothetical project. Explain how you would go about it.
    They want to know how you would break your work down into tasks and how many weeks for each task. I'm really looking to find out about planning methods, their skill set and how quickly they can execute.
  • How do you respond to requirement changes in the middle of a cycle?
  • What type of methodology have you used in the past? What are its drawbacks?
  • What are different techniques for prototyping an application?
    Similar question: Do you feel there is value in wireframing an application? Why?
  • How do you manage conflicts in Web applications when there are different people managing data?
  • Tell me something you learned from a team member in the last year.
  • What software testing procedures have you used to perform a QA?
Once the coding skills verified. Sample I
· The Activity life cycle is must. Ask about the different phases of Activity Life cycle. For example: when and how the activity comes to foreground?
· Check the 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
· Ask about different Kinds of context
· Ask about different Storage Methods in android
· Kinds of Log debugger and Debugger Configuration
· How to debug the application on real device.
· 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 avoid ANR status
· How to do Memory management
· Ask about IPC
· What is onCreate(Bundle savedInstanceState), Have you used savedInstanceState when and why?
· To check how updated the person is just ask about what are Fragments in an Activity
If this is an Android specific job, just ask the obvious stuff. Sample II
  • Application lifecycle
  • When to use a service
  • How to use a broadcast receiver and register it both in the manifest and in code
  • Intent filters
  • Stuff about what manifest attributes and tags mean
  • The types of flags to run an application
    • FLAG_ACTIVITY_NEW_TASK
    • FLAG_ACTIVITY_CLEAR_TOP
    • etc
  • 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)