HTC One X

HTC ONE X


GENERAL 2G Network GSM 850 / 900 / 1800 / 1900
3G Network HSDPA 850 / 900 / 1900 / 2100
HTD-SCDMA/ TD-HSPA 1900 / 2100 – HTC One XT
SIM Micro-SIM
Announced 2012, February
Status Available. Released 2012, May
BODY Dimensions 134.4 x 69.9 x 8.9 mm (5.29 x 2.75 x 0.35 in)
Weight 130 g (4.59 oz)
DISPLAY Type Super IPS LCD2 capacitive touchscreen, 16M colors
Size 720 x 1280 pixels, 4.7 inches (~312 ppi pixel density)
Multitouch Yes
Protection Corning Gorilla Glass
– HTC Sense UI
SOUND Alert types Vibration, MP3, WAV ringtones
Loudspeaker Yes
3.5mm jack Yes
MEMORY Card slot No
Internal 16/32 GB (26 GB user available), 1 GB RAM
DATA GPRS Yes
EDGE Yes
Speed HSDPA, 21 Mbps; HSUPA, 5.76 Mbps
WLAN Wi-Fi 802.11 a/b/g/n, Wi-Fi Direct, DLNA, Wi-Fi hotspot
Bluetooth Yes, v4.0 with A2DP
NFC Yes
USB Yes, microUSB v2.0 (MHL)
CAMERA Primary 8 MP, 3264×2448 pixels, autofocus, LED flash, check quality
Features Simultaneous HD video and image recording, geo-tagging, face and smile detection
Video Yes, 1080p@24fps, stereo sound rec., video stabilization, check quality
Secondary Yes, 1.3 MP, 720p
FEATURES OS Android OS, v4.0 (Ice Cream Sandwich), upgradable to v4.1.1 (Jelly Bean)
Chipset Nvidia Tegra 3
CPU Quad-core 1.5 GHz
GPU ULP GeForce
Sensors Accelerometer, gyro, proximity, compass
Messaging SMS (threaded view), MMS, Email, Push Email

HTC ONE X

Browser HTML, Adobe Flash
Radio Stereo FM radio with RDS
GPS Yes, with A-GPS support
Java Yes, via Java MIDP emulator
Colors Gray, White
– Beats Audio
– Active noise cancellation with dedicated mic
– Dropbox (25 GB storage)
– TV-out (via MHL A/V link)
– SNS integration
– MP4/H.263/H.264/WMV player
– MP3/eAAC+/WMA/WAV player
– Google Search, Maps, Gmail,
YouTube, Calendar, Google Talk
– Document viewer/editor
– Voice memo/dial/commands
– Predictive text input
BATTERY Non-removable Li-Po 1800 mAh battery
Stand-by No official data
Talk time No official data
MISC SAR US 0.68 W/kg (head) 0.70 W/kg (body)
SAR EU 0.68 W/kg (head)

Samsung Galaxy S4

Samsung Galaxy S4

GENERAL 2G Network GSM 850 / 900 / 1800 / 1900
3G Network HSDPA 850 / 900 / 1900 / 2100
4G Network LTE
SIM Micro-SIM
Announced 2013, March
Status Coming soon. Exp. release 2013, April 26th
BODY Dimensions 136.6 x 69.8 x 7.9 mm (5.38 x 2.75 x 0.31 in)
Weight 130 g (4.59 oz)
DISPLAY Type Super AMOLED capacitive touchscreen, 16M colors
Size 1080 x 1920 pixels, 5.0 inches (~441 ppi pixel density)
Multitouch Yes
Protection Corning Gorilla Glass 3
– TouchWiz UI
SOUND Alert types Vibration; MP3, WAV ringtones
Loudspeaker Yes
3.5mm jack Yes
MEMORY Card slot microSD, up to 64 GB
Internal 16/32/64 GB storage, 2 GB RAM
DATA GPRS Yes
EDGE Yes
Speed HSDPA, 42.2 Mbps; HSUPA, 5.76 Mbps
WLAN Wi-Fi 802.11 a/b/g/n/ac, dual-band, DLNA, Wi-Fi Direct, Wi-Fi hotspot
Bluetooth Yes, v4.0 with A2DP, EDR, LE
NFC Yes
Infrared port Yes
USB Yes, microUSB v2.0 (MHL 2), USB On-the-go, USB Host
CAMERA Primary 13 MP, 4128 x 3096 pixels, autofocus, LED flash, check quality
Features Dual Shot, Simultaneous HD video and image recording, geo-tagging, touch focus, face and smile detection, image stabilization, HDR
Video Yes, 1080p@30fps, dual-video rec., check quality
Secondary Yes, 2 MP,1080p@30fps, dual video call
FEATURES OS Android OS, v4.2.2 (Jelly Bean)
Chipset Exynos 5 Octa 5410
CPU Quad-core 1.6 GHz Cortex-A15 & quad-core 1.2 GHz Cortex-A7
GPU PowerVR SGX 544MP3
Sensors Accelerometer, gyro, proximity, compass, barometer, temperature, humidity, gesture

http://www.geeky-gadgets.com/wp-content/uploads/2013/02/samsung-galaxy-s4-mini1.jpg

Messaging SMS(threaded view), MMS, Email, Push Mail, IM, RSS
Browser HTML5, Adobe Flash
Radio No
GPS Yes, with A-GPS support and GLONASS
Java Yes, via Java MIDP emulator
Colors White Frost, Black Mist
– Wireless charging (market dependent)
– S-Voice natural language commands and dictation
– Smart stay, Smart pause, Smart scroll
– Air gestures
– Dropbox (50 GB storage)
– Active noise cancellation with dedicated mic
– TV-out (via MHL 2 A/V link)
– SNS integration
– MP4/DivX/XviD/WMV/H.264/H.263 player
– MP3/WAV/eAAC+/AC3/FLAC player
– Organizer
– Image/video editor
– Document viewer (Word, Excel, PowerPoint, PDF)
– Google Search, Maps, Gmail,
YouTube, Calendar, Google Talk, Picasa
– Voice memo/dial/commands
– Predictive text input (Swype)
BATTERY Li-Ion 2600 mAh battery

Buy Micromax A 91 Ninja online for Rs 8,499.

Micromax A91 NInja

The device was spotted on online site Saholic, while India TV News reported that the device was also available at ManiacStore for Rs 8,990 and Sulekha.com for Rs 9,000.

The A91 Ninja
The dual sim phone runs on Android 4.0 (Ice Cream Sandwich) and comes with 4GB internal storage, expandable via microSD. It runs on a MediaTek MT6577 1GHz dual-core processor, and has a PowerVR SGX531 GPU.

Read more from this link.
http://www.firstpost.com/tech/micromax-a91-ninja-with-ics-is-now-on-sale-online-for-rs-8499-689222.html

How to create a simple PopUp Menu in Android?

Hello all…

This is a simple tutorial for creating a simple popup menu like the one you see in the action bar options button.
Actually this is fairly simple with actionBar. But if you don’t want the actionbar and only want the popup menu, then here is the solution.

PopUp in Android

You can read more about PopupMenu here
http://developer.android.com/reference/android/widget/PopupMenu.html

Note : The “PopupMenu” Class is only supported in versions from 3.0 (HoneyComb). So you must Set your project SDK to 3.0 or greater while testing this post.

