Test Script

Sunday, December 29, 2013

Android Card Layout

I have been using the Card layout in my apps for quite a while now and I absolutely love the look they provide. I recently came across the updated Book My Show app which leverages the Card Layout as well and I liked it. So I decided to write a small tutorial on how to use the Card Layout in your app, I have tried to replicate the BMS app to some extent(Also we won't be using any external libraries to get the Card Layout). Here is what the end result will look like :





Looks great, doesn't it ? So what are we waiting for lets get going. We are going to use 3 classes, 2 xml files and an image to achieve that.


Update : I have improved this tutorial by using nine patch images. I have the code updated on the Github Repo. I have now updated this tutorial to reflect the same. Now I set the background of the list_row.xml to the nine patch image.

 


MainActivity.java

package com.example.testcardlayout;

import java.util.ArrayList;
import java.util.List;
import android.app.ActionBar;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.Menu;
import android.widget.ListView;

public class MainActivity extends Activity {

 private List rowItems;

    private static Integer[] images = {
            R.drawable.red,
            R.drawable.red,
            R.drawable.red,
            R.drawable.red,
            R.drawable.red,
            R.drawable.red,
            R.drawable.red,            
            R.drawable.red
    };

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  // Intialize and set the Action Bar Background to Holo Blue
  ActionBar actionBar = getActionBar();
  actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#33b5e5" )));
  
  ListView lv = (ListView) findViewById(R.id.myList);
  rowItems = new ArrayList();
   
         String[] titles = {"Movie1","Movie2","Movie3","Movie4","Movie5","Movie6","Movie7","Movie8"};
         String[] descriptions = {"First Movie","Second movie","Third Movie","Fourth Movie","Fifth Movie",
           "Sixth Movie","Seventh Movie","Eighth Movie"};
        
                //Populate the List
         for (int i = 0; i < titles.length; i++) {
             RowItem item = new RowItem(images[i], titles[i], descriptions[i]);
             rowItems.add(item);
         }

         // Set the adapter on the ListView
         LazyAdapter adapter = new LazyAdapter(getApplicationContext(), R.layout.list_row, rowItems);
         lv.setAdapter(adapter);
 }

}

Let me explain what we did there :


  1. Defined a set of images, I have all pointing to the same image in the drawable folder. These images are going to be used for the imageview. Typically in a real life scenario these images will be added dynamically from your server.
  2. We then initialized the ActionBar and set the background to HOLO Blue.
  3. We populated the rowItems list with RowItem objects(RowItem is a simple POJO class)
  4. We then create an instance of the LazyAdapter(Our Custom Adapter) and  set it to our listview.
  5. Also note we passed in the resource for each list item as R.layout.list_row. This defines what each list item will contain.

Now lets have a look at out Custom Adapter:

LazyAdapter.java

package com.example.testcardlayout;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

public class LazyAdapter extends ArrayAdapter {

    Context context;

    public LazyAdapter(Context context, int resourceId, List items){
        super(context, resourceId, items);
        this.context = context;
    }

    public class ViewHolder{
        ImageView image;
        TextView title;
        TextView description;
    }


    public View getView(int position, View convertView, ViewGroup parent){
        ViewHolder holder;
        RowItem rowItem = getItem(position);

        LayoutInflater mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (convertView == null){
            convertView = mInflater.inflate(R.layout.list_row, null);
            holder = new ViewHolder();
            holder.image = (ImageView)convertView.findViewById(R.id.list_image);
            holder.title = (TextView)convertView.findViewById(R.id.title);
            holder.description = (TextView)convertView.findViewById(R.id.description);
            convertView.setTag(holder);
        } else
            holder = (ViewHolder)convertView.getTag();

        holder.image.setImageResource(rowItem.getImageId());
        holder.title.setText(rowItem.getTitle());
        holder.description.setText(rowItem.getDesc());

        return convertView;
    }

Here I implement a custom Adapter for our ListView. I have made use of the Holder pattern to make sure the performance of our ListView is maximum. But if none of this makes sense to you at the moment, don't worry I am planning to write a small tutorial on the same soon. For now trust me and agree with me on this.

There is one final java class which is the POJO class:

RowItem.java
package com.example.testcardlayout;

public class RowItem {
    private int imageId;
    private String title;
    private String description;

