Test Script

Tuesday, September 3, 2013

Hi guys,  I am writing this article to announce that I have now joined Android Dissected as a writer, and it gives me immense pleasure to announce that you can now read my tutorials on their site as well.

What does this move mean for my blog ?

I will continue writing Android Tutorials on this blog as well, but since I have joined the awesome guys at Android Dissected you just have an extra place to follow me and read my articles.

Thats all for now, stay tuned for a Google Analytics Tutorial coming shortly :P 

Friday, July 26, 2013

Custom URL Scheme in Android

Hi guys, I am back with yet another simple but interesting Tutorial for you. Today we will be seeing on how to use a Custom URL scheme in Android.

Why do you even need it, you ask?

Well imagine the possibility if you open your app through a simple link on the Internet. I will be considering two case scenarios here to give you a better idea of the concept.

Scenario 1:

So lets say, for some reason you want to be able to open your app whenever the user clicks on Facebook link.


Here is how to do it :

Inside your activity declaration in the Manifest file, add a Intent Filter with the data tag as below :


    
    


So now every time the user clicks on a FB Link your app will be shown as a option to open the link.

Simple and pretty neat huh?

Scenario 2:

So your not happy with just opening FB links & want to open  your app based on some of your links probably placed on your website to provide a tight coupled feeling to the user.

Lets do that now :

This is pretty much similar to the previous approach but here we define our own custom scheme. So again inside the Activity tag in your Manifest file add the following :


    
    



Now here we see we have defined our own custom scheme, this could be anything you wish to name. So now on your website just add a anchor tag with the link as the Custom Url scheme.

Click to open my app



Thats it, now when the user clicks on that link through his device , your app will be opened automatically.


There is still a small part left to this , that being how to read the parameters sent through the link. I will be leaving that to a part 2 of this tutorial.


So i guess thats it for this tutorial ! Hope you enjoyed reading it.


As always feel free to drop me a comment below.


Thursday, July 11, 2013

Ellipsize Property of Android

Hi guys , today we will be going over a very short tutorial over a simple TextView property of Android.

I am going to be teaching you the Ellipsize property of a TextView in Android.

This property is useful if you have a long text and have a single line to display it.

Ex:

My actual long text :
This is some real large text so that we can see the ellipsize effect visible and make a demo out of the same for other users

After applying Ellipsize property :
This is some real large text so that we can see the ellipsize effect visible and make a demo out of ...

Usage :

In list Views if the text is too long then the text gets cut off in middle but this is a graceful way of making it look nice. It enhances the User Experience.


So lets get started :

We will just use a single Activity & a simple layout file for demonstrating this.

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



package com.example.testellipsize;

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

public class MainActivity extends Activity {

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

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
 }

}


So, this is just a simple plain old Activity nothing at all in the activity. The real magic begins in the XML Layout file


================================================================
activity_main.xml
================================================================



    

    

    

    



================================================================
In the above XML all, we did was :

1) Typed some long text , made all the TextViews to show the text in a single Line using 


"android:singleLine=true"


2) We then set  android:ellipsize property of each textView.


3) We set the Ellipsize property to start,end,middle & marquee which behave as their names suggest.


Thats all for this tutorial , feel free to drop me any comments !


Thanks,


Lets see a screenshot :



As we see the difference is clearly visible, the first TextView shows ... at the start , the second shows at the end similarly 3rd shows in the middle & finally marquee makes the text scroll.



Monday, June 17, 2013

Chat Heads V2

Ok so after a lot of requests, lot of fuss and some busy office time, here is my V2 for Chat Heads !

This just extends the previous blog post & gives a Chat Head on an Incoming SMS. This blog post should be a starting guide if your planning to include chat head like notification for your upcoming android app.

So what are we waiting for ? Let's begin :

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



package com.example.testincoming;

import android.app.Service;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;

public class ChatHeadService extends Service {
String from,msg;
   private WindowManager windowManager;
   private ImageView chatHead;
   WindowManager.LayoutParams params;
   