Android 3.0(API Level 11) provide android.widget.PopupMenu class, to displays a Menu in a modal popup window anchored to a View. The popup will appear below the anchor view if there is room, or above it if there is not. If the IME is visible the popup will not overlap it until it is touched. Touching outside of the popup will dismiss it.

So here we start…

At first what you have to do is

1. Create a folder named “menu” in the “res” folder.

then create an XML named “popup.xml” in it and copy these contents to it.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/search"
        android:icon="@android:drawable/ic_menu_search"
        android:title="Search"/>
    <item
        android:id="@+id/add"
        android:icon="@android:drawable/ic_menu_add"
        android:title="Add"/>
    <item
        android:id="@+id/edit"
        android:icon="@android:drawable/ic_menu_edit"
        android:title="Edit">
        <menu>
            <item
                android:id="@+id/share"
                android:icon="@android:drawable/ic_menu_share"
                android:title="Share"/>
        </menu>
    </item>

</menu>

Now in your activity copy this code.
My Activity is named “PopupMenu1″…
So my code look like this…

package com.example.popuptest;

import android.app.Activity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.PopupMenu;
import android.widget.Toast;

public class PopupMenu1 extends Activity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.popup_menu_1);
	}

	public void onPopupButtonClick(View button) {
		PopupMenu popup = new PopupMenu(this, button);
		popup.getMenuInflater().inflate(R.menu.popup, popup.getMenu());

		popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
			public boolean onMenuItemClick(MenuItem item) {
				Toast.makeText(PopupMenu1.this,
						"Clicked popup menu item " + item.getTitle(),
						Toast.LENGTH_SHORT).show();
				return true;
			}
		});

		popup.show();
	}
}

Reading webpage contents as a string in Windows Phone 7.

Hello all….

I am new to Windows Phone 7. So I am starting by posting a simple tutorial Here.

In this post I will try to read a webpage contents as a string and show it in a MessageBox.

https://lh3.googleusercontent.com/-m_5Xb6PLJiE/UV23ivMTXiI/AAAAAAAAAPs/Nkxw2rwtqy0/w258-h428-p-o/1.png

Here is the complete code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO;

namespace PhoneApp1
{
    public partial class MainPage : PhoneApplicationPage
    {        
        public MainPage()
        {
            InitializeComponent();
            RequestAsync( new Uri("http://google.com"), (html, exc) =>
             {
                 if (exc == null)
                 {
                     Dispatcher.BeginInvoke(() => MessageBox.Show(html));
                 }
                 else
                 {
                     // handle exception appropriately
                 }
             });
        }

        public static void RequestAsync(Uri url, Action<string, Exception> callback)
        {
            if (callback == null)
            {
                throw new ArgumentNullException("callback");
            }

            try
            {
                var req = WebRequest.CreateHttp(url);

                AsyncCallback getTheResponse = ar =>
                {
                    try
                    {
                        string responseString;

                        var request = (HttpWebRequest)ar.AsyncState;

                        using (var resp = (HttpWebResponse)request.EndGetResponse(ar))
                        {
                            using (var streamResponse = resp.GetResponseStream())
                            {
                                using (var streamRead = new StreamReader(streamResponse))
                                {
                                    responseString = streamRead.ReadToEnd();
                                    Console.WriteLine(responseString);
                                }
                            }
                        }

                        callback(responseString, null);
                    }
                    catch (Exception ex)
                    {
                        callback(null, ex);
                    }
                };

                req.BeginGetResponse(getTheResponse, req);
            }
            catch (Exception ex)
            {
                callback(null, ex);
            }
        }
    }
}

How to send Data between two individual applications in Android?

We can send data between two individual applications in Android if the receiving application is configured to received that type of data.
For example if an application is to receive Image data then it’s manifest should contain the ImageFilter as Shown below

 <intent-filter>
                <action android:name="android.intent.action.SEND" />

                <category android:name="android.intent.category.DEFAULT" />

                <data android:mimeType="image/*" />
            </intent-filter>

For example ac activity in the receiving application is named “Receiver” then its entry in the AndroidManifest.xml should be like this.

 <activity
            android:name="com.example.receivingapplication.Receiver"
            android:label="@string/app_name" >             
            <intent-filter>
                <action android:name="android.intent.action.SEND" />

                <category android:name="android.intent.category.DEFAULT" />

                <data android:mimeType="image/*" />
            </intent-filter>
        </activity>

This line means that the Receiver application can receive any image type data.

Now in this post I have two application each have an activity. One is the Sending application and other is the receiving application.

At first I will explain what am I doing in “Sender application”

SENDING APPLICATION STARTS

My Only activity in the SenderApplication will have a layout like this

<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:text="Send Text" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:text="Send Image" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/textView1"
        android:layout_alignLeft="@+id/button1"
        android:layout_marginBottom="68dp"
        android:src="@drawable/ic_launcher" />

</LinearLayout>

My Activity will be looking like this

package com.example.sendingapplication;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class SendingActivity extends Activity {

	private static final int SELECT_PICTURE = 1;
	private String selectedImagePath;
	private ImageView img;

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

		img = (ImageView) findViewById(R.id.imageView1);
		Button send = (Button) findViewById(R.id.button1);
		send.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Intent sendIntent = new Intent();
				sendIntent.setAction(Intent.ACTION_SEND);
				sendIntent.putExtra(Intent.EXTRA_TEXT,
						"This is my text to send.");
				sendIntent.putExtra("MyKey",
						"This is second my text to send using my key.");
				sendIntent.setType("text/plain");
				startActivity(Intent.createChooser(sendIntent, "Send"));
			}
		});

		Button sendImage = (Button) findViewById(R.id.button2);
		sendImage.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent();
				intent.setType("image/*");
				intent.setAction(Intent.ACTION_GET_CONTENT);
				startActivityForResult(
						Intent.createChooser(intent, "Select Picture"),
						SELECT_PICTURE);
			}
		});

	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			if (requestCode == SELECT_PICTURE) {
				Uri selectedImageUri = data.getData();
				selectedImagePath = getPath(selectedImageUri);
				System.out.println("Image Path : " + selectedImagePath);
				img.setImageURI(selectedImageUri);
				sendImage(selectedImageUri);
			}
		}
	}

	void sendImage(Uri selectedImageUri) {
		Intent shareIntent = new Intent();
		shareIntent.setAction(Intent.ACTION_SEND);
		shareIntent.putExtra(Intent.EXTRA_STREAM, selectedImageUri);
		shareIntent.setType("image/*");
		startActivity(Intent.createChooser(shareIntent, "Send Image"));
	}

	public String getPath(Uri uri) {
		String[] projection = { MediaStore.Images.Media.DATA };
		Cursor cursor = managedQuery(uri, projection, null, null, null);
		int column_index = cursor
				.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	}

}

Note that for sharing data we have to do nothing for the Sending Application.

Now Our Sending application is Over

RECEIVING APPLICATION STARTS.

This is my only activity in the Receiving application.

