Sunday, 31 March 2013

Location


To find the location of user, comes with cost and cost includes battery, CPU etc.
Android provides two way to get the user location:

1. Network Provider:
a) It uses cell tower and wifi signals. 
b) It works indoor and outdoor both.
c) It consumes less battery and takes less time to give result.

2. GPS Provider:
a) It is more accurate than Network Provider.
b) It works only outdoor.
c) It consumes more battery and takes more time to give result.

Permission:
1. ACCESS_COARSE_LOCATION:
Required for NETWORK_PROVIDER.
2. ACCESS_FINE_LOCATION:
Required for GPS_PROVIDER. It includes permission for NETWORK_PROVIDER too. Use this if you are using both provider.

To get the location, we need to register the listner(LocationListener) with LocationManager:

// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
    public void onLocationChanged(Location location) {
      // Called when a new location is found by the network location provider.
      makeUseOfNewLocation(location);
    }
    public void onStatusChanged(String provider, int status, Bundle extras) {}
    public void onProviderEnabled(String provider) {}
    public void onProviderDisabled(String provider) {}
  };

// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER/LocationManager.NETWORK_PROVIDER, min_time_interval, min_distance_change, locationListener);

Note:
1) Setting min_time_interval and min_distance_change to 0 receives the updates as frequently as possible.
2) To get the location updates from both provider, you need to register twice one with GPS_PROVIDER and second with NETWORK_PROVIDER.

Getting Location while registering:
You will not get location as soon as you register, it takes time. So for first time
we can use the last cached location.

String locationProvider = LocationManager.NETWORK_PROVIDER;
// Or use LocationManager.GPS_PROVIDER
Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);

Note:
It may happen that last received location is more accurate than the newest one.
How to Know which provider to use?
If you are not sure  know about the best provider for your requirments then you can use Criteria class:

Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
/**
*  Get the critria list here(http://developer.android.com/reference/android/location/Criteria.html).
*/
String provider = locationManager.getBestProvider(criteria, true);

Note:
For detailed analysis, follow the doc.



profile for Vineet Shukla at Stack Overflow, Q&A for professional and enthusiast programmers

Saturday, 29 September 2012

Animation Prior to Android 3.0

Before Android 3.0, we have View Animation which covers:

1. Tween Animation

Tween animation calculates the animation with information such as the start point, end point, size, rotation, and other common aspects of an animation.

A sequence of animation instructions defines the tween animation, defined by either XML or Android code. As with defining a layout, an XML file is recommended because it's more readable, reusable, and swappable than hard-coding the animation.


The animation XML file belongs in the res/anim/ directory of your Android project. The file must have a single root element: this will be either a single <alpha><scale><translate><rotate>, interpolator element, or<set> element that holds groups of these elements (which may include another <set>).


Note:

Be sure to use the proper format for what you want ("50" for 50% relative to the parent, or "50%" for 50% relative to itself).

Using translate animation we can do animation like slide left, slide right, slide up, slide down, shake etc.


slide_left.xml




<?xml version="1.0" encoding="utf-8"?>
<translate
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromXDelta="0%"
    android:toXDelta="-100%"
    android:interpolator="@android:anim/linear_interpolator"
    android:duration="2000" />


slide_right.xml


<?xml version="1.0" encoding="utf-8"?>
<translate
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromXDelta="0%"
    android:toXDelta="100%"
    android:interpolator="@android:anim/linear_interpolator"
    android:duration="2000" />

slide_up.xml



<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromYDelta="0%"
    android:toYDelta="-100%"
    android:duration="2000"
    android:interpolator="@android:anim/linear_interpolator" />


slide_down.xml


<?xml version="1.0" encoding="utf-8"?>
<translate
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromYDelta="0%"
    android:toYDelta="100%"
    android:duration="2000"
    android:interpolator="@android:anim/linear_interpolator" />

shake.xml




