Test Script

Tuesday, May 14, 2013

Fetch Image from Camera or Gallery - Android

Hi guys, in this tutorial I will be showing how to get an Image from the user's Camera or from his gallery.

Let's get started :


================================================================
MainActivity.java
================================================================

package com.example.gallerytestapp;

import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.DragEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {

  Uri selectedImageUri;
  String  selectedPath;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  Button b = (Button) findViewById(R.id.bGallery);
  Button bCam= (Button) findViewById(R.id.bCamera);
  ImageView preview = findViewById(R.id.preview);
  bCam.setOnClickListener(new OnClickListener() {
   
   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
                startActivityForResult(cameraIntent, 100); 
   }
  });
  
  
  b.setOnClickListener(new OnClickListener() {
  
   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
     openGallery(10);
   }
  });
 }
 
 
 
 public void openGallery(int req_code){

        Intent intent = new Intent();

        intent.setType("image/*");

        intent.setAction(Intent.ACTION_GET_CONTENT);

        startActivityForResult(Intent.createChooser(intent,"Select file to upload "), req_code);

   }

public void onActivityResult(int requestCode, int resultCode, Intent data) {



        if (resultCode == RESULT_OK) {
         if(data.getData() != null){
           selectedImageUri = data.getData();
         }else{
          Log.d("selectedPath1 : ","Came here its null !");
          Toast.makeText(getApplicationContext(), "failed to get Image!", 500).show();
         }
         
         if (requestCode == 100 && resultCode == RESULT_OK) {  
                Bitmap photo = (Bitmap) data.getExtras().get("data"); 
                selectedPath = getPath(selectedImageUri);
                preview.setImageURI(selectedImageUri);
                Log.d("selectedPath1 : " ,selectedPath);

            } 
         
            if (requestCode == 10)

            {

               selectedPath = getPath(selectedImageUri);
               preview.setImageURI(selectedImageUri);
               Log.d("selectedPath1 : " ,selectedPath);

            }

        }

    }


 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);

    }
 
}
================================================================


Whoa ! That was a bit long code ! So let me quickly explain what i am doing above :


I have just created a Activity , the layout file has just two buttons & a ImageView. One button is to pick an Image from Gallery , the other button is to use the camera of the device to click a picture.

1) In onClick of the button bCam(which starts the native Camera) i create a intent with the following action "android.provider.MediaStore.ACTION_IMAGE_CAPTURE" This is used to invoke the native Camera of the device.

2) Then i start the activity but call it using " startActivityForResult(cameraIntent, 100); " . This is used when you want a result from the activity you are calling.

3) The startActivityForResult method takes in a intent & a request code.

4) The request code is used to identify the result.

5) The result we receive from the Camera is a image Uri. 

6) To get the result we Override onActivityResult method 

7) This method gets request code, result code & a intent as parameters.

8) We check whether the Result Code is equal to 200 , this means the operation was successful . And also check whether the request code is the same as we had specified.

9) We then take the data returned from the Activity.

10) The imageUri returned is set to the ImageView. This shows the captured image as in the imageView.

================================================================

That was how we fetch a image from the Camera , lets see how to fetch an existing image from the Gallery :

================================================================

1) The other button b is used to open up the gallery 

2) Here we call the method openGallery() passing in a Request Code.

3) In the openGallery() method we create a new intent and set its type to image

4) We set the Action to GET_CONTENT & start the activity.

5) We have to again use the startActivityForResult method here so that we get the result after picking the image from the gallery.

6) Now Gallery is opened,once the user selects a image that image is returned again and set in the imageView.

================================================================

You notice there is one more method i.e. getPath(Uri uri), this method is used to fetch the actual path of the image which the user has selected. This is used when you want to upload the selected image to a server or need the complete file path of the selected Image.

In that method all we are doing is querying the MediaStore to get the actual file-path.


So, thats all from me for this tutorial! As always feel free to drop me a mail or comment below if you have any queries.

Thursday, May 9, 2013

Fetching User's Mobile Number - Android


Hi guys in this tutorial I am going to be showing you how to fetch the user's mobile number programmatically. This is a very short & simple tutorial so without wasting further time lets get to work :

================================================================
MainActivity.java
================================================================

package com.example.testmobiledemo;



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


public class MainActivity extends Activity {
 

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String number = getMobileNumber();
        Toast.makeText(getApplicationContext(), number, 500).show();

}

   public String getMobileNumber(){

  TelephonyManager telephonyManager  =        (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);

String strMobileNumber = telephonyManager.getLine1Number();  

// Note : If the phone is dual sim, get the second number using :

// telephonyManager.getLine2Number();

     return strMobileNumber;
   }

}



================================================================

You also need a permission to access the Accounts


So add the above permission to your Manifest file.

================================================================



So, let me quickly explain what i did above :

1) I created a method which fetches the User's Mobile Number

2) We use Telephony Manager Class to get the number of the device

3) "telephonyManager.getLine1Number();  "  gives me the Mobile Number of the first Sim.