package com.example.receivingapplication;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class ReceivingActivity extends Activity {

	private Bitmap bitmap;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		LinearLayout lin = new LinearLayout(this);

		Intent intent = getIntent();
		String action = intent.getAction();
		String type = intent.getType();
		TextView tv = new TextView(this);
		lin.addView(tv);
		lin.setOrientation(LinearLayout.VERTICAL);
		if (Intent.ACTION_SEND.equals(action) && type != null) {
			if ("text/plain".equals(type)) {

				tv.setText(intent.getExtras().getString(Intent.EXTRA_TEXT));
				tv.append("\n" + (intent.getExtras().getString("MyKey")));

			} else if (type.startsWith("image/")) {
				if (bitmap != null) {
					bitmap.recycle();
				}
				ImageView img = new ImageView(this);
				Bundle bundle = intent.getExtras();
				Uri uri = (Uri) bundle.get(Intent.EXTRA_STREAM);
				img.setImageURI(uri);
				lin.addView(img);
		}

		} else {
			// Handle other intents, such as being started from the home screen
		}
		setContentView(lin);
	}
}

This is the AndroidManifest for the Receiving application.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.receivingapplication"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.receivingapplication.ReceivingActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.SEND" />

                <category android:name="android.intent.category.DEFAULT" />

                <data android:mimeType="text/plain" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.SEND" />

                <category android:name="android.intent.category.DEFAULT" />

                <data android:mimeType="image/*" />
            </intent-filter>
        </activity>
    </application>

</manifest>

WATCH CAREFULLY THE INTENT FILTERS IN THE MANIFEST FOR THE RECEIVING ACTIVITY.
YOU CAN HAVE PLAIN TEXT, IMAGE OR MULTIPLE IMAGES SEND TO IT. I HAVE NOT WRITTEN CODE FOR SENDING MULTIPLE IMAGES NOW, IT WILL BE COMING IN THE NEXT UPDATE.

How to pass an object back from a finishing activity to the previous activity in android?

Hello all

This simple post tells you how to pass an object to next activity and pass it back when that activity is closed.

Check these posts before reading this post to get an overview of other methods.
1. How to pass an Object from One Activity to another in Android?

2. How to pass an arraylist value from one activity to another in android?

Note : The most important thing to note in this post is that for an object to be passed to an activity or back, the Object class should implement Serializable Interface.

Here MyObject is My class whose object is I am going to pass.
And the MyObject class should look like this.

MyObject.java

package com.example.passobjectback;

import java.io.Serializable;

public class MyObject implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	String name, website;

	public MyObject() {

	}

	public String getWebsite() {
		return website;
	}

	public void setWebsite(String website) {
		this.website = website;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}

This is my first activity that is sending MyObject to the Second Activity.

MainActivity.java

package com.example.passobjectback;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

public class MainActivity extends Activity {

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

		final MyObject myobj = new MyObject();
		myobj.setName("Coderz"); 
		myobj.setWebsite("CoderzHeaven.com");

		Intent intent = new Intent(MainActivity.this, Second.class);
		intent.putExtra("myobject", myobj);
		startActivityForResult(intent, 1);
	} 

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 1) {
			if (resultCode == Activity.RESULT_OK) {
				Bundle b = data.getExtras();
				if (b != null) {
					MyObject myobj = (MyObject) b.getSerializable("Obj");
					System.out.println("Name : " + myobj.getName()
							+ ", Website : " + myobj.getWebsite());
				}  
			} else if (resultCode == 0) {
				System.out.println("RESULT CANCELLED");    
			}
		}
	}  
}

Note that here I am starting my second activity directly but using “startActivityForResult” because I am expecting something back from the Second Activity when it closes.

So we should have this method in the MainActivity to get the results.

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	super.onActivityResult(requestCode, resultCode, data);

}

This is my Second Activity that is accepting my object and sending back the same object which is received in the intent in the “onActivityResult” function in the MainActivity.

Second.java.

package com.example.passobjectback;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;


public class Second extends Activity {

	MyObject myobj;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		this.setTitle("Second Activity");

		Bundle b = getIntent().getExtras();

		if (b != null) {
			myobj = (MyObject) getIntent().getExtras()
					.getSerializable("myobject");

		}
	}

	@Override
	public void onBackPressed() {
		Intent intent = new Intent();
 		intent.putExtra("Obj", myobj);
		setResult(Activity.RESULT_OK, intent);
		finish();
		super.onBackPressed();
	}

}


I am getting the object back in the “onActivityResult” in the MainActivity when we press BackButton in the second Activity.
This is how we send back the object in the backpressed function

@Override
	public void onBackPressed() {
		Intent intent = new Intent();
 		intent.putExtra("Obj", myobj);
		setResult(Activity.RESULT_OK, intent);
		finish();
		super.onBackPressed();
	}

The main thing to note is that if you are closing the activity using back button then you should write the setResult() before “super.onBackPressed();” statement.

How to change the Style of a button dynamically in android?

Here I am going to change the style of a default button to buttonStyleSmall. So after that the button will appear small.

this simple code does this.

Button myButton = new Button(context, null, android.R.attr.buttonStyleSmall);

The try this adding to a layout

RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
                                     RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.addRule(android.widget.RelativeLayout.ALIGN_PARENT_RIGHT);
rLayout.addView(rightButton, lp);

How to create a simple App Launcher in Android?

You have seen Launchers listing your apps. Ever wondered how they get the list of all apps.

https://lh4.googleusercontent.com/-30y4nKNVGI0/UUxx3Nb7kcI/AAAAAAAAANY/I3f-77piaX4/w762-h428-p-o-k/app_launcher.png

This program help you to list all apps installed in your phone and in a gridview and invoke them.

Here we use this class..
PackageManager
Class for retrieving various kinds of information related to the application packages that are currently installed on the device. You can find this class through getPackageManager().

ResolveInfo
Information that is returned from resolving an intent against an IntentFilter. This partially corresponds to information collected from the AndroidManifest.xml’s tags.

First we will create the adapter for the GridView.

MyAdapter.java

package com.coderzheaven.applauncher;

import java.util.List;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

public class MyAdapter extends BaseAdapter {

	private Context myContext;
	private List<ResolveInfo> MyAppList;
	PackageManager myPackageManager;

	MyAdapter(Context c, List<ResolveInfo> appIntentList) {
		myContext = c;
		MyAppList = appIntentList;
		myPackageManager = c.getPackageManager();
	}

	@Override
	public int getCount() {
		return MyAppList.size();
	}

	@Override
	public Object getItem(int position) {
		return MyAppList.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {

		ImageView imageView;
		if (convertView == null) {
			imageView = new ImageView(myContext);
			imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
			imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
			imageView.setPadding(8, 8, 8, 8);
		} else {
			imageView = (ImageView) convertView;
		}

		ResolveInfo resolveInfo = MyAppList.get(position);
		imageView.setImageDrawable(resolveInfo.loadIcon(myPackageManager));

		return imageView;

	}

}

Now the Activity that uses this adapter in the GridView.

package com.coderzheaven.applauncher;

import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.LinearLayout;

public class AppListActivity extends Activity {

	PackageManager myPackageManager;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		myPackageManager = getPackageManager();

		Intent intent = new Intent(Intent.ACTION_MAIN, null);
		intent.addCategory(Intent.CATEGORY_LAUNCHER);
		List<ResolveInfo> appIntentList = getPackageManager()
				.queryIntentActivities(intent, 0);