<?xml version="1.0" encoding="utf-8"?>
<translate
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromXDelta="0"
    android:toXDelta="100"
    android:duration="1000"
    android:interpolator="@android:anim/cycle_interpolator"
    android:repeatCount="50"
    android:repeatMode="reverse" />


Note:

To implement shake behaviour we need to use cycle interpolator and repeatCount attribute. 



Using rotate animation we can do rotation with different angles and points.


rotate_360.xml


<?xml version="1.0" encoding="utf-8"?>
<rotate
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="0"
    android:toDegrees="360"
    android:pivotX="50%"
    android:pivotY="50%"
    android:interpolator="@android:anim/linear_interpolator"
    android:duration="2000" />

Note:




android:pivotX
Float. The X coordinate to remain fixed when the object is scaled.
android:pivotY
Float. The Y coordinate to remain fixed when the object is scaled.


Using alpha animation we can do fade in/ fade out animation.

fade_in.xml




<?xml version="1.0" encoding="utf-8"?>
<alpha
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromAlpha="0"
    android:toAlpha="1"
    android:interpolator="@android:anim/linear_interpolator"
    android:duration="2000" />


fade_out.xml



<?xml version="1.0" encoding="utf-8"?>
<alpha
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="2000"
    android:fromAlpha="1"
    android:interpolator="@android:anim/linear_interpolator"
    android:toAlpha="0" />


Loading View Animation:


Animation animation = AnimationUtils.loadAnimation(this, R.anim.yourAnim);
animation.startAnimation(animation);

2. Frame by Frame Animation

Drawable animation lets you load a series of Drawable resources one after another to create an animation.

frame_animation.xml



<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:oneshot="false">
    <item android:drawable="@drawable/active" android:duration="500" />
    <item android:drawable="@drawable/deactive" android:duration="500" />
</animation-list>


Note:
By setting the android:oneshot attribute of the list to true, it will cycle just once then stop and hold on the last frame.

Loading Frame Animation:



@Override
public void onWindowFocusChanged(boolean hasFocus) {
  // TODO Auto-generated method stub
super.onWindowFocusChanged(hasFocus);
((AnimationDrawable)view.getBackground()).start();
}



profile for Vineet Shukla at Stack Overflow, Q&A for professional and enthusiast programmers

Thursday, 23 August 2012

Passing Data Object from one Activity to Another

We often need to pass data model from one activity to another. For this Android provides a way to do this and it is called Parcelable.

Using parcelable we can pass different types of data:

1. int and int[]
2. float and float[]
3. double and double[]
4. byte and byte[]
5. boolean[]
6. long and long[]
7. String and String[]
8. Object and Object[]
9. List and List<T>
10. Map
11. Nested data model and many more.

Below I am covering some basic types and rest you can try on your own.

Create a data Model: TestModel


public class TestModel implements Parcelable{

public int testInt;
public Double testDouble;
public String testString;
public boolean testBoolean;
private byte testByte;

public TestModel() {
testInt = 0;
testDouble = 0.0;
testString = "";
testBoolean = false;
testByte = 0;
}

//Get your data here in the same order in which you have set it. public TestModel(Parcel in) {
testInt = in.readInt();
testDouble = in.readDouble();
testString = in.readString();
boolean[] flag = new boolean[1];
in.readBooleanArray(flag);
testBoolean = (flag[0] == true)? true : false;
testByte = in.readByte();
}

public int getTestInt() {
return testInt;
}

public void setTestInt(int testInt) {
this.testInt = testInt;
}

public Double getTestDouble() {
return testDouble;
}

public void setTestDouble(Double testDouble) {
this.testDouble = testDouble;
}

public String getTestString() {
return testString;
}

public void setTestString(String testString) {
this.testString = testString;
}

public boolean isTestBoolean() {
return testBoolean;
}

public void setTestBoolean(boolean testBoolean) {
this.testBoolean = testBoolean;
}

public byte getTestByte() {
return testByte;
}