4) Finally added a permission of READ_PHONE_STATE required to access the TELEPHONY Manager.

Thats all there is, this is used to fetch user's Mobile Number programmatically.

Update : This method may not work for all devices, as not all manufacturers support this and the Android Documentation for this is unofficial. So, if you get a null value its just that your manufacturer isn't supporting it


================================================================

As always feel  free to comment or fire any queries to me ! 

Wednesday, May 8, 2013

FaceBook Chat Heads Feature

Hi guys,so I was wondering how facebook implemented the Chat Heads feature recently to their messenger & I found a excellent post which explains how they did it. So this basically going to be a repost of the same, I usually dont do this but this really deserves a mention.

Thanks to Pierre-Yves Ricau that this tutorial was possible, i strongly recommend you to visit his site and drop him a thanks for this.

Link to  Pierre-Yves Ricau's site : Pierre-Yves Ricau's Site


Let's get started :

So basically its just a service running in the background which is responsible for displaying the chat head on your screen. And it is able to display it on top of any activity because of a special permission :


android:name="android.permission.SYSTEM_ALERT_WINDOW"/>


================================================================
ChatHeadService.java
================================================================


public class ChatHeadService extends Service {

  private WindowManager windowManager;
  private ImageView chatHead;

  @Override public IBinder onBind(Intent intent) {
    // Not used
    return null;
  }

  @Override public void onCreate() {
    super.onCreate();

    windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);

    chatHead = new ImageView(this);
    chatHead.setImageResource(R.drawable.android_head);

    WindowManager.LayoutParams params = new WindowManager.LayoutParams(
        WindowManager.LayoutParams.WRAP_CONTENT,
        WindowManager.LayoutParams.WRAP_CONTENT,
        WindowManager.LayoutParams.TYPE_PHONE,
        WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
        PixelFormat.TRANSLUCENT);

    params.gravity = Gravity.TOP | Gravity.LEFT;
    params.x = 0;
    params.y = 100;

    windowManager.addView(chatHead, params);
  }

  @Override
  public void onDestroy() {
    super.onDestroy();
    if (chatHead != null) windowManager.removeView(chatHead);
  }
}


================================================================

Ok so what did we do above :

1)Just add a View on top of the window 

2)Created a new ImageView & set the image 

3)Created a instance of Window Manager & added the ImageView to the Window.

4)You should note " WindowManager.LayoutParams.TYPE_PHONEparameter, this allows it to be on top of the Window.

5)Then we set the position of the ImageView to top left corner 

Now we have the service ready we just need to invoke/start it somehow.

So lets do that by simple creating a Activity as below.

================================================================
Home.java
================================================================



public class Home extends Activity {

Button showChatHead;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.homepage);


showChatHead = (Button)  findViewById(R.id.button);


showChatHead.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
   Intent i = new Intent(getApplicationContext(), ChatHeadService.class);
   startService(i);
}
});



================================================================


Ok so what did we do above :

1) Created a simple Activity which a normal button in it

2) On clicking the button we started the service which we created earlier.

3) Dont forget to register the service in the Manifest & add the permission:

 android:name="android.permission.SYSTEM_ALERT_WINDOW"/>

4) Now on running the application & clicking the button you should see a Android icon pop up on left corner of your Screen.

5) Let's add the functionality of being able to drag this anywhere on the screen.


================================================================


To the same existing ChatHeadService class add the following code
 & you should have the Drag functionality.

================================================================
ChatHeadService.java
================================================================


chatHead.setOnTouchListener(new View.OnTouchListener() {
  private int initialX;
  private int initialY;
  private float initialTouchX;
  private float initialTouchY;

  @Override public boolean onTouch(View v, MotionEvent event) {
    switch (event.getAction()) {
      case MotionEvent.ACTION_DOWN:
        initialX = params.x;
        initialY = params.y;
        initialTouchX = event.getRawX();
        initialTouchY = event.getRawY();
        return true;
      case MotionEvent.ACTION_UP:
        return true;
      case MotionEvent.ACTION_MOVE:
        params.x = initialX + (int) (event.getRawX() - initialTouchX);
        params.y = initialY + (int) (event.getRawY() - initialTouchY);
        windowManager.updateViewLayout(chatHead, params);
        return true;
    }
    return false;
  }
});


================================================================

Now you should have fully functional Chat Head which can be dragged anywhere on the screen !









Well, that was simple wasn't it?

This was just a simple demo tutorial how you can use it using a button, the possibilities are limitless.

Most basic use would be to pop up a notification as a Chat Head for all types of events like SMS,MMS,Calls,Emails etc. Could be used as a Notification Manager or Task Switcher as well.

Happy Hacking !!

Again a big thanks to Pierre-Yves Ricau for sharing this with the general public.

He has the code up on Github as well, so feel free to go there and have a look at it yourself.

Link :

Github Link

That's all for this tutorial from my end, feel free to drop me a comment if you need any help !














UA-42774700-1