		GridView gridview = new GridView(this);
		gridview.setStretchMode(GridView.STRETCH_COLUMN_WIDTH);
		gridview.setNumColumns(GridView.AUTO_FIT);
		gridview.setHorizontalSpacing(30);
		gridview.setVerticalSpacing(30);
		gridview.setGravity(Gravity.CENTER);
		gridview.setColumnWidth(50);
		gridview.setPadding(10, 10, 10, 10);

		gridview.setAdapter(new MyAdapter(this, appIntentList));

		gridview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				ResolveInfo cleckedResolveInfo = (ResolveInfo) parent
						.getItemAtPosition(position);
				ActivityInfo clickedActivityInfo = cleckedResolveInfo.activityInfo;

				Intent intent = new Intent(Intent.ACTION_MAIN);
				intent.addCategory(Intent.CATEGORY_LAUNCHER);
				intent.setClassName(
						clickedActivityInfo.applicationInfo.packageName,
						clickedActivityInfo.name);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
						| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
				startActivity(intent);
			}

		});

		setContentView(gridview);
	}
}

How to encrypt and decrypt a file using “AES” algorithm in Android? – Google’s Advice

This is a simple example showing how to encrypt and decrypt a file in android.
what we will do in this post is

1. Generate a key for encrypting our data.
2. Create a file and save data using ENCRYPTION with our generated key to the SDCARD.
3. With the help of the key DECRYPT the File and show the contents.

An anti-pattern
A common (but incorrect) pattern that we’ve recently become aware of is to use SecureRandom as a means of generating deterministic key material, which would then be used to encrypt local credential caches. Examples are not hard to find, such as here, here, here, and elsewhere.

In this pattern, rather than storing an encryption key directly as a string inside an APK, the code uses a proxy string to generate the key instead — similar to a passphrase. This essentially obfuscates the key so that it’s not readily visible to attackers. However, a skilled attacker would be able to easily see around this strategy. We don’t recommend it.

This complete program does this.
Please check the Logcat for the output.

package com.coderzheaven.encryptfile;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;

public class MainActivity extends Activity {

	private String encryptedFileName = "Enc_File.txt";
	private static String algorithm = "AES";
	static SecretKey yourKey = null;

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