    public RowItem(int imageId, String title, String desc) {
        this.imageId = imageId;
        this.title = title;
        this.description = desc;
    }
    public int getImageId() {
        return imageId;
    }
    public void setImageId(int imageId) {
        this.imageId = imageId;
    }
    public String getDesc() {
        return description;
    }
    public void setDesc(String desc) {
        this.description = desc;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    @Override
    public String toString() {
        return title + "\n" + description;
    }
}

Now let us have a look at the XML files which define our layouts :

1. activity_main.xml

This layout defines a plain simple ListView within a Linear Layout



    




2. list_row.xml

This layout defines a an ImageView and 2 TextViews to be displayed as an individual list item. Also look at how I set the background of this layout to @drawable/card_greenborder. That gives it the Card look.



       
    
    



    







That's all ! Congratulations, you have successfully built the Card Layout and can now use it in your app. A few things to note here though :

  • I have used a Nine Patch drawable for better performance.
  • This was just a simple demo of how to achieve the Card UI in your app without using any external libraries, you can customize the list_row.xml to suit your needs.
  • A big thanks to Andrew Ruffalo for his help on the card background.
  • Also beginning from this tutorial onwards I will be maintaining a Github repo to post all the source code I develop for tutorials.
Source Code :  Github

Feel free to drop me a comment below if you like my tutorial or if you run into any problem. I would really appreciate it if you could share this post if you liked it.

Tuesday, December 17, 2013

Shared Preferences In Android


So a lot of times you see a few of your favorite apps make the app more customisable and friendlier to you by letting you choose your favorite theme, font and whole bunch of other stuff. Ever wondered how they do it? Wished your apps had such personalisation? Well, look no further today in this tutorial I will be covering something called Shared Preferences in Android which is exactly the magic behind the personalisation of your app for each user.



Shared Preference - It is named so because the preference value  is shared between different components of your app. These are a lightweight mechanism to store key value pairs and use those data later on in the app. You see the bigger picture now don't you? Each of your choice(theme, font etc) are stored as a preference. Thus every time the app starts it reads the stored preferences and customises the entire app for you. Exciting, isn't it ? Enough of my ranting, lets go see how you can setup this awesome thing in your apps.


So to better demonstrate the concept, let me assume that we wish to save the username of the user, so that the next time he opens the app he doesn't need to type the password.

The code snippet below explains how to save a key value pair in a shared preference :


String USERNAME_KEY ="UserName";
String prefName = "userNamePref";

public void savePreferences(){

  SharedPreferences  prefs = getSharedPreferences(prefName, MODE_PRIVATE);
  SharedPreferences.Editor prefEditor = prefs.edit();
  prefEditor.putString(USERNAME_KEY, "user123");
  prefEditor.commit();

 }


Let me quickly explain what we did there :

  1. Created a instance of SharedPreferences called 'prefs', using the getSharedPreferences() method. This method opens the preference named userNamePref if it already exists or creates a new preference if it doesn't exist.
  2. Opened the editor to modify the value stored within the preference.
  3. Inserted the username of the user(i.e. user123 in this case) into the preference.
  4. Lastly, after you have edited the preference you always need to call the commit() on the Editor, else the preference value won't be stored. This is a very common mistake and I forget it quite a few times as well.

So now that you have created a new preference you would like to read it every time the user opens the app so that you can fetch the saved username and display it to the user. So let us see how we read it :

SharedPreferences userPrefs = getSharedPreferences(prefName, MODE_PRIVATE);
String userName = userPrefs.getString(USERNAME_KEY, "");


That's all there is to reading the SharedPreference, the getString() method takes 2 parameters : key and a default value which is returned if the shared preference is not found. In this case if the shared preference is not found then we return an empty string. That's all there is to a simple Shared Preference.

This Shared Preference is available only to components within your app. There are a few extra methods to change the accessibility of the shared preferences but I will be covering that in a follow-up post sometime next week. If you have any queries feel free to drop me a comment below !

Friday, December 13, 2013

Android Invisible App

Have you ever been in a situation where you wished you could have a transparent/invisible activity. May be the next killer spy app or probably a screen monitoring or recording app? Well guess what you are in luck ! In this tutorial I will be showing you how to create a transparent activity in Android. So lets see how we can create our hidden/invisible Activity.



All the magic is going to happen through a simple XML file, the styles.xml in your res folder(if the file already exists then just add the new style at the end) :


    


That's it, now you just need to apply this to the Activity which you want to be transparent in the AndroidManifest.xml




Congratulations, you now have a transparent activity ready for your spying app! So now whenever you start this activity the user won't see any UI as it is completely invisible. You can now perform any actions in the MainActivity.java and the user wont even know that there is something happening.

That's all great but with great power comes great responsibility, so there are two things which you need to make sure as an efficient Android developer :

1. Our transparent activity is still registering touches, so the user is going to be pissed at you if he can't see your activity but his touches don't get registered on the screen. So we would want to make our app to stop listening for touch events so that the user's touches are registered on the visible UI screen.

This is pretty simple as well, all we need to do is add a single line of code in our MainActivity.java

 getWindow().addFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);   // Do not listen for touch events

Basically what that does is, it tells Android to stop registering Touch Events for this activity. Now the user can click the screen as normal without even knowing that your activity is is there spying on him. :P

2. I would not recommend the use of this unless absolutely necessary because since the activity is invisible it will be running and hogging the resources from the device. You can call the finish() method but even after that the app will be in the background consuming resource until the OS kills it. So please make sure you use this only if absolutely necessary and there is no other way of achieving what you want.



That's all from my end, feel free to drop me a comment below if you have any queries !

Saturday, December 7, 2013

How To Send SMS In Android

Hi guys, today in this tutorial we will be looking at how you can send SMS in Android through your next killer app you are designing.



You can use two methods to send out SMS :

1. SmsManager API

2. Built In SMS Application

Using the SmsManager API - using this API you can send SMS directly from within your apps. Here is how

SmsManager smsManager = SmsManager.getDefault();
 smsManager.sendTextMessage("1234567890", null, "SMS Text goes here!", null, null);


That's it, its that simple !
1.  The first parameter is where you send the mobile number to which you wish to send the SMS to.
2.  The 3rd parameter contains the text of the SMS to be sent out.
3.  We create an instance of the SmsManager and using the sendTextMessage method we send out the SMS.
This will send the message using the user's credits, so it is always advised to confirm with the user once before sending out the SMS.

Using the Built-In SMS App - using this method you can redirect the user from your application to the default Messaging app in the device where the user can proceed further as needed.

Here is how we can invoke the default SMS app :

Intent sendIntent = new Intent(Intent.ACTION_VIEW);
 sendIntent.putExtra("sms_body", "The SMS text goes here!"); 
 sendIntent.setType("vnd.android-dir/mms-sms");
 startActivity(sendIntent);

Here is what we did :

1.  Create a new intent with the action as Intent.ACTION_VIEW
2.  Set the body of the SMS using the putExtra method, make sure you put the key as " sms_body".
3.  Set the type to  "vnd.android-dir/mms-sms".
4.  Start the activity.

The user will now be redirected to his default/chosen SMS app. Also for both the above methods to work you need to have the Send SMS permission so add the following permission in the Android Manifest :



That's all there is to send out a SMS through your app. Also if your targeting devices on Android 4.4 and above make sure to check this link :  Android 4.4 SMS Changes

Feel free to drop me any comments/queries. 

Saturday, November 30, 2013

Implemeting A Simple Splash Screen

A splash screen is basically the loading screen of the app. Some people use the splash screen to load the application while others use it to show branding. Today in this article we will be looking at how to create a simple splash screen which will be shown to the user's for a couple of minutes before the app is loaded.


This is the image I have chosen to display as my splash screen for my app. You can select any image you wish as your splash screen. Android doesn't provide any built in mechanism for displaying a splash screen, so we will be using a timer to display the image for a certain time period before we start the app. 


I will be using a simple XML and Java class to demonstrate the same, so let's see how we can create our Splash screen :

SplashScreenActivity.java

public class SplashScreenActivity extends Activity {

 // Show the Splash Screen for 3secs(3000ms)
 long START_UP_DELAY = 3000L;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.splashscreen);
  
  
  // Add delay so that Splash Screen is displayed for 3secs
  new Handler().postDelayed(new Runnable() {
   @Override
   public void run() {

    Intent loginPage = new Intent(SplashScreenActivity.this, LoginActivity.class);
    startActivity(loginPage);
   }
  }, START_UP_DELAY);
 }
 
 // Override the onPause method to kill this Activity, so that pressing the back button doesn't bring up this screen.
 @Override
 protected void onPause() {
  // TODO Auto-generated method stub
  super.onPause();
  this.finish();
 }
}

The corresponding XML file for the UI :

splashscreen.xml


    




That's it, its that simple to display a Splash Screen. The code is self explanatory with the comments but here is a gist of what we did above:

1.  The XML for the UI just contains an ImageView which shows the splash screen image.

2.  We created a new handler and basically made it wait for the required delay and then started the Login Activity(This is the activity you want to open after the splash screen)

3.  The more tricky part here in this tutorial is the code in the onPause(), we call this.finish() in the onPause. This is done so that we kill this activity once the splash screen is shown, because we don't want to be showing the splash screen image again if the user presses the back button.

A better approach instead of calling finish() would be to set the android:noHistory="true"  attribute for SplashScreenActivity in the AndroidManifest. Also make sure you set SplashScreenActivity.java as your Launcher activity so that when the user starts the app the splash screen is shown first.

Well, that's all there is from my end for this tutorial. If you have any queries feel free to drop me a comment below.

Tuesday, September 24, 2013

CES 2014

Hi guys , thanks for you continuos support I am now officially invited to CES 2014 as  press/media. I would like to take this opportunity to thank all you guys because it wouldn't have been possible without your support.

A special thanks to all my close buddies who were the ones who motivate me to go further and were there for me all the time I needed them. Also a huge thanks to all the members at Android Dissected, who were kind enough to give me an opportunity to write for their site and give my thoughts a voice to a global audience.


Thanks a ton !

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 !














Saturday, April 27, 2013

Fetching User's Email ID

Hi guys in this tutorial I am going to be showing you how to fetch the user's email Id which has been tied to the users device. This is a very short & simple tutorial so without wasting further time lets get to work :

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


package com.example.testemail;



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 emailId = getEmailId();
        Toast.makeText(getApplicationContext(), emailId, 500).show();

}

   public String getEmailId(){

      Account[] accounts=AccountManager.get(this).getAccountsByType("com.google");
    
   
    for(Account account: accounts)
    {
        String emailId=account.toString();
        Log.d("List of  email id's of user", emailId);

    }

     String myEmailid=accounts[0].name;

    return myEmailid;
   }

}

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

You also need a permission to access the Accounts 

<uses-permission android:name="android.permission.GET_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 email ID
2) Here we get a Array of Accounts using the AccountManager, notice "getAccountsByType("com.google");" 
that is used to to get all Gmail Accounts configured in the users device

3) "accounts[0].name"  gives me the Email Id of the first Account of the user, which is most likely to be the users actual Gmail Id.

4) Finally added a permission of GET_ACCOUNTS required to access the accounts.

Thats all there is, this is used to fetch user's gmail Id programmatically.


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

Note : Try this on a actual device rather than a emulator because the emulator has no Email Id by default .

If this post helped you, please do drop a comment & i will be happy !

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



UA-42774700-1