Tuesday, 28 January 2014

Circular image and imageview in android

Here is the procedure to create circular image in android:

First method:

Bitmap bitmap = get some bitmap image;
     
       
        if(bitmap!=null)
       
        {
   
   int targetWidth = 65;
   int targetHeight = 65;
   Bitmap targetBitmap = Bitmap.createBitmap(targetWidth, targetHeight,Bitmap.Config.ARGB_8888);
   BitmapShader shader;
   shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);

   Paint paint = new Paint();
   paint.setAntiAlias(true);
   paint.setShader(shader);
   Canvas canvas = new Canvas(targetBitmap);
   Path path = new Path();
   path.addCircle(((float) targetWidth - 1) / 2,
   ((float) targetHeight - 1) / 2,
   (Math.min(((float) targetWidth),((float) targetHeight)) / 2),Path.Direction.CCW);
   paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
   paint.setStyle(Paint.Style.STROKE);
   canvas.clipPath(path);
   Bitmap sourceBitmap = bitmap;
   canvas.drawBitmap(sourceBitmap, new Rect(0, 0, sourceBitmap.getWidth(),sourceBitmap.getHeight()),
   new Rect(0, 0, targetWidth,targetHeight), null);
 
 
    imageView.setImageBitmap(targetBitmap);   //set the circular image to your imageview
        }
        else
        {
            queuePhoto(url, imageView);
            imageView.setImageResource(stub_id);
        }




here is the demo:








Another method:


Create Circular imageview:

public class CircularImageView extends ImageView
{
    private int borderWidth = 4;
    private int viewWidth;
    private int viewHeight;
    private Bitmap image;
    private Paint paint;
    private Paint paintBorder;
    private BitmapShader shader;

    public CircularImageView(Context context)
    {
        super(context);
        setup();
    }

    public CircularImageView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        setup();
    }

    public CircularImageView(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
        setup();
    }

    @SuppressLint("NewApi")
private void setup()
    {
        // init paint
        paint = new Paint();
        paint.setAntiAlias(true);

        paintBorder = new Paint();
        setBorderColor(Color.GREEN);
        paintBorder.setAntiAlias(true);
        this.setLayerType(LAYER_TYPE_SOFTWARE, paintBorder);
        paintBorder.setShadowLayer(4.0f, 0.0f, 2.0f, Color.BLACK);
    }

    public void setBorderWidth(int borderWidth)
    {
        this.borderWidth = borderWidth;
        this.invalidate();
    }

    public void setBorderColor(int borderColor)
    {
        if (paintBorder != null)
            paintBorder.setColor(borderColor);

        this.invalidate();
    }

    private void loadBitmap()
    {
        BitmapDrawable bitmapDrawable = (BitmapDrawable) this.getDrawable();

        if (bitmapDrawable != null)
            image = bitmapDrawable.getBitmap();
    }

    @Override
    public void onDraw(Canvas canvas)
    {
        // load the bitmap
        loadBitmap();

       
        if (image != null)
        {
            shader = new BitmapShader(Bitmap.createScaledBitmap(image, canvas.getWidth(), canvas.getHeight(), false), Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
            paint.setShader(shader);
            int circleCenter = viewWidth / 2;

         
            canvas.drawCircle(circleCenter + borderWidth, circleCenter + borderWidth, circleCenter + borderWidth - 4.0f, paintBorder);
            canvas.drawCircle(circleCenter + borderWidth, circleCenter + borderWidth, circleCenter - 4.0f, paint);
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        int width = measureWidth(widthMeasureSpec);
        int height = measureHeight(heightMeasureSpec, widthMeasureSpec);

        viewWidth = width - (borderWidth * 2);
        viewHeight = height - (borderWidth * 2);

        setMeasuredDimension(width, height);
    }

    private int measureWidth(int measureSpec)
    {
        int result = 0;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);

        if (specMode == MeasureSpec.EXACTLY)
        {
            // We were told how big to be
            result = specSize;
        }
        else
        {
            // Measure the text
            result = viewWidth;
        }

        return result;
    }

    private int measureHeight(int measureSpecHeight, int measureSpecWidth)
    {
        int result = 0;
        int specMode = MeasureSpec.getMode(measureSpecHeight);
        int specSize = MeasureSpec.getSize(measureSpecHeight);

        if (specMode == MeasureSpec.EXACTLY)
        {
            result = specSize;
        }
        else
        {
            result = viewHeight;
        }

        return (result + 2);
    }
}


And call the class in your layout:

<com.newapplication.CircularImageView
    android:id="@+id/row_icon"
    android:layout_width="80dp"
    android:layout_height="80dp"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="22dp"
    android:contentDescription="@string/app_name"
    android:padding="10dp"
    android:scaleType="fitCenter"
    android:src="@drawable/peacock" />

Saturday, 13 April 2013

Make a Phonecall in Android

How to make a phone-call in Android


Here is the code:


private void call() {
   try {
       Intent callIntent = new Intent(Intent.ACTION_CALL);
       callIntent.setData(Uri.parse("tel:123456789"));
       startActivity(callIntent);
   } catch (ActivityNotFoundException activityException) {
       Log.e("phonecall", "Call failed", activityException);
   }
}

Manifest file:


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

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



Here is the code after completing the call activity it will return back to your application:



PhoneCallListener phoneListener = new PhoneCallListener();
TelephonyManager telephonyManager = (TelephonyManager) this .getSystemService(Context.TELEPHONY_SERVICE);



private class PhoneCallListener extends PhoneStateListener {
 
private boolean isPhoneCalling = false;


@Override
public void onCallStateChanged(int state, String incomingNumber) {

if (TelephonyManager.CALL_STATE_RINGING == state) {
//  ringing state

}

if (TelephonyManager.CALL_STATE_OFFHOOK == state) {
//active state
isPhoneCalling = true;
}

if (TelephonyManager.CALL_STATE_IDLE == state) {
//idle state


if (isPhoneCalling) {

Intent intent = getBaseContext().getPackageManager()
.getLaunchIntentForPackage(
getBaseContext().getPackageName());
intent .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent );

isPhoneCalling = false;
}

}
}
}







Saturday, 30 March 2013

QUOTES



Albert Einstein (14 March 1879 – 18 April 1955) was a German-born theoretical physicist  who developed the general theory of relativity one of the two pillars of modern physics (quantum mechanics).While best known for his mass-energy equivalence formula E = mc2 he received the 1921 Nobel prize in physics for his services to theoretical physics, and especially for his discovery of the law of the photoelectric effect.


Quotes:

  • " When you are courting a nice girl an hour seems like a second. When you sit on a red-hot cinder a second seems like an hour. That's relativity."― Albert Einstein
  • “I speak to everyone in the same way, whether he is the garbage man or the president of the university.”  ― Albert Einstein
  • "Peace cannot be kept by force. It can only be achieved by understanding."― Albert Einstein
  • "Education is what remains after one has forgotten everything he learned in school."― Albert Einstein
  • "Sometimes one pays most for the things one gets for nothing."― Albert Einstein
  • "A human being is a part of a whole, called by us universe a part limited in time and space. He experiences himself, his thoughts and feelings as something separated from the rest a kind of optical delusion of his consciousness. This delusion is a kind of prison for us, restricting us to our personal desires and to affection for a few persons nearest to us. Our task must be to free ourselves from this prison by widening our circle of compassion to embrace all living creatures and the whole of nature in its beauty."― Albert Einstein
  • "God does not care about our mathematical difficulties. He integrates empirically."  ― Albert Einstein


Sir Isaac Newton (25 December 1642 – 20 March 1727) was an English physicist and mathematician who is widely regarded as one of the most influential scientists of all time and as a key figure in the scientific revolution. His book Philosophiæ Naturalis Principia Mathematica("Mathematical Principles of Natural Philosophy"), first published in 1687, laid the foundations for most of classical mechanics. Newton also made seminal contributions to optics and shares credit with Gottfried Leibniz for the invention of the infinitesimal calculus.


Quotes:


  • "I see I have made my self a slave to Philosophy."
  • "Truth is ever to be found in simplicity, and not in the multiplicity and confusion of things." 


William Shakespeare (26 April 1564  – 23 April 1616) was an English poet and playwright, was born and brought up in Stratford-upon-Avon , widely regarded as the greatest writer in the English language and the world's pre-eminent dramatist. He is often called England's national poet and the "Bard of Avon". His extant works, including some collaborations, consist of about 38 plays, 154 sonnets, two long narrative poems, two epitaphs on a man named John Combe, one epitaph on Elias James, and several other poems. His plays have been translated into every major living language and are performed more often than those of any other playwright.


Quotes:


  • "What's in a name? That which we call a rose by any other name would smell as sweet".  Romeo and Juliet ( Quote Act II, Sc. II).


Saturday, 23 March 2013

Famous Shayari [Hindi-Bollywood-Movies]

Famous Shayari from Bollywood Movies:


Movie: Anand 1971
Director: Hrishikesh Mukherjee
Starring:  Rajesh Khanna, Amitabh Bachchan