		saveFile("Hello From CoderzHeaven asaksjalksjals");
		decodeFile();

	}
	
	public static SecretKey generateKey(char[] passphraseOrPin, byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException {
	    // Number of PBKDF2 hardening rounds to use. Larger values increase
	    // computation time. You should select a value that causes computation
	    // to take >100ms.
	    final int iterations = 1000; 

	    // Generate a 256-bit key
	    final int outputKeyLength = 256;

	    SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
	    KeySpec keySpec = new PBEKeySpec(passphraseOrPin, salt, iterations, outputKeyLength);
	    SecretKey secretKey = secretKeyFactory.generateSecret(keySpec);
	    return secretKey;
	}

	public static SecretKey generateKey() throws NoSuchAlgorithmException {
		// Generate a 256-bit key
		final int outputKeyLength = 256;
		SecureRandom secureRandom = new SecureRandom();
		// Do *not* seed secureRandom! Automatically seeded from system entropy.
		KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
		keyGenerator.init(outputKeyLength, secureRandom);
		yourKey = keyGenerator.generateKey();
		return yourKey;
	}

	public static byte[] encodeFile(SecretKey yourKey, byte[] fileData)
			throws Exception {
		byte[] encrypted = null;
		byte[] data = yourKey.getEncoded();
		SecretKeySpec skeySpec = new SecretKeySpec(data, 0, data.length,
				algorithm);
		Cipher cipher = Cipher.getInstance(algorithm);
		cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(
				new byte[cipher.getBlockSize()]));
		encrypted = cipher.doFinal(fileData);
		return encrypted;
	}

	public static byte[] decodeFile(SecretKey yourKey, byte[] fileData)
			throws Exception {
		byte[] decrypted = null;
		Cipher cipher = Cipher.getInstance(algorithm);
		cipher.init(Cipher.DECRYPT_MODE, yourKey, new IvParameterSpec(
				new byte[cipher.getBlockSize()]));
		decrypted = cipher.doFinal(fileData);
		return decrypted;
	}

	void saveFile(String stringToSave) {
		try {
			File file = new File(Environment.getExternalStorageDirectory()
					+ File.separator, encryptedFileName);
			BufferedOutputStream bos = new BufferedOutputStream(
					new FileOutputStream(file));
			yourKey = generateKey();
			byte[] filesBytes = encodeFile(yourKey, stringToSave.getBytes());
			bos.write(filesBytes);
			bos.flush();
			bos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	void decodeFile() {

		try {
			byte[] decodedData = decodeFile(yourKey, readFile());
			String str = new String(decodedData);
			System.out.println("DECODED FILE CONTENTS : " + str);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public byte[] readFile() {
		byte[] contents = null;

		File file = new File(Environment.getExternalStorageDirectory()
				+ File.separator, encryptedFileName);
		int size = (int) file.length();
		contents = new byte[size];
		try {
			BufferedInputStream buf = new BufferedInputStream(
					new FileInputStream(file));
			try {
				buf.read(contents);
				buf.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return contents;
	}

}


IF YOU WANT MORE SUCURITY THEN USE THE BELOW CODE…

If your app needs additional encryption, a recommended approach is to require a passphase or PIN to access your application. This passphrase could be fed into PBKDF2 to generate the encryption key. (PBKDF2 is a commonly used algorithm for deriving key material from a passphrase, using a technique known as “key stretching”.) Android provides an implementation of this algorithm inside SecretKeyFactory as PBKDF2WithHmacSHA1:

package com.coderzheaven.encryptfile;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;

public class ActivityEncrypt extends Activity {

	private String encryptedFileName = "Enc_File2.txt";
	private static String algorithm = "AES";
	static SecretKey yourKey = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		saveFile("Hello From CoderzHeaven testing ");
		decodeFile();

	}

	public static SecretKey generateKey(char[] passphraseOrPin, byte[] salt)
			throws NoSuchAlgorithmException, InvalidKeySpecException {
		// Number of PBKDF2 hardening rounds to use. Larger values increase
		// computation time. You should select a value that causes computation
		// to take >100ms.
		final int iterations = 1000;

		// Generate a 256-bit key
		final int outputKeyLength = 256;

		SecretKeyFactory secretKeyFactory = SecretKeyFactory
				.getInstance("PBKDF2WithHmacSHA1");
		KeySpec keySpec = new PBEKeySpec(passphraseOrPin, salt, iterations,
				outputKeyLength);
		yourKey = secretKeyFactory.generateSecret(keySpec);
		return yourKey;
	}

	public static SecretKey generateSalt() throws NoSuchAlgorithmException {
		// Generate a 256-bit key
		final int outputKeyLength = 256;

		SecureRandom secureRandom = new SecureRandom();
		// Do *not* seed secureRandom! Automatically seeded from system entropy.
		KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
		keyGenerator.init(outputKeyLength, secureRandom);
		SecretKey key = keyGenerator.generateKey();
		return key;
	}

	public static byte[] encodeFile(SecretKey yourKey, byte[] fileData)
			throws Exception {
		byte[] data = yourKey.getEncoded();
		SecretKeySpec skeySpec = new SecretKeySpec(data, 0, data.length,
				algorithm);
		Cipher cipher = Cipher.getInstance(algorithm);
		cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

		byte[] encrypted = cipher.doFinal(fileData);

		return encrypted;
	}

	public static byte[] decodeFile(SecretKey yourKey, byte[] fileData)
			throws Exception {
		byte[] data = yourKey.getEncoded();
		SecretKeySpec skeySpec = new SecretKeySpec(data, 0, data.length,
				algorithm);
		Cipher cipher = Cipher.getInstance(algorithm);
		cipher.init(Cipher.DECRYPT_MODE, skeySpec);

		byte[] decrypted = cipher.doFinal(fileData);

		return decrypted;
	}

	void saveFile(String stringToSave) {
		try {
			File file = new File(Environment.getExternalStorageDirectory()
					+ File.separator, encryptedFileName);
			BufferedOutputStream bos = new BufferedOutputStream(
					new FileOutputStream(file));
			char[] p = { 'p', 'a', 's', 's' };
			SecretKey yourKey = generateKey(p, generateSalt().toString()
					.getBytes());
			byte[] filesBytes = encodeFile(yourKey, stringToSave.getBytes());
			bos.write(filesBytes);
			bos.flush();
			bos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	void decodeFile() {
		try {
			byte[] decodedData = decodeFile(yourKey, readFile());
			String str = new String(decodedData);
			System.out.println("DECODED FILE CONTENTS : " + str);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public byte[] readFile() {
		byte[] contents = null;

		File file = new File(Environment.getExternalStorageDirectory()
				+ File.separator, encryptedFileName);
		int size = (int) file.length();
		contents = new byte[size];
		try {
			BufferedInputStream buf = new BufferedInputStream(
					new FileInputStream(file));
			try {
				buf.read(contents);
				buf.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return contents;
	}

}

Useful information collected from this link.
http://android-developers.blogspot.in/2013/02/using-cryptography-to-store-credentials.html

Highest Rated CEOs 2013

Mark Zuckerberg Facebook

Do you approve of the way your CEO is leading the company? See which CEOs have the highest approval ratings. The Glassdoor list is based entirely on employee feedback shared during the past year.

Check out the Top CEOs of 2013 and caste your vote here..

http://www.glassdoor.com/50-Highest-Rated-CEOs.htm

How to create transparency in your activity or dialog in android – different methods?

There are different ways for making an acitivity transparent.

First method

1. Through XML in AndroidManifest

like this.

<activity
            android:name="com.coderzheaven.interfacedemo.MainActivity"
            android:label="@string/app_name" 
           <strong> android:theme="@android:style/Theme.Translucent"</strong>
            >
          
        </activity>

Here we are using Android’s built in theme.

Method 2

Through styles

create a style like this in your styles.xml

 <style name="Theme.Transparent" parent="android:Theme">
        <item name="android:windowIsTranslucent">true</item>
        <item name="android:windowBackground">@android:color/transparent</item>
        <item name="android:windowContentOverlay">@null</item>
        <item name="android:windowNoTitle">true</item>
        <item name="android:windowIsFloating">true</item>
        <item name="android:backgroundDimEnabled">false</item>
    </style>

and applying like this in the AndroidManifest.xml

 <activity
            android:name="com.coderzheaven.interfacedemo.MainActivity"
            android:label="@string/app_name" 
            <strong>android:theme="@style/Theme.Transparent"</strong>
            >
        </activity>

Check out this post for the complete implementation.
http://www.coderzheaven.com/2011/07/20/how-to-create-a-transparent-activity-in-android/

Now we see how to make a Dialog transparent.

I am using this post for explaining this

http://www.coderzheaven.com/2013/02/13/extend-dialog-class-write-its-button-click-activity-interfaces-android/

package com.coderzheaven.interfacedemo;

import android.app.Activity;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import com.coderzheaven.interfacedemo.MyDialog.myOnClickListener;

public class MainActivity extends Activity {

	public myOnClickListener myListener;

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

		// create new onclicklistener interface //
		myListener = new myOnClickListener() {
			@Override
			public void onButtonClick() {
				Toast.makeText(getApplicationContext(),
						"This is a Transparent Custom Dialog Demo",
						Toast.LENGTH_LONG).show();
			}
		};

		MyDialog mydialog = new MyDialog(this, myListener);
		mydialog.show();
		addTransparency(mydialog);
		
	}

	void addTransparency(MyDialog mydialog) {
		mydialog.getWindow().setBackgroundDrawable(
				new ColorDrawable(android.graphics.Color.TRANSPARENT));
	}

}

This code does the work here for transparency in the Dialog.

void addTransparency(MyDialog mydialog) {
		mydialog.getWindow().setBackgroundDrawable(
				new ColorDrawable(android.graphics.Color.TRANSPARENT));
	}

How to Customize “Force Close” Dialog in Android?

An interesting post..

Everytime you write an app, it may or may not crash and we often see the “Force Close” Dialog.
But what if we can customize the “Force Close” Dialog itself.

Force Close in Android

This is done using “UncaughtExceptionHandler” class.

This post explains this.
here I am knowingly crashing the application like this

int y = 5/0;

Now this is my MainActivity that is going to crash.

package com.coderzheaven.forceclosecustomize;

import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {

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

		Thread.setDefaultUncaughtExceptionHandler(new UnCaughtException(MainActivity.this));
		
		int y = 5/0;
	}

}

And this is the Class that captures the Force Close Dialog and shows our CustomDialog.
UnCaughtException.java

package com.coderzheaven.forceclosecustomize;

import java.io.File;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.Date;
import java.util.Locale;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.os.Looper;
import android.os.StatFs;
import android.util.Log;

public class UnCaughtException implements UncaughtExceptionHandler {

	
	private Context context;
	private static Context context1;

	public UnCaughtException(Context ctx) {
		context = ctx;
		context1 = ctx;
	}

	private StatFs getStatFs() {
		File path = Environment.getDataDirectory();
		return new StatFs(path.getPath());
	}

	private long getAvailableInternalMemorySize(StatFs stat) {
		long blockSize = stat.getBlockSize();
		long availableBlocks = stat.getAvailableBlocks();
		return availableBlocks * blockSize;
	}

	private long getTotalInternalMemorySize(StatFs stat) {
		long blockSize = stat.getBlockSize();
		long totalBlocks = stat.getBlockCount();
		return totalBlocks * blockSize;
	}

	private void addInformation(StringBuilder message) {
		message.append("Locale: ").append(Locale.getDefault()).append('\n');
		try {
			PackageManager pm = context.getPackageManager();
			PackageInfo pi;
			pi = pm.getPackageInfo(context.getPackageName(), 0);
			message.append("Version: ").append(pi.versionName).append('\n');
			message.append("Package: ").append(pi.packageName).append('\n');
		} catch (Exception e) {
			Log.e("CustomExceptionHandler", "Error", e);
			message.append("Could not get Version information for ").append(
					context.getPackageName());
		}
		message.append("Phone Model: ").append(android.os.Build.MODEL)
				.append('\n');
		message.append("Android Version: ")
				.append(android.os.Build.VERSION.RELEASE).append('\n');
		message.append("Board: ").append(android.os.Build.BOARD).append('\n');
		message.append("Brand: ").append(android.os.Build.BRAND).append('\n');
		message.append("Device: ").append(android.os.Build.DEVICE).append('\n');
		message.append("Host: ").append(android.os.Build.HOST).append('\n');
		message.append("ID: ").append(android.os.Build.ID).append('\n');
		message.append("Model: ").append(android.os.Build.MODEL).append('\n');
		message.append("Product: ").append(android.os.Build.PRODUCT)
				.append('\n');
		message.append("Type: ").append(android.os.Build.TYPE).append('\n');
		StatFs stat = getStatFs();
		message.append("Total Internal memory: ")
				.append(getTotalInternalMemorySize(stat)).append('\n');
		message.append("Available Internal memory: ")
				.append(getAvailableInternalMemorySize(stat)).append('\n');
	}

	public void uncaughtException(Thread t, Throwable e) {
		try {
			StringBuilder report = new StringBuilder();
			Date curDate = new Date();
			report.append("Error Report collected on : ")
					.append(curDate.toString()).append('\n').append('\n');
			report.append("Informations :").append('\n');
			addInformation(report);
			report.append('\n').append('\n');
			report.append("Stack:\n");
			final Writer result = new StringWriter();
			final PrintWriter printWriter = new PrintWriter(result);
			e.printStackTrace(printWriter);
			report.append(result.toString());
			printWriter.close();
			report.append('\n');
			report.append("**** End of current Report ***");
			Log.e(UnCaughtException.class.getName(),
					"Error while sendErrorMail" + report);
			sendErrorMail(report);
		} catch (Throwable ignore) {
			Log.e(UnCaughtException.class.getName(),
					"Error while sending error e-mail", ignore);
		}
	}

	/**
	 * This method for call alert dialog when application crashed!
	 */
	public void sendErrorMail(final StringBuilder errorContent) {
		final AlertDialog.Builder builder = new AlertDialog.Builder(context);
		new Thread() {
			@Override
			public void run() {
				Looper.prepare();
				builder.setTitle("Sorry...!");
				builder.create();
				builder.setNegativeButton("Cancel",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								System.exit(0);
							}
						});
				builder.setPositiveButton("Report",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								Intent sendIntent = new Intent(
										Intent.ACTION_SEND);
								String subject = "Your App crashed! Fix it!";
								StringBuilder body = new StringBuilder("Yoddle");
								body.append('\n').append('\n');
								body.append(errorContent).append('\n')
										.append('\n');
								// sendIntent.setType("text/plain");
								sendIntent.setType("message/rfc822");
								sendIntent.putExtra(Intent.EXTRA_EMAIL,
										new String[] { "coderzheaven@gmail.com" });
								sendIntent.putExtra(Intent.EXTRA_TEXT,
										body.toString());
								sendIntent.putExtra(Intent.EXTRA_SUBJECT,
										subject);
								sendIntent.setType("message/rfc822");
								context1.startActivity(sendIntent);
								System.exit(0);
							}
						});
				builder.setMessage("Oops,Your application has crashed");
				builder.show();
				Looper.loop();
			}
		}.start();
	}
}

How to create Gradient Buttons Dynamically without XML in Android?

Hello all..

I have shown you how to create gradient buttons in Android using XML in this post.

Now I will show you how to create these gradient buttons dynamically.

We will start with a class that extends StateListDrawable similar to state-list we use in XML

UIGradientSelector.java

package com.example.dynamicgradient;

import android.graphics.drawable.StateListDrawable;

/**
 * {@link StateListDrawable} that controls selection of
 * {@link UIGradientDrawable} based on the three basic button states.
 */
public class UIGradientSelector extends StateListDrawable {

	/**
	 * {@link UIGradientSelector} that selects the {@link UIGradientDrawable}
	 * defined by the colors for the three basic button states.
	 * 
	 * @param normalColors
	 *            Array of primitive ints that define the gradient colors for a
	 *            button in its normal state.
	 * @param focusedColors
	 *            Array of primitive ints that define the gradient colors for a
	 *            button in its focused state.
	 * @param pressedColors
	 *            Array of primitive ints that define the gradient colors for a
	 *            button in its pressed state. If the array is null, then
	 *            focusedColors will be used for the pressed state.
	 */
	public UIGradientSelector(int[] normalColors, int[] focusedColors,
			int[] pressedColors) {
		int stateFocused = android.R.attr.state_focused;
		int statePressed = android.R.attr.state_pressed;
		UIGradientDrawable normalGradient = new UIGradientDrawable(normalColors);
		UIGradientDrawable focusedGradient = new UIGradientDrawable(
				focusedColors);
		UIGradientDrawable pressedGradient;

		if (pressedColors == null) {
			pressedGradient = focusedGradient;
		} else {
			pressedGradient = new UIGradientDrawable(pressedColors);
		}

		addState(new int[] { stateFocused }, focusedGradient);
		addState(new int[] { statePressed }, pressedGradient);
		addState(new int[] { -statePressed, -stateFocused }, normalGradient);
	}
}

Now the class that extends PaintDrawable Class.

UIGradientDrawable.java

package com.example.dynamicgradient;

import android.graphics.drawable.PaintDrawable;
import android.graphics.drawable.shapes.RectShape;

/**
 * {@link PaintDrawable} that paints the surface via a {@link UIGradientShader}.
 */
public class UIGradientDrawable extends PaintDrawable {

    /**
     * {@link UIGradientDrawable} with an initial shape of a rounded rectangle
     * that transitions evenly between the specified colors.
     * 
     * @param colors
     *            Array of primitive ints that contain the argb values of the
     *            color to use for transitioning.
     */
    public UIGradientDrawable(int[] colors) {
        UIGradientShader gradientShader = new UIGradientShader(colors);
        setShape(new RectShape());
        setCornerRadius(8);
        setShaderFactory(gradientShader);
        setDither(true);
    }
}

Now the last java class that extends ShaderFactory.
UIGradientShader.java

package com.example.dynamicgradient;

import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Shader;
import android.graphics.drawable.ShapeDrawable.ShaderFactory;

/**
 * {@link ShaderFactory} that uses a {@link LinearGradient} to transition
 * between specified colors. Any number of colors may be specified.
 */
public class UIGradientShader extends ShaderFactory {
	private int[] colors;
	private float[] positions;

	/**
	 * {@link UIGradientShader} that spaces color transitions evenly across the
	 * painting surface.
	 * 
	 * @param colors
	 *            Array of primitive ints that contain the argb values of the
	 *            color to use for transitioning. If the array contains only one
	 *            color, then an argb of (0, 0, 0, 0) will be used for the end
	 *            color of the transition. If the array is set to null or
	 *            contains zero colors, then the transition will be from an argb
	 *            of (255, 255, 255, 255) to and argb of (0, 0, 0, 0).
	 * 
	 * @see Color
	 */
	public UIGradientShader(int[] colors) {
		init(colors, null);
	}

	/**
	 * {@link UIGradientShader} that spaces color transitions across the
	 * painting surface as specified.
	 * 
	 * @param colors
	 *            Array of primitive ints that contain the argb values of the
	 *            color to use for transitioning. If the array contains only one
	 *            color, then an argb of (0, 0, 0, 0) will be used for the end
	 *            color of the transition. If the array is set to null or
	 *            contains zero colors, then the transition will be from an argb
	 *            of (255, 255, 255, 255) to and argb of (0, 0, 0, 0).
	 * @param positions
	 *            Array of primitive floats that contain the position of the
	 *            transition points. If the array is null, then the color
	 *            transitions will be spaced evenly.
	 */
	public UIGradientShader(int[] colors, float[] positions) {
		init(colors, positions);
	}

	private void init(int[] colors, float[] positions) {
		if (colors == null || colors.length == 0) {
			this.colors = new int[2];
			this.colors[0] = Color.argb(255, 255, 255, 255);
			this.colors[1] = Color.argb(0, 0, 0, 0);
		} else if (colors.length == 1) {
			this.colors = new int[2];
			this.colors[0] = colors[0];
			this.colors[1] = Color.argb(0, 0, 0, 0);
		} else {
			this.colors = colors;
		}

		this.positions = positions;
	}

	public Shader resize(int width, int height) {
		LinearGradient lg = new LinearGradient(0, 0, 0, height, colors,
				positions, Shader.TileMode.REPEAT);
		return lg;
	}

}

Atlast the MainActivity Class that applies these java classes.

package com.example.dynamicgradient;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.Button;
import android.widget.LinearLayout;

public class MainActivity extends Activity {

	protected LinearLayout mainLayout;
	public static Button btn1 = null;
	public static Button btn2 = null;

	// Members
	private int[] normalColors = new int[4];
	private int[] focusedColors = new int[2];
	private int[] disabledColors = new int[1];
	private int defaultSkinR = 255;
	private int defaultSkinG = 100;
	private int defaultSkinB = 150;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		  mainLayout = (LinearLayout) getLayoutInflater().inflate(R.layout.activity_main,
	                null);

	        normalColors[0] = Color.argb(255, defaultSkinR, defaultSkinG,
	                defaultSkinB);
	        normalColors[1] = Color.argb(255, 217, 217, 217);
	        normalColors[2] = Color.argb(191, defaultSkinR, defaultSkinG,
	                defaultSkinB);
	        normalColors[3] = Color.argb(140, defaultSkinR, defaultSkinG,
	                defaultSkinB);

	        focusedColors[0] = Color.argb(100, 242, 242, 242);
	        focusedColors[1] = Color.BLUE;

	        UIGradientSelector gradientSelector1 = new UIGradientSelector(
	                normalColors, focusedColors, null);
	        UIGradientSelector gradientSelector2 = new UIGradientSelector(
	                normalColors, focusedColors, null);

	        disabledColors[0] = Color.argb(153, 216, 216, 216);
	        UIGradientDrawable disabledGradient = new UIGradientDrawable(
	                disabledColors);

	        btn1 = (Button) mainLayout.findViewById(R.id.btn1);
	        btn1.setBackgroundDrawable(gradientSelector1);

	        btn2 = (Button) mainLayout.findViewById(R.id.btn3);
	        btn2.setBackgroundDrawable(disabledGradient);

	        setContentView(mainLayout);
	}

}

Now the Layout XML that contains two buttons.

<?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="wrap_content"
    android:orientation="vertical" 
    android:background="@android:color/black">

    <Button
        android:id="@+id/btn1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:textColor="@android:color/white"
        android:text="Dynamic Gradient Button" />

    <Button
        android:id="@+id/btn3"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:textColor="@android:color/white"
        android:text="Dynamic Gradient Disbled Button" />

</LinearLayout>

How to Download a PDF File and open it in Android using an installed PDF Reader?

Actually this is fairly simple.

Open PDF

Open PDF

Open PDF

This simple code does this.

Uri path = Uri.fromFile(downloadFile(download_file_url));
				try {
					Intent intent = new Intent(Intent.ACTION_VIEW);
					intent.setDataAndType(path, "application/pdf");
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(intent);
					finish();
				} catch (ActivityNotFoundException e) {
					setError("PDF Reader application is not installed in your device");
				}

Here is the complete program that shows how to download a PDF File and open it in Android using an installed PDF Reader.

package com.example.openpdf;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.Gravity;
import android.widget.TextView;

public class MainActivity extends Activity {

	TextView tv_loading;
	String dest_file_path = "test.pdf";
	int downloadedSize = 0, totalsize;
	String download_file_url = "http://ilabs.uw.edu/sites/default/files/sample_0.pdf";
	float per = 0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		tv_loading = new TextView(this);
		setContentView(tv_loading);
		tv_loading.setGravity(Gravity.CENTER);
		tv_loading.setTypeface(null, Typeface.BOLD);
		downloadAndOpenPDF();
	}

	void downloadAndOpenPDF() {
		new Thread(new Runnable() {
			public void run() {
				Uri path = Uri.fromFile(downloadFile(download_file_url));
				try {
					Intent intent = new Intent(Intent.ACTION_VIEW);
					intent.setDataAndType(path, "application/pdf");
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(intent);
					finish();
				} catch (ActivityNotFoundException e) {
					tv_loading
							.setError("PDF Reader application is not installed in your device");
				}
			}
		}).start();
  
	}

	File downloadFile(String dwnload_file_path) {
		File file = null;
		try {

			URL url = new URL(dwnload_file_path);
			HttpURLConnection urlConnection = (HttpURLConnection) url
					.openConnection();

			urlConnection.setRequestMethod("GET");
			urlConnection.setDoOutput(true);

			// connect
			urlConnection.connect();

			// set the path where we want to save the file
			File SDCardRoot = Environment.getExternalStorageDirectory();
			// create a new file, to save the downloaded file
			file = new File(SDCardRoot, dest_file_path);

			FileOutputStream fileOutput = new FileOutputStream(file);

			// Stream used for reading the data from the internet
			InputStream inputStream = urlConnection.getInputStream();

			// this is the total size of the file which we are
			// downloading
			totalsize = urlConnection.getContentLength();
			setText("Starting PDF download...");

			// create a buffer...
			byte[] buffer = new byte[1024 * 1024];  
			int bufferLength = 0;

			while ((bufferLength = inputStream.read(buffer)) > 0) {
				fileOutput.write(buffer, 0, bufferLength);
				downloadedSize += bufferLength;
				per = ((float) downloadedSize / totalsize) * 100;
				setText("Total PDF File size  : "
						+ (totalsize / 1024)
						+ " KB\n\nDownloading PDF " + (int) per
						+ "% complete");
			}
			// close the output stream when complete //
			fileOutput.close();
			setText("Download Complete. Open PDF Application installed in the device.");

		} catch (final MalformedURLException e) {
			setTextError("Some error occured. Press back and try again.",
					Color.RED);
		} catch (final IOException e) {
			setTextError("Some error occured. Press back and try again.",
					Color.RED);
		} catch (final Exception e) {
			setTextError(
					"Failed to download image. Please check your internet connection.",
					Color.RED);
		}
		return file;
	}

	void setTextError(final String message, final int color) {
		runOnUiThread(new Runnable() {
			public void run() {
				tv_loading.setTextColor(color);
				tv_loading.setText(message);
			}
		});

	}

	void setText(final String txt) {
		runOnUiThread(new Runnable() {
			public void run() {
				tv_loading.setText(txt);
			}
		});

	}

}

Samsung Galaxy s4 Rumours – Bigger, Better, Eye-Based Scrolling

Samsung Galaxy S4

We know Samsung is set to reveal its Galaxy S4 smartphone on March 14th, and that the company has been desperately trying to spin up the same sort of pre-release hype about the device that Apple usually benefits from–including a rather strange promotion campaign involving a young “secret messenger” called Jeremy. Now a source that has been accurate with Samsung rumors in the past has leaked some specs of the device.

Read the complete story here…

http://www.fastcompany.com/3006602/tech-forecast/galaxy-s-iv-rumors-bigger-better-eye-based-scrolling

Different ways to KEEP SCREEN ON in Android.

These are the different ways in which you can keep your screen on in your app

1. Declare the screen stays on in your XML layout
2. Inform the window manager in onCreate you want the screen to stay on
3. WakeLock – used for critical downloads or things that you definitely don’t want the Android system shutting down for

First Method

import android.app.Activity;
import android.os.Bundle;
import android.view.WindowManager;

public class ScreenOnFlagActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_flag);
 
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }
}