   @Override public IBinder onBind(Intent intent) {
     // Not used
    from = intent.getStringExtra("From");
    msg = intent.getStringExtra("Msg");
     return null;
   }

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

     windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
  
     chatHead = new ImageView(this);
     chatHead.setImageResource(R.drawable.ic_launcher);

    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);
     
     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();
              Intent i = new Intent(getBaseContext(),MainActivity.class);
              i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    i.setClass(getBaseContext(), MainActivity.class);
                    i.putExtra("Msg", msg);
                    i.putExtra("From", from);
              startActivity(i);
              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;
        }
      });

   }
   
  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
   // TODO Auto-generated method stub
    from = intent.getStringExtra("From");
    msg = intent.getStringExtra("Msg");
    Log.d("In Start", "In start");
   return startId;
   
  }
  
 
   
   @Override
   public void onDestroy() {
     super.onDestroy();
     if (chatHead != null) windowManager.removeView(chatHead);
    
 }


So what did i change in this version :
1) We now start a activity from the service on Touch passing in the SMS Text received from the Broadcast Receiver.
2) The Activity Layout is completely empty except for a Absolute Layout as its parent 
3) I have set the theme of the Application to a Dialog Theme.


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

package com.example.testincoming;

import android.os.Bundle;
import android.app.Activity;
import android.app.ActivityOptions;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {
Button b ;
String from,msg;
ChatHeadService c = new ChatHeadService();
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  Intent incomingIntent = getIntent();
  from = incomingIntent.getStringExtra("From");
  msg = incomingIntent.getStringExtra("Msg");
  Log.d("Activity", "Came in activity");
 
  AlertDialog.Builder builder = new AlertDialog.Builder(this);
     builder.setTitle(from);
     builder.setMessage(msg);
     Log.d("Activity", "Came in dialog");
     builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
 
  @Override
  public void onClick(DialogInterface dialog, int which) {
   // TODO Auto-generated method stub
   Log.d("Activity", "Came in OK ");
   MainActivity.this.finish();
  }
 });
     
     builder.show();
  
     
    
 }
 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
 }

 
 
}



Changes in this version in this Activity:

1) We now create a Dialog and take the text passed in from the Service

2) I set the sender's number/Name as the Dialog Title & the content of the SMS as the body of the Dialog.

3) I have set up a button on the dialog which on Click closes the dialog by finishing the activity.


================================================================
SmsListener.java
================================================================


package com.example.testincoming;



import android.animation.AnimatorSet.Builder;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;

public class SmsListener extends BroadcastReceiver{

   

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub

        if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")){
            Bundle bundle = intent.getExtras();           //---get the SMS message passed in---
            SmsMessage[] msgs = null;
            String msg_from;
            if (bundle != null){
                //---retrieve the SMS message received---
                try{
                 Log.d("test", "came here!");
                    Object[] pdus = (Object[]) bundle.get("pdus");
                    msgs = new SmsMessage[pdus.length];
                    int length = msgs.length;
                    for(int i=0; i<length;i++){
                        msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
                        msg_from = msgs[i].getOriginatingAddress();
                        String msgBody = msgs[i].getMessageBody();
                        Toast.makeText(context, msgBody, 550).show();
                       
                        Intent chatHead = new Intent(context, ChatHeadService.class);
                        chatHead.putExtra("Msg", msgBody);
                        chatHead.putExtra("From", msg_from);
                      
                        context.startService(chatHead);
                        Log.d("msgBody : ", msgBody);
                    }
                }catch(Exception e){
                            Log.d("Exception caught",e.getMessage());
                }
            }
        }
    }
}

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

Let's see what I did in the above class :

1) I create a Broadcast receiver which listens for Incoming SMS

2) I read the sms Text received & pass the sender Number , Msg to ChatHeadService class.

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

So thats all that you need , dont forget to add appropriate permissions in the Manifest.


For any queries , drop me a comment !

Thanks

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