Friday, 27 June 2014

Implement Voice input mechanism in android

No comments :
Google Now made us lazy. it can make call for you , can set alarm or reminder for you and much more things that you and i even don't know. And it is without using key board or even without touching your smart phone. as it provide voice input, it is one of the best functionality smart phone provides. Apps and User preference changes day by day and still you provide input using key board i think you have to rethink before next update.  Voice input is supported form android  v 2.3 Ginger bread so you can implement it in your application without using any third party Api. you can implement it using RecognizerIntent.ACTION_RECOGNIZE_SPEECH intent. In this tutorial i am going to show you how you can implement it in your app. just go through full tutorial i am sure you will implement it successfully.

Step -1 : Create New Android application and give name MainActivity to main activity and same name for layout file.
minSdkVersion="11” and targetSdkVersion="17".

you can use below android version also for compilation and build option (As per requirement). now put below code in your project main.xml file. you can set layout as you want but for practice purpose you can go with same.

Main.xml


    

        
            
        

        
        
    


I have given style to the Edit text so it looks nice. below xml file is style applied on it . so now create one resource file and put this code in it.
edittextstyle.xml

    
    
    


Step -2 : Layout is set for your activity. now put below code inside your main class file or where you want voice input. the RecognizerIntent Class allows you to use inbuilt speech recolonization functionality. As i have used this class (intent) it will allow to prompt a dialog box where you can display message what ever you want. 
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak the word");
After user input you can get the result using onActivityResult() method. i get that response and set it into the edit text. now put the below code in class file.
Main.java
package com.androprogrammer.tutorialsamples;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class Main extends Activity {

    EditText word;
    ImageButton bt_voiceinput;
    private static final int REQUEST_CODE = 1234;

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

        // Disable button if no recognition service is present
        PackageManager pm = getPackageManager();
        List activities = pm.queryIntentActivities(
                new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
        if (activities.size() == 0) {
            bt_voiceinput.setEnabled(false);
        }

        bt_voiceinput.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startVoiceRecognitionActivity();
            }
        });
        word.addTextChangedListener(new TextWatcher() {
            public void afterTextChanged(Editable s) {
            }

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            public void onTextChanged(CharSequence s, int start, int before, int count) {
                bt_voiceinput.setEnabled(false);
            }
        });
    }

    private void setRef() {
        // TO set Reference to the xml button object.
        bt_voiceinput = (ImageButton) findViewById(R.id.ib_speak);
        word = (EditText) findViewById(R.id.et_word);
    }

    /**
     * Fire an intent to start the voice recognition activity.
     */
    private void startVoiceRecognitionActivity() {
        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak the word");
        startActivityForResult(intent, REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //If Voice recognition is successful then it returns RESULT_OK
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
            if (resultCode == RESULT_OK) {
                ArrayList textMatchList = data
                        .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);

                if (!textMatchList.isEmpty()) {
                        String Query = textMatchList.get(0);
                        word.setText(searchQuery);
                }
                //Result code for various error.
            } else if (resultCode == RecognizerIntent.RESULT_NETWORK_ERROR) {
                showToastMessage("Network Error");
            } else if (resultCode == RecognizerIntent.RESULT_NO_MATCH) {
                showToastMessage("No Match");
            } else if (resultCode == RecognizerIntent.RESULT_SERVER_ERROR) {
                showToastMessage("Server Error");
            }
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    private void showToastMessage(String msg) {
        Toast.makeText(Main.this, msg, Toast.LENGTH_LONG).show();
    }
}
       Screen Shots




So that's it from coding side now you can run app and test it. i hope you it will run smoothly.
if you have any query comment it in below comment box.
Keep coding...
Read More

Sunday, 11 May 2014

Implement Push Notification in Your App

No comments :
To alert user about some event or to remind about some event happen in your app ,  push notification is a great and easy way. in android for in app notification you can use alert box but if your application is running in background (background mode) and then to notify user you have to use push notification. on Android devices, when a device receives a push notification, your application's icon and a message appear in the status bar. so in this tutorial i am going to show 2 types of notification. one is just small notification consist of Notification Heading , Sort subject , Icon , time etc. 
and in another type you can display big notification like Gmail notification for new mail (same as image).  it consist Big heading , big message and all other things remain same.