Next Method

import android.app.Activity;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;

public class ScreenOnWakeLockActivity extends Activity {
    private static final String TAG = "com.blundell.tut.ui.phone.ScreenOnWakeLockActivity.WAKE_LOCK_TAG";
    private WakeLock wakeLock;
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wake_lock);
 
        PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        wakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, TAG);
    }
 
    @Override
    protected void onResume() {
        super.onResume();
        wakeLock.acquire();
    }
 
    @Override
    protected void onPause() {
        super.onPause();
        wakeLock.release();
    }
}

The third method

Add this to your root layout

‘android:keepScreenOn=”true”‘

But for all these to work.
You have to add this permission in the AndroidManifest.xml

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

Note : Don’t use this screen on feature unless you really need it, because it kills your battery.

Budget iPhone 5 Coming Soon

iPhone 5

The budget version of Apple’s latest iPhone will cost roughly $330 (£220), priced in order to appeal to young, middle class consumers in countries like China and India.
The claims about the price and the imminent release were made on the Japanese website Macotakara, following on from earlier reports about Apple plans for a cheaper phone.
In January it was reported that the planned new phone will resemble the iPhone 5 from the front but Apple will replace that handset’s aluminium body with a cheaper plastic casing.

Read More from here
http://www.telegraph.co.uk/technology/apple/9902864/Budget-iPhone-5-to-launch-soon.html