Babumoshai, zindagi aur maut uparwale ke haath hai jahanpanah. Usse na toh aap badal sakte hain na main. Hum sab toh rangmanch ki kathputhliyan hain jinki dor uparwale ki ungliyon main bandhi hain. Kab, kaun, kaise uthega yeh koi nahi bata sakta hai. Ha, ha, ha.

Zindagi Badi Honi Chahiye, Lambi Nahi Babu Moshai.

Maine tumse kitni baar kaha hai Pushpa, mujhse yeh aansoo nahi dekhe jaate. I hate tears.



Movie: Namak Haram 1973
Director: Hrishikesh Mukherjee
Starring:  Rajesh Khanna, Amitabh Bachchan


Maine tera namak khaya hai isliye teri nazron mein namak haram zaroor hoon lekin jisne yeh namak banaya hai uski nazron mein namak haraam nahi hoon, Vicky.


Movie: Bawarchi 1972
Director: Hrishikesh Mukherjee
Starring:  Rajesh Khanna, Jaya Bhaduri

'It's simple to be happy but difficult to be simple'.

Movie: Roti 1974
Director: Manmohan Desai
Starring:  Rajesh Khanna, Mumtaz



Insaan ko dil de, jism de, dimaage de, lekin yeh kambaqth pet mat de. Jab pet deta hai, toh usse bhook mat de.



Movie: Aradhana 1969
Director: Shakti Samanta
Starring:  Rajesh Khanna, Sharmila Tagore



Ek chhota sa zakhm bahut gehra daag ban sakta hai. Aur ek chhoti si mulaqat jeevan bhar ka saath ban sakti hai.


Movie: Jab Tak Hai Jaan 2012
Director: Yash Chopra
Starring:  Shahrukh Khan, Katrina Kaif, Anushka Sharma



Teri aankhon ki namkeen mastiyaan

Teri hansi ki beparwah gustaakhiyaan

Teri zulfon ki lehraati angdaaiyaan

Nahin bhoolunga main

Jab tak hai jaan, Jab tak hai jaan

Tera haath se haath chhodna

Tera saayon se rukh modna

Tera palat ke phir na dekhna

Nahin maaf karunga main

Jab tak hai jaan, jab tak hai jaan

Baarishon mein bedhadak tere naachne se

Baat baat pe bewajah tere roothne se

Chhoti chhoti teri bachkani badmashiyon se

Mohabbat karunga main

Jab tak hai jaan, jab tak hai jaan

Tere jhoothe kasme vaadon se

Tere jalte sulagte khwabon se

Teri be-raham duaaon se

Nafrat karunga main

Jab tak hai jaan, jab tak hai jaan





Custom Alert message when Back button is Pressed in Android

Prevent the closing of Application on click back button



Here we go for a simple code which will prevent your application from closing on click backbutton [Hardware-Android phone].


Thus the code begins :


@Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();

AlertDialog.Builder alertbox=new AlertDialog.Builder(Firstpage.this);
alertbox.setTitle("Warning");
    alertbox.setIcon(R.drawable.info);
    alertbox.setMessage("Exit Application?");
    alertbox.setPositiveButton("Yes", new
    DialogInterface.OnClickListener() {
    public void onClick(DialogInterface arg0, int arg1) {
    finish();
    }
    });
    alertbox.setNegativeButton("No", new
    DialogInterface.OnClickListener() {
    public void onClick(DialogInterface arg0, int arg1) {
    }
    });
    alertbox.show();
}

Thus it will generate alertbox ,onclick yes it will close the app:








Friday, 1 March 2013

Get Start with Google MapKey in Android

In Order to Obtain Google MapKey in Android application 



Here is the simple tutorial to work with mapview in android.

Step to be followed:


In order to use google maps in your android application. you need to get map key.

Open your command prompt by typing cmd in your run. Start ⇒ Run ⇒ cmd  (In Windows PC)

 If your installed jdk version is 1.6 or below then you can get the MD5 fingerprint using  the code below:


C:\Program Files\Java\jdk1.6.0\bin>keytool.exe -list -alias androiddebugkey -keystore   "C:\Users \janmejoylayek\.android\debug.keystore" -storepass android -keypass android

Else you will get only (SHA1) fingerprint.

 

get key


For 1.7 or above jdk versions you can go for this code.

 

C:\Program Files\Java\jdk1.7.0\bin>keytool -list -alias androiddebugkey -v -keystore "C:\Users\janmejoylayek\.android\debug.keystore" -storepass android -keypass android.


get all fingerprints

By using the above code you can get both fingerprints.

Now to get map key using the following fingerprints go to Google Maps Android v1 API Key Signup and get your map key.

generate api


  If you will enter the correct fingerprint then you will receive the code like below..

