Ad

Sunday, November 17, 2013

Android get current GPS location

You can Find location either GPS_PROVIDER or NETWORK_PROVIDER
Overview of location services in Android , LocationManager class at the heart of location services in Android.
Here is one example which try to find location using GPS , if your GPS not available then try to use network for find location
Demo Code
Activity - AndroidGPSTrackingActivity.java
public class AndroidGPSTrackingActivity extends Activity {
  
    Button btnShowLocation;
  
    // GPSTracker class
    GPSTracker gps;
  
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
      
        btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
      
        // show location button click event
        btnShowLocation.setOnClickListener(new View.OnClickListener() {
          
            @Override
            public void onClick(View arg0) {      
                // create class object
                gps = new GPSTracker(AndroidGPSTrackingActivity.this);

                // check if GPS enabled      
                if(gps.canGetLocation()){
                  
                    double latitude = gps.getLatitude();
                    double longitude = gps.getLongitude();
                  
                    // \n is for new line
                    Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();  
                }else{
                    // can't get location
                    // GPS or Network is not enabled
                    // Ask user to enable GPS/network in settings
                    gps.showSettingsAlert();
                }
              
            }
        });
    }
  
}

GPSTracke.java
public class GPSTracker extends Service implements LocationListener {

    private final Context mContext;

    // flag for GPS status
    boolean isGPSEnabled = false;

    // flag for network status
    boolean isNetworkEnabled = false;

    // flag for GPS status
    boolean canGetLocation = false;

    Location location; // location
    double latitude; // latitude
    double longitude; // longitude

    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

    // Declaring a Location Manager
    protected LocationManager locationManager;

    public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }

    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);

            // getting GPS status
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);

            // getting network status
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                this.canGetLocation = true;
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return location;
    }
  
    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app
     * */
    public void stopUsingGPS(){
        if(locationManager != null){
            locationManager.removeUpdates(GPSTracker.this);
        }      
    }
  
    /**
     * Function to get latitude
     * */
    public double getLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }
      
        // return latitude
        return latitude;
    }
  
    /**
     * Function to get longitude
     * */
    public double getLongitude(){
        if(location != null){
            longitude = location.getLongitude();
        }
      
        // return longitude
        return longitude;
    }
  
    /**
     * Function to check GPS/wifi enabled
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }
  
    /**
     * Function to show settings alert dialog
     * On pressing Settings button will lauch Settings Options
     * */
    public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
       
        // Setting Dialog Title
        alertDialog.setTitle("GPS is settings");

        // Setting Dialog Message
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // On pressing Settings button
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });

        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }

    @Override
    public void onLocationChanged(Location location) {
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

}
Layout - main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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/btnShowLocation"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Location"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"/>

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

Android Internal and External storage

  • Android Internal Storage
    •  Internal storage are private to your application and other applications cannot access them (nor can the user).
    •  When the user uninstalls your application, these files are removed.
  •  Android External Storage
    •  External storage such as SD card can also store application data.
    •  There's no security enforced upon files you save to the external storage.
    •  All applications can read and write files placed on the external storage and the user can remove them.
    •  You need Read and Write permission in External Storage
In this example we are going to save data from an EditText to both Internal Storage and External Storage, and then try to get the data back from the respective storage places.

 FileOutputStream :For save Data
 FileInputStream  :For Display data



Layout - 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" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Storage Demo" />

    <EditText
        android:id="@+id/InputText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:gravity="top|left"
        android:inputType="textMultiLine"
        android:lines="5"
        android:minLines="2"
        android:text="Internal and External Storage" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/InternalStorageSave"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Internal Storage(Save)" />

    <Button
        android:id="@+id/InternalStorageGet"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Internal Storage(Display)" />

    <Button
        android:id="@+id/ExternalStorageSave"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="External Storage(Save)" />

    <Button
        android:id="@+id/ExternalStorageGet"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="External Storage(Displays)" />

    <TextView
        android:id="@+id/responseText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="5dp"
        android:text=""
        android:textAppearance="?android:attr/textAppearanceMedium" />

</LinearLayout>

Activity - MainActivity.java

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;



public class MainActivity extends Activity implements OnClickListener {

    private String filename = "StorageFile.txt";
    private String filepath = "FileStorage";
    File myInternalFile;
    File myExternalFile;

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

        ContextWrapper contextWrapper = new ContextWrapper(
                getApplicationContext());
        File directory = contextWrapper.getDir(filepath, Context.MODE_PRIVATE);
        myInternalFile = new File(directory, filename);

        Button saveToInternalStorage = (Button) findViewById(R.id.InternalStorageSave);
        saveToInternalStorage.setOnClickListener(this);