Galaxy S3 rival LG Optimus G @ Rs 30,990

LG launching Galaxy S3 rival Optimus G @ Rs 30,990

LG is all set to launch its erstwhile flagship smartphone Optimus G in India at an event in Mumbai on February 27. This device is pitted against the current market leader Samsung Galaxy S III and is the basis for the highly popular Google Nexus 4. India will be among the first countries outside the US, Canada, Japan and South Korea, as the device is yet to hit Europe as well as other major markets. The phone is available on online retail sites in the country at Rs 30,990 even before its launch.

Read More from
here

What are webservices? How we can use in Android?

A webservice can be

A web service is any piece of software that makes itself available over the internet and uses a standardized XML messaging system. XML is used to encode all communications to a web service. For example, a client invokes a web service by sending an XML message, then waits for a corresponding XML response. Because all communication is in XML, web services are not tied to any one operating system or programming language–Java can talk with Perl; Windows applications can talk with Unix applications.

Web Services are self-contained, modular, distributed, dynamic applications that can be described, published, located, or invoked over the network to create products, processes, and supply chains. These applications can be local, distributed, or Web-based. Web services are built on top of open standards such as TCP/IP, HTTP, Java, HTML, and XML.

Web services are XML-based information exchange systems that use the Internet for direct application-to-application interaction. These systems can include programs, objects, messages, or documents.