public void setTestByte(byte testByte) {
this.testByte = testByte;
}

//Write your data here

public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(testInt);
dest.writeDouble(testDouble);
dest.writeString(testString);
dest.writeBooleanArray(new boolean[]{testBoolean});
dest.writeByte(testByte);

}

public static final Parcelable.Creator<TestModel> CREATOR = new Parcelable.Creator<TestModel>()
{
public TestModel createFromParcel(Parcel in)
{
return new TestModel(in);
}
public TestModel[] newArray(int size)
{
return new TestModel[size];
}
};

public int describeContents() {
// TODO Auto-generated method stub
return 0;
}

}

Passing data model to another Activity:
//Setting data in the model
TestModel  model = new TestModel ();
//Set values in the model...

//Create intent

Intent intent = new Intent(getApplicationContext(),YourActivity.class);
Bundle bundle = new Bundle();                //create bundle..
bundle.putParcelable("data",  model  );    
intent.putExtras(bundle);                    //set the bundle..
startActivity(intent);

Get the data in the Activity:




Bundle bundle = getIntent().getExtras();
TestModel  model = bundle.getParcelable("data");


profile for Vineet Shukla at Stack Overflow, Q&A for professional and enthusiast programmers

Sunday, 22 July 2012

Working with HttpsUrlConnection


Refer this doc over HttpsUrlConnection.
To create key and import certificate use Portecle tool.
To create key using Keytool, follow the doc.


String query = "emailId=" + URLEncoder.encode("xxx@gmail.com", HTTP.UTF_8) + "&pwd=" + URLEncoder.encode("password", HTTP.UTF_8);


HttpsURLConnection urlConnection = null;
try{
    KeyStore keyStore = KeyStore.getInstance("BKS");
    InputStream in =  
    getResources().openRawResource(R.raw.keystore);
    keyStore.load(in, "password".toCharArray());
    TrustManagerFactory tmf = 
    TrustManagerFactory.getInstance("X509");
    tmf.init(keyStore);


    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, tmf.getTrustManagers(), null);
    System.setProperty("http.keepAlive", "false");
    URL url = new URL("https://www.google.co.in/");
    urlConnection = (HttpsURLConnection) url.openConnection();
     
urlConnection.setSSLSocketFactory(context.getSocketFactory());
    urlConnection.setDoInput(true);
    urlConnection.setDoOutput(true);
    urlConnection.setRequestMethod("POST");
    urlConnection.setRequestProperty("content-type",
    "application/x-www-form-urlencoded");
    urlConnection.setRequestProperty("Content-length", "" +  query.getBytes().length);

     //To post data...
     DataOutputStream output = new DataOutputStream( urlConnection.getOutputStream() );
     output.writeBytes( query );
     output.flush();
     output.close();

     InputStream stream = null;


     if ( urlConnection.getResponseCode() == 201 )
stream = urlConnection.getInputStream();
     else
       //Report error...

     urlConnection.disconnect();


}catch(Exception e){
     urlConnection.disconnect();
}



profile for Vineet Shukla at Stack Overflow, Q&A for professional and enthusiast programmers

Thursday, 5 July 2012

WebView Settings


Note: To know the HTML5 browser support for your device, you only need to open the url in your browser: http://html5test.com/


WebSettings settings = mWebView.getSettings();
//To enable the built-in zoom
settings.setBuiltInZoomControls(true);


//To enable JavaScript
settings.setJavaScriptEnabled(true);


//To enable Plugin
settings.setPluginState(PluginState.ON);


Plugin:
plug-ins are commonly used in web browsers to play video, 
scan for viruses, and display new file types. 
Well-known plug-ins examples include 
Adobe Flash Player, QuickTime, and Microsoft Silverlight.


//To enable or disable file access within WebView. 
//File access is enabled by default.
settings.setAllowFileAccess(true);