        Button readFromInternalStorage = (Button) findViewById(R.id.InternalStorageGet);
        readFromInternalStorage.setOnClickListener(this);

        Button saveToExternalStorage = (Button) findViewById(R.id.ExternalStorageSave);
        saveToExternalStorage.setOnClickListener(this);

        Button readFromExternalStorage = (Button) findViewById(R.id.ExternalStorageGet);
        readFromExternalStorage.setOnClickListener(this);

        // check if external storage is available and not read only
        if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
            saveToExternalStorage.setEnabled(false);
        } else {
            myExternalFile = new File(getExternalFilesDir(filepath), filename);
        }

    }

    public void onClick(View v) {

        EditText myInputText = (EditText) findViewById(R.id.InputText);
        TextView responseText = (TextView) findViewById(R.id.responseText);
        String myData = "";

        switch (v.getId()) {
        case R.id.InternalStorageSave:
            try {
                FileOutputStream fos = new FileOutputStream(myInternalFile); // save
                fos.write(myInputText.getText().toString().getBytes());
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            myInputText.setText("");
            responseText.setText("Saved to Internal Storage.(StorageFile.txt)");
            break;

        case R.id.InternalStorageGet:
            try {
                FileInputStream fis = new FileInputStream(myInternalFile); // display
                DataInputStream in = new DataInputStream(fis);
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(in));
                String strLine;
                while ((strLine = br.readLine()) != null) {
                    myData = myData + strLine;
                }
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            myInputText.setText(myData);
            responseText
                    .setText("Data retrieved from Internal Storage.(StorageFile.txt)");

            break;

        case R.id.ExternalStorageSave:
            try {
                FileOutputStream fos = new FileOutputStream(myExternalFile);
                fos.write(myInputText.getText().toString().getBytes());
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            myInputText.setText("");
            responseText.setText("Saved to External Storage.(StorageFile.txt)");
            break;

        case R.id.ExternalStorageGet:
            try {
                FileInputStream fis = new FileInputStream(myExternalFile);
                DataInputStream in = new DataInputStream(fis);
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(in));
                String strLine;
                while ((strLine = br.readLine()) != null) {
                    myData = myData + strLine;
                }
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            myInputText.setText(myData);
            responseText
                    .setText("Data retrieved from Internal Storage.(StorageFile.txt)");
            break;

        }
    }

    private static boolean isExternalStorageReadOnly() {
        String extStorageState = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
            return true;
        }
        return false;
    }

    private static boolean isExternalStorageAvailable() {
        String extStorageState = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {
            return true;
        }
        return false;
    }

}

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


Thursday, March 21, 2013

Android get lat and long from address



You can use the Google Geocoder service in the Google Maps API to convert from your location name to a latitude and longitude. So you need some code like

The idea is simple. Make a request to Google Map server and it will return an JSON or XML. Then, parse the JSON to get Lat and Long.

 I have used Google Maps API Here.


    // JSON Node names
    private static final String TAG_RESULTS = "results";
    private static final String TAG_GEOMETRY = "geometry";
    private static final String TAG_VIEWPORT = "viewport";
    private static final String TAG_NORTHEAST = "northeast";
    private static final String TAG_LAT = "lat";
    private static final String TAG_LNG = "lng";
    // contacts JSONArray
    JSONArray results = null;

Android get lat and long from address

// Creating JSON Parser instance
        JSONParser jParser = new JSONParser();

        address = "Rajkot, Gujarat, India";

        address = address.replaceAll(" ", "%20");
        url = "http://maps.googleapis.com/maps/api/geocode/json?address="
                + address + "&sensor=true";

        // getting JSON string from URL
        JSONObject json = jParser.getJSONFromUrl(url);

        try {
            // Getting Array of results
            results = json.getJSONArray(TAG_RESULTS);

            Toast.makeText(getApplication(),
                    "Number of results : " + results.length(),
                    Toast.LENGTH_LONG).show();

            for (int i = 0; i < results.length(); i++) {
                JSONObject r = results.getJSONObject(i);

                // geometry and location is again JSON Object
                JSONObject geometry = r.getJSONObject(TAG_GEOMETRY);

                JSONObject viewport = geometry.getJSONObject(TAG_VIEWPORT);

                JSONObject northest = viewport.getJSONObject(TAG_NORTHEAST);

                String lat = northest.getString(TAG_LAT);
                String lng = northest.getString(TAG_LNG);

                tvlat.setText(lat);
                tvlng.setText(lng);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }


JSONParser.java

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();           

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}


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



Wednesday, March 13, 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(
Jelly Bean)

12. Give the new Android platform for mobile phones?
Android 4.0 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, March 12, 2013

Android 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, December 21, 2012

Android 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, December 20, 2012

Android 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;
    }
}