A web service is a collection of open protocols and standards used for exchanging data between applications or systems. Software applications written in various programming languages and running on various platforms can use web services to exchange data over computer networks like the Internet in a manner similar to inter-process communication on a single computer. This interoperability (e.g., between Java and Python, or Windows and Linux applications) is due to the use of open standards.

To summarize, a complete web service is, therefore, any service that:

1. Is available over the Internet or private (intranet) networks

2. Uses a standardized XML messaging system

3. Is not tied to any one operating system or programming language

4. Is self-describing via a common XML grammar

Is discoverable via a simple find mechanism

An Example

Consider a simple account-management and order -processing system. The accounting personnel use a client application built with Visual Basic or JSP to create new accounts and enter new customer orders.

The processing logic for this system is written in Java and resides on a Solaris machine, which also interacts with a database to store the information.
The steps illustrated above are as follows:

The client program bundles the account registration information into a SOAP message.
This SOAP message is sent to the Web Service as the body of an HTTP POST request.
The Web Service unpacks the SOAP request and converts it into a command that the application can understand. The application processes the information as required and responds with a new unique account number for that customer.
Next, the Web Service packages up the response into another SOAP message, which it sends back to the client program in response to its HTTP request.
The client program unpacks the SOAP message to obtain the results of the account registration process. For further details regarding the implementation of Web Services technology, read about the Cape Clear product set and review the product components.

In Android we can use it like an HTTP call. Several examples can be found on coderzheaven.com
Some of them are “connecting with php and android” where the php script can be called as a webservice which can be used by any system independent of the operating systems.

Some example links

http://www.coderzheaven.com/2012/09/25/table-values-mysql-database-show-android-tables/

How to create Simple Login form using php in android? – Connect php with android.

Samsung Galaxy Note 8.0

Samsung Galaxy Note 8.0

It would appear that Samsung will indeed be showing off their fabled Galaxy Note 8.0 tablet this coming week at Mobile World Congress 2013. We’ve been sent a sort of spy-shot of the Samsung Galaxy Note 8.0 being blasted on a large screen inside the new MWC convention location – the show still being set up in a very large way. True to what we’ve seen in several leaked bits and pieces over the past couple of weeks, this device is everything you might expect it to be – with an 8-inch screen!

Read complete story here

http://www.slashgear.com/samsung-galaxy-note-8-0-leaked-at-mwc-23270810/

iPhone Mini launch this summer

iPhone Mini

A low-priced iPhone makes a lot of sense, Morgan Stanley says, and it even could hit the market this summer.
Katy Huberty, an analyst with the banking firm, noted that after her meetings with Apple Chief Financial Officer Peter Oppenheimer, she’s convinced that innovation remains a top priority for the Cupertino, Calif., electronics giant. She also believes that Apple will increase cash return to shareholders and expand carriers, distribution, and possibly price points to drive iPhone growth.
She noted that a lower priced iPhone makes sense for several reasons:
“iPad Mini is expanding Apple’s customer base with 50 [percent] of purchases in China/Brazil representing new customers to the ecosystem.”
“Chinese consumers show a desire to purchase the latest version of iPhone (instead of discounted older generations).”
“iPhone 4 demand surprised to the upside in the December quarter.”

Read more from here

http://news.cnet.com/8301-13579_3-57570715-37/iphone-mini-launch-this-summer-makes-sense-analyst-says/

HTC One takes on iPhone5 and Samsung Galaxy S3

HTC One

since its arrival on the scene, HTC has been performing absolutely well and its latest launched, the HTC One or simply called the One, is pitted against Samsung’s Galaxy S3 and Apple’s iPhone 5 by the company and the market pundits.

But will the HTC One be a competition for the top two, namely, Samsung and Apple in the smartphone world?

That is for the company and the consumer to answer. Nevertheless, here’s looking at some of the important features of HTC One that could set it up against Samsung Galaxy S3 and Apple iPhone 5.

Read More from here