get api

After getting the code assign the code in your api key file:

<?xml version="1.0" encoding="utf-8"?>
<com.google.android.maps.MapView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mapView"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:clickable="true"
    android:apiKey="08eG45cVt7Aelu9h9opbPzrcrD5JPlPtCQH8oyA"
/>

How to get start with Android google map api v2 ?


The Maps APIs for Android have been updated in the latest version of the Google Play Services library and have been aroused to Android devices with the Play Store.

Steps to follow:

 To use Google Maps API you need an API Key:

  1. Go to the Google APIs Console
  2. In Services enable ‘Google Maps Android API v2’ and agree to the terms
  3. In the left navigation bar, click API Access.
  4. Click Create New Android Key
  5. In the resulting dialog box, enter the SHA-1 fingerprint, then a semicolon(;), then your application's package name. For example:
  6. 4C:D6:CB:18:A5:73:AC:11:04:2D:77:AB:46:D8:09:E0:1C:99:DF:A0;com.example.androidmapview

Click Ok then you will receive something like this..





After receiving api key come to the programming Part. 


Create a new project.

     File -> New -> Android Application Project 

     Select Window > Android SDK Manager. 
     

             Scroll to the bottom of the package list and select Extras > Google Play services. The   Google Play services SDK is downloaded to your computer and installed in your Android SDK environment at <android-sdk-folder>/extras/google/google_play_services/ 


extras

selection
  
 Add the Google Play Services project into your Eclipse workspace.  

             Click File -> Import..., select Android -> Existing Android Code into WorkspaceBrowse to and select <android-sdk-folder>/extras/google/google_play_services/libproject/google-play-services_lib


library

         To add the dependency to Google Play Services into your project

         Project -> Properties -> Android -> Library, Add -> google-play-services_lib. 


Xml Layout:

<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:map="http://schemas.android.com/apk/res-auto"
  android:id="@+id/map"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
 class="com.google.android.gms.maps.SupportMapFragment"/>
 
Java Code:

package com.example.androidmapview;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;

import com.google.android.gms.maps.SupportMapFragment;

public class MainActivity extends FragmentActivity {

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

        SupportMapFragment fragment = new SupportMapFragment();
        getSupportFragmentManager().beginTransaction()
                .add(android.R.id.content, fragment).commit();
    }
}

                                                   
Manifest File:

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

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

    <permission
        android:name="com.example.androidmapview.permission.MAPS_RECEIVE"
        android:protectionLevel="signature" />

    <uses-permission android:name="com.example.androidmapview.permission.MAPS_RECEIVE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <meta-data
    android:name="com.google.android.maps.v2.API_KEY"
    android:value="AIzaSyCkpPuGvz04vogPV71j4TLu5ZNg_X9WXuw"></meta-data>
    </application>

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />
</manifest>


Issues:

  

  Sometime you will face this error:

 


android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=http://play.google.com/store/apps/details?id=com.google.android.gms flg=0x80000 pkg=com.android.vending }



     if you will run in Android 4.1.2


  Error:


android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=market://details?id=com.google.android.gms flg=0x80000 pkg=com.android.vending }




Actually these error will arise only when you are running your app in emulator,when you will run your app in device ,it will ask you to update Google play after that the map will be visible.












Monday, 4 February 2013

Start with Android Basic in Eclipse

Start with Basic Android Developing using Eclipse

  Steps to follow:

           Download Eclipse for  Mobile Developer

 

 For installing eclipse 


          You should have  Java SE Development Kit





open eclipse

For Installing Android :

Go to help > Install new Software

 


Download the ADT Plugin:

  1. Click Add, in the top-right corner.
  2. In the Add Repository dialog that appears, enter "ADT Plugin" for the Name and the following URL for the Location:
     
    https://dl-ssl.google.com/android/eclipse/
     
  3. Click OK. If you have trouble acquiring the plugin, try using "http" in the Location URL, instead of "https" (https is preferred for security reasons).
  4. In the Available Software dialog, select the checkbox next to Developer Tools and click Next.
  5. In the next window, you'll see a list of the tools to be downloaded. Click Next.
  6. Read and accept the license agreements, then click Finish. If you get a security warning saying that the authenticity or validity of the software can't be established, click OK.
  7. When the installation completes, restart Eclipse.


Install new software

Add repository

 



Licenses




Get the Android SDK:

Download the Sdk from Android-Sdk Location
Choose the directory to install and add the location in eclipse

Sdk Location


Open Window

   

Install sdk tools
Thus click the location and install the require SDK with tools

Add ready to start with Android project Go to File > New > Android Application Project


Android app start