This tutorial will show you how to add push notification functionality in your an Android app to send and receive push notifications.

Step -1 : Create New Android application and give name MainActivity to main activity and same name for layout file. 
minSdkVersion="11”  and 
targetSdkVersion="17".
you can use below android version also for compilation and build option (As per requirment). now put below code in your project main.xml file. you can set layout as you want but for practice purpose you can go with same.
Main.xml


 
 
 
 

 
 
 
 
 

 




In the below class file i have take care of which android version it is so it won't get crashed in older Android version. Below android  3.0 the notification consist simple style of notification  not the bigger one. so we have to take care which version user is using. but firstly you are require to get system service for creating notification. so get it using getSystemService() method of context. 
on small notification button click simple style notification is get created and pending intent will add that intent in intent pool. so system will notify user with NotificationManager.notify() method. 
in other case big notification will be created by second button. in which the big message which will be displayed in notification will be store in Notification.InboxStyle object. that object can store big message , big image (like Screen shot image) etc. 

Step -2 : Hope it will be clear to you. So just now put the below code in Main.java file.
Main.java
package com.androprogrammer.tutorialsamples;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;


public class Main extends Activity {

    Button notification_small , notification_big;
    EditText heading , message;
    String heading_text, subject_text;
    Notification n;
    Notification.Builder nb;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        final NotificationManager notificationManager = (NotificationManager)
                getSystemService(NOTIFICATION_SERVICE);
        setRef();

        final Intent intent = new Intent(getApplicationContext(),Main.class);
        final PendingIntent pending = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);

        notification_small.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                if(heading.getText().length() < 0)
                {
                    heading_text = "test";
                }
                else
                {
                    heading_text = heading.getText().toString();
                }

                if (Build.VERSION.SDK_INT < 11)
                {
                    n = new Notification(R.drawable.ic_launcher,
                            heading_text,
                            System.currentTimeMillis());

                    n.setLatestEventInfo(
                            getApplicationContext(),
                            heading_text,
                            message.getText().toString(),
                            pending);
                }
                else
                {
                   n = new Notification.Builder(NotificationDemo.this)
                        .setContentTitle(heading_text)
                        .setContentText(message.getText().toString())
                        .setSmallIcon(R.drawable.ic_launcher)
                        .setContentIntent(pending)
                        .setAutoCancel(true)
                        .addAction(R.drawable.abc_ic_clear, "Close", pending).build();
                }
                n.flags |= Notification.FLAG_AUTO_CANCEL;
                notificationManager.notify(0,n);
            }
        });

        notification_big.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                if(heading.getText().length() < 0)
                {
                    heading_text = "test";
                }
                else
                {
                    heading_text = heading.getText().toString();
                }

                if (Build.VERSION.SDK_INT < 11)
                {
                    n = new Notification(R.drawable.ic_launcher,
                            heading_text,
                            System.currentTimeMillis());

                    n.setLatestEventInfo(
                            getApplicationContext(),
                            heading_text,
                            message.getText().toString(),
                            pending);
                }
                else
                {
                   nb = new Notification.Builder(Main.this);

                    Notification.InboxStyle nc =
                            new Notification.InboxStyle();

                    nc.setBigContentTitle(heading_text);

                    String [] text = new String[5];

                    for (int i = 0 ; i < 5 ; i++)
                    {
                        text[i]  = i + ". say hello...";
                        nc.addLine(text[i]);
                    }

                    nb.setStyle(nc);
                }

                notificationManager.notify(100,nb.build());
            }
        });
    }

    private void setRef()
    {
        // TO set Reference to the xml button & edit text object.
        notification_small = (Button) findViewById(R.id.nd_smallnotification);
        notification_big = (Button) findViewById(R.id.nd_bignotification);
        heading = (EditText) findViewById(R.id.nd_etHeading);
        message = (EditText) findViewById(R.id.nd_notificationbody);
    }

}