//To enable dom storage
//DOM Storage is a way to store meaningful amounts of 
//client-side data in a persistent and secure manner.
settings.setDomStorageEnabled(true);


//To enable wide viewport.
settings.setUseWideViewPort(true);


//To enable JavaScript to open windows automatically.
settings.setJavaScriptCanOpenWindowsAutomatically(true);


//To enable twitter, youtube etc.
settings.setUserAgentString("Mozilla/5.0 (Linux; U; Android 2.0; en-us; Droid Build/ESD20) 
AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/530.17");


Detailed Description: WebSettingsWebView
profile for Vineet Shukla at Stack Overflow, Q&A for professional and enthusiast programmers

Monday, 25 June 2012

Programmatically add Image to Gallery


private void addPicToGallery() {
    Intent media = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);


//mCurrentPhotoPath is the path to image.
    File f = new File(mCurrentPhotoPath);
    Uri contentUri = Uri.fromFile(f);
    media.setData(contentUri);
    this.sendBroadcast(media);
}
profile for Vineet Shukla at Stack Overflow, Q&A for professional and enthusiast programmers

Monday, 12 March 2012

Single textview with multiple action

We can use single textview for:

1.  Different textsizes.
2.  Different colors.
3.  Click event.
4.  Linking with URL etc.

private void prepareStylishText ( TextView view ) {
        SpannableStringBuilder spanTxt = new SpannableStringBuilder("Different");

        //set the text clickable.
        spanTxt.setSpan(new ClickableSpan() {

            @Override
            public void onClick(View widget) {
                // TODO Auto-generated method stub
                Toast.makeText(getApplicationContext(), "Different style text in android.",
                        Toast.LENGTH_SHORT).show();
            }
        },
                0, spanTxt.length(), 0 );

        //set the text color.
        spanTxt.setSpan(new ForegroundColorSpan(Color.RED),
                0, spanTxt.length(), 0 );

        //add more text.
        spanTxt.append(" style");
        spanTxt.setSpan(new ForegroundColorSpan(Color.BLUE),
            spanTxt.length() - " style".length(), spanTxt.length(), 0 );

        spanTxt.append(" text with single textview in");

        spanTxt.setSpan(new ForegroundColorSpan(Color.BLACK),
            spanTxt.length() - " text with single textview in".length(), spanTxt.length(), 0 );

        spanTxt.append(" android.");

        //make the textsize 2 times.
        spanTxt.setSpan(new RelativeSizeSpan(2f), spanTxt.length() - " android".length(), spanTxt.length(), 0  );

        //make the link.
        spanTxt.setSpan(new URLSpan("http://developer.android.com/index.html"), spanTxt.length() - " android".length(), spanTxt.length(), 0 );

        //set the color after the link else the link color will override it.
        spanTxt.setSpan(new ForegroundColorSpan(Color.GREEN),
                spanTxt.length() - " android".length(), spanTxt.length(), 0 );

        //make click and url to work.
        view.setMovementMethod(LinkMovementMethod.getInstance());
        view.setText(spanTxt, BufferType.SPANNABLE);
    }

Output:
 Note: You can also use SpannableString in place of SpannableStringBuilder.

profile for Vineet Shukla at Stack Overflow, Q&A for professional and enthusiast programmers

Tuesday, 6 March 2012

Fragment Dialog and Date-Time Picker

With the fragment use we often need to use dialog with fragment. Here we will see how to use dialog with fragment and How to use Date-Time picker with the fragment.

Note: Check Fragment.

1. Extend DialogFragment:

public class CustomDialogFragment extends DialogFragment{
       //Define constants for date-time picker.
       public final int DATE_PICKER = 1;
       public final int TIME_PICKER = 2;
       public final int DIALOG = 3;
}

2. Add constructor with Fragment argument as It will let know over which fragment, the dialog should be shown.

private Fragment mCurrentFragment;
public CustomDialogFragment ( Fragment fragment ) {
        mCurrentFragment = fragment;
}

3.  Override onCreateDialog:

public Dialog onCreateDialog(Bundle savedInstanceState) {
        Bundle bundle = new Bundle();
        bundle = getArguments();
        int id = bundle.getInt("dialog_id");
        switch (id) {
        case DATE_PICKER:
            return new DatePickerDialog(getActivity(),
                    (OnDateSetListener)mCurrentFragment, bundle.getInt("year"),
                    bundle.getInt("month"), bundle.getInt("day"));
   
       case TIME_PICKER:
            return new TimePickerDialog(getActivity(),
                    (OnTimeSetListener)mCurrentFragment,          bundle.getInt("hour"),
                    bundle.getInt("minute"), false);
        }

       case DIALOG:
       //Define your custom dialog or alert dialog here and return it.
       return dialog;
    }

Note: Implement OnDateSetListener, OnTimeSetListener on Fragment.

4. Show the dialog:

CustomDialogFragment dialog = new CustomDialogFragment(YourFragment.this);
Bundle bundle = new Bundle();
bundle.putInt("dialog_id", DATE_PICKER);
bundle.putInt("year", mYear);
bundle.putInt("month", mMonth);
bundle.putInt("day", mDay);
dialog.setArguments(bundle);
dialog.show(getFragmentManager(), "dialog");

Note: For detail description follow the link.

profile for Vineet Shukla at Stack Overflow, Q&A for professional and enthusiast programmers

Monday, 5 March 2012

Useful stuff

Here is nothing new but I wanted to bind some useful stuff that I could not find in one place.

1. Invoke the device's gallery and get the Image/video URI. 

private void invokeGallery () {
     Intent intent = new Intent();
     intent.setAction(Intent.ACTION_PICK);
     intent.setType("image/*");
     startActivityForResult(intent, 001);
}

   @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if ( requestCode == 001 && data != null && data.getData() != null ) {
            URi imageUri = data.getData();
            imageview.setImageURI(imageUri );
        }
    }

2. Launch default contact picker and get the contact details.

private void launchContactPicker() {
        Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
                Contacts.CONTENT_URI);
        startActivityForResult(contactPickerIntent, 1001);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   if ( requestCode == 1001 ) {
      Bundle _data = data.getExtras();
      Set<String> keys = _data.keySet();
      Iterator<String> iterate = keys.iterator();
      if ( iterate.hasNext() ) {
         String key = iterate.next();
         String contactName = _data.get(key).toString();
      //To query Content Provider for contact number:
      Cursor cursor = getContentResolver().query(android.provider.ContactsContract.Contacts.CONTENT_URI, null,    android.provider.ContactsContract.Contacts.DISPLAY_NAME + "=?", new String[]{contactName }, null);    
      //To query the Content Provider for Email ID's:

      //Using above cursor:
      String id = cursor .getString(cursor .getColumnIndex(android.provider.ContactsContract.Contacts._ID));
      Cursor emailCursor = getContentResolver().query(android.provider.ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, android.provider.ContactsContract.CommonDataKinds.Email.CONTACT_ID+ " = " + id, null, null);

      if(emailCursor .getCount() > 0){
         emailCursor .moveToFirst();
         do {
             String _emailId = emailCursor.getString(emailCursor        .getColumnIndex(android.provider.ContactsContract.CommonDataKinds.Email.DATA));            }while(mCursor.moveToNext());
        }

            }
        }
}

3. Get device resolution and desity.

DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
 //Desity
switch(metrics.densityDpi){
    case DisplayMetrics.DENSITY_LOW:
         break;
    case DisplayMetrics.DENSITY_MEDIUM:
         break;
    case DisplayMetrics.DENSITY_HIGH:
         break;
}
//Resolution
int screenWidth = metrics .widthPixels;
int screenHeight = metrics .heightPixels;

profile for Vineet Shukla at Stack Overflow, Q&A for professional and enthusiast programmers