Step -3 :  Now run your app and write some text for heading and body part of notification. as you can see in below screen shot i have shown both notification type in it. 

if its still not clear to you or have some query ask me in below comment box.if you like it share this tutorial with your friends.

Keep coding...
Screen Shot


Read More

Sunday, 23 March 2014

How To Create Application Folder in SD Card ?

1 comment :
Android framework create your application folder in internal space when you install any of app. it is located at data/data/package-name folder. if you have rooted emulator or smart phone you can check it out. but it has one disadvantage once user remove your app this folder will also be removed but if you want to store data after it also so you can use it if user again install your app or you want to store some info related to your app on SD card then you can create it using this tutorial.  just follow the steps of this tutorial.

Step -1 : Create New Android application and give name MainActivity to main activity and same name for layout file. minSdkVersion="11” and targetSdkVersion="17".you can use below android version also for compilation and build option. put this below code in your mainactivity so once user start your app it will be created so you can use it further in your app.
MainActivity.java
package com.androprogrammer.tutorialsamples;

import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.ActionBarActivity;
import android.widget.Toast;

import java.io.File;


public class MainActivity extends ActionBarActivity {

    String folderPath;
    File folder;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sdcard_folder_demo);
        folderPath = createFolder();
    }

    private String createFolder()
    {
            String extStorageDirectory = Environment
                    .getExternalStorageDirectory().toString();
            folder = new File(extStorageDirectory, "/Android/data/" + getPackageName());
            if(!folder.exists())
            {
                folder.mkdir();
                Toast.makeText(MainActivity.this, "Folder Created At :" + folder.getPath().toString(), Toast.LENGTH_LONG).show();
            }
            else
            {
                Toast.makeText(MainActivity.this, "Folder Already At :" + folder.getPath().toString(), Toast.LENGTH_LONG).show();
            }
            return folder.getPath().toString();
    }
}
Step -2 : i have created createFolder() method it will also check if folder is already created or not. if it is there it return path to the folder. the above code will create folder with your package name so to check out run your application. one more thing in order to create or write in SD card you required to add below permission in manifest file.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Screen Shots
androprogrammer.comandroprogrammer.com

That's it check out your application folder in SD card at Android/data/package-name folder. now you can store any data in or file in this folder using string returned by that method.

Keep coding.. 
Read More

Thursday, 13 March 2014

Create Android Dynamic view with Fragments...

No comments :
In Android Application to Perform multiple task you have to create different activities or services or both but using fragments you can use multiple views in single fragment activity. The Concept of Fragments comes from Android 3.0 (Honeycomb) but now developers have created many API so you can use it in below android version also. In this tutorial i am going to explain you how you can implements fragment in your application easily. The Fragment concept is quit confusing and from documentation you can not understand it properly. 

So Go through the full tutorial and don't miss any steps because it is confusing so you may miss some of the main points. In this tutorial i am going to create List of Website and When user clicks on it. it will open that site in web view. so these are the files i am going to create in my project. i am clarifying it because their are many tutorials but in many of them you get confuse between those files so have a look it.

Java (Class) Files
1. MainActivity.java
2.FragmentListview.java
3.FragmentWebview.java
4.FragmentSupport.java

Xml (Layout) Files
1.activity_main.xml
2.fragmentlistview.xml
3.fragmentwebview.xml
4.fragment_support.xml


Fragments in android



This is how it looks in portrait view. When mobile is in Portrait view only one view is display to the user. when user click on list item then new view is get created and display to the user. you can add view in back stack of fragment. further read about back stack navigation.
Below image is of fragment in landscape view. in order to work your application in landscape mode you have to create folder name as layout-land. 


Fragments in android

Step -1 : Create New Android application and give name MainActivity to main activity and same name for layout file. minSdkVersion="11” and targetSdkVersion="17".you can use below android version also for compilation and build option.
Step-2 : in your activity_main.xml file add fragment in it. when you add it in eclipse you have option to create fragment class but in android studio you will see below popup box then select any of them we will change it later.

Fragments in android

Now below coding is of activity_main.xml file you can put it in your code.
activity_main.xml



    


Now Create New Layout File For List view and add list view in it and Layout for Web view also. this layouts are use to create dynamically view.
fragmentlistview.xml


    
    


fragmentwebview.xml


    

Step-3 : Create New Activity and name it fragmentSupport.jave and fragment_support.xml. Below one is layout for fragment support activity. this activity is for take index of list item and pass it to the web fragment. in landscape view both layout is in view so you are not require to call or create web view again.
fragment_support.xml


    
    


now create layout-land folder in res folder and create new layout file and give same name as activity_main.xml. android will automatically use this view when user rotate mobile to landscape view. then copy below code in it. it have both fragment listview and webview. 
now all your layout is done. make sure name of fragments are same in portrait view layout file and landscape view file. 

Step-4 : All layout is set so now i proceed to coding so copy below code in MainActivity.java file. the MaiActivity.java file implements interface that is created in FragmentListview.java class. this interface is connector between two views. 
MainActivity.java
package com.androprogrammer.democollection;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.app.FragmentManager;


public class MainActivity extends Activity implements FragmentListview.OnSiteSelectedListener{

    FragmentWebview web;
    FragmentListview list;
    FragmentManager manager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        manager = getFragmentManager();
        list = (FragmentListview) manager.findFragmentById(R.id.fragment1);
        list.setRefrence(this);
    }

    @Override
    public void onSiteSelected(int i) {
        // TODO Auto-generated method stub

        web = (FragmentWebview) manager.findFragmentById(R.id.fragment2);
        // Check for landscape mode
        if (web!= null && web.isVisible())
        {
            web.setNewPage(i);
        }
        else
        {
            Intent intent = new Intent(this , Fragmentsupport.class);
            intent.putExtra("index", i);
            startActivity(intent);
        }
    }

}
onSiteselected method is implemented in OnSiteSelectedListener interface. this method will take index from main view weather it is portrait view or landscape view and then send it to the Fragmentwebview class to get website from String array and then load it in Web view. now put below code in FragmentListview.java file.
FragmentListview.java
package com.androprogrammer.democollection;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class FragmentListview extends Fragment implements AdapterView.OnItemClickListener
{
    ListView list;
 String [] websites = {"Google","Facebook","Twitter","Xda-developer"};
 
 
 OnSiteSelectedListener SiteListener;

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

 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container,
   Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  View v = inflater.inflate(R.layout.fragmentlistview, container, false);
        list = (ListView) v.findViewById(R.id.list);
        list.setAdapter(new ArrayAdapter(getActivity().getApplicationContext(),android.R.layout.simple_list_item_1,websites));
        list.setOnItemClickListener(this);
        return v;
 }

    @Override
    public void onItemClick(AdapterView adapterView, View view, int position, long l)
    {
        SiteListener.onSiteSelected(position);
    }

    // Container Activity must implement this interface
    public interface OnSiteSelectedListener {
        public void onSiteSelected(int i);
    }

    public void setRefrence(OnSiteSelectedListener siteListener)
    {
        this.SiteListener = siteListener;
    }

}
Fragmentwebview.java
package com.androprogrammer.democollection;

import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;

public class FragmentWebview extends Fragment {

 WebView webView;
 String [] links = {"http://www.google.com","http://www.facebook.com","http://www.twitter.com" , "http://www.xda-developers.com"};
 @Override
 public void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
 }

 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container,
   Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragmentwebview, container, false);
  webView = (WebView) v.findViewById(R.id.webView1);
        webView.loadUrl(links[0].toString());
        return v;
 }

 public void setNewPage(int i) 
 {
  //webView = (WebView) getView().findViewById(R.id.webView1);
  Log.d("webveiw", "called");
  webView.loadUrl(links[i].toString());
 }
}
FragmentSupport.java
package com.androprogrammer.democollection;

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

public class Fragmentsupport extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_support);
        Intent intent = getIntent();
        int index = intent.getIntExtra("index",0);
        FragmentWebview web = (FragmentWebview) getFragmentManager().findFragmentById(R.id.fragment2);
        if (web != null)
            web.setNewPage(index);

    }
}

the above four class file is not activity only MainActivity and FragmentSupport is activity so make sure you have added entry in manifest file. one more thing add below permission also in manifest file.
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
that's it. you have created fragment project successfully. so now customize it as you require.
you can download full source code from here.
Keep Coding...
Read More

Wednesday, 19 February 2014

Check Internet Connectivity Status in Android.

No comments :
To Access Web Services or Internet connection you required to check weather connection is available or not. so to check how you can do this read my this article in which i will help you to get connection status in your application. there are no of ways to get connectivity status like broadcast receiver , back ground service etc. but in this example i am using connectivity manager class which allow to use connection service in our application. 

Step -1  : Create New Android application and give name ConnectivityDemo to main activity and same name for layout file. minSdkVersion="17” and targetSdkVersion="17".you can use below android version also for compilation and build option.

Step-2 : in your connectivitydemo.xml file put the below code in it. in this layout file i have used two buttons but if you won't require it you can skip this step.
ConnectivityDemo.xml


      

    


Step-3 : Above layout File having one button for checking mobile data connection and one is for wifi connection.  now put below code in ConnectivityDemo.java file.
ConnectivityDemo.java
package com.example.samplecollection;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class ConnectivityDemo extends Activity implements OnClickListener{

 Button MobileData,wifi;
 boolean status;
 CheckForConnection cf;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.connectivity_demo);
  setRef();
 }

 private void setRef()
 {
  // TO set Refrence to the xml button object.
  MobileData = (Button) findViewById(R.id.CD_bt_mdata);
  wifi = (Button) findViewById(R.id.CD_bt_wifi);
  MobileData.setOnClickListener(this);
  wifi.setOnClickListener(this);
  
 }

 @Override
 public void onClick(View v)
 {
  // Get Which button is clicked by user
  switch (v.getId())
  {
   case R.id.CD_bt_mdata:
    cf = new CheckForConnection();
    status = cf.getMobileDataStatus(ConnectivityDemo.this);
    if(status)
     Toast.makeText(ConnectivityDemo.this,"Data Connection is On.", Toast.LENGTH_LONG).show();
    else
     Toast.makeText(ConnectivityDemo.this,"Data Connection is Off", Toast.LENGTH_LONG).show();
   break;

   case R.id.CD_bt_wifi:
    cf= new CheckForConnection();
    status = cf.getWifiStatus(ConnectivityDemo.this);
    if(status)
     Toast.makeText(ConnectivityDemo.this,"Wifi Connection is On.", Toast.LENGTH_LONG).show();
    else
     Toast.makeText(ConnectivityDemo.this,"Wifi Connection is Off.", Toast.LENGTH_LONG).show();
   break;
   
  default:
   break;
  }
  
 }

}
Step-4 : i have created another class CheckForConnection which actually check weather mobile data or wifi is on or not. in android you can not do network connectivity task on main thread so to perform network task i have created this class. this is the main and handy point because if you create Broad cast Receiver you have to register it and you have to add entry in manifest file also but if you forget any of this its like a burden for you. and if you create service in your application it runs continuously. so that's why i choose this way  to make yor work easy. now create new class CheckForConnection.java. and copy below code in it.
CheckForConnection.java
package com.example.samplecollection;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class CheckForConnection
{
 
    public static boolean getWifiStatus(Context context) 
    {
        // To get System Connectivity status
     ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        if (null != activeNetwork)
        {
         // Check For Wifi Status 
            if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
                return true;
            else
             return false;
        } 
        
        return false;
    }

    public static boolean getMobileDataStatus(Context context) 
    {
        // To get System Connectivity status
     ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        if (null != activeNetwork)
        {
         // Check For Mobile Data Status  
            if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
                return true;
            else
             return false;
        } 
        
        return false;
    }
    
 
}


Screen Shots
androprogrammer
androprogrammer.com

Now just run your application and check weather it works.  i hope you understand the way i have done this so you can implement in your application. if you have any query or problem ask in below comment box.

Keep coding...
Read More