Monday, November 26, 2012

How To Vibrate The Android Phone

In this tutorial we learn How to Vibrate a phone in default manner or  in the pattern you want.

What we learn:
Service
Vibrating the Phone

Requires Knowledge:
Basic Android


To vibrate a phone we need following Permission Do not forget to declare this permission in Manifest.

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

We can Vibrate a Phone Using an Activity  , Service and Using Threads.

Using Activity will not be a good Idea because it takes time to vibrate the Phone and an Activity always runs in foreground.

We will implement using Service because  a Service runs in Background.

for we need to have an Object of Class Vibrator, we do not create the Object directly but we get Vibrate System Service.

Vibrator v = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);

Add    <uses-permission android:name="android.permission.VIBRATE"/>  in Your Manifest

So let's start.

Create a new Android Project  "Vibrate Phone".
and edit the manifest and main.xml file

manifest file


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidjuncture.vibrate"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />
    
    <uses-permission android:name="android.permission.VIBRATE"/>

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".VibrateMainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
        <!-- Declare the Vibrate Service -->
        <service android:name=".VibrateService"/>
        
    </application>

</manifest>

main.xml


(to be inflated/used in VibrateMainActivity)




<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" 
    android:background="#99C2D6"
    android:orientation="vertical">
    
    

    <TextView
        android:layout_marginTop="140dp"
        android:layout_gravity="center_horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20dp"
        android:text="Android Vibrate Service Example" />

    <Button
        android:id="@+id/buttonVibrate"
        android:layout_marginTop="20dp"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Vibrate" />
    
</LinearLayout>

When User clicks on Vibrate Button we will start a new Service which will vibrate the phone.

VibrateMainActivity .java

public class VibrateMainActivity extends Activity 
{

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
   
    Button btnVibrate=(Button)findViewById(R.id.buttonVibrate);
   
   
    // Set on click listener and start vibrate service when clicked on Button Vibrate
   
    btnVibrate.setOnClickListener(new View.OnClickListener() {

public void onClick(View arg0) {
// TODO Auto-generated method stub

// Create a New Intent and start the service
Intent intentVibrate =new Intent(getApplicationContext(),VibrateService.class);
startService(intentVibrate);

}
});
    }

   
}





And The Service Class

Do Not Forget To Declare the Service in Manifest like
<service android:name=".VibrateService"/>

public class VibrateService  extends Service
{

   

           @Override
            public void onStart(Intent intent, int startId) 
           {
                // TODO Auto-generated method stub
                super.onStart(intent, startId);
               
                       
                       
                                    Vibrator v = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);

                                     // pass the number of millseconds fro which you want to vibrate the phone here we
                                     // have passed 2000 so phone will vibrate for 2 seconds.

                                      v.vibrate(2000);

                                   // If you want to vibrate  in a pattern
                                   //  long pattern[]={0,800,200,1200,300,2000,400,4000};
                                   // 2nd argument is for repetition pass -1 if you do not want to repeat the Vibrate
                                   // v.vibrate(pattern,-1);

                                  Toast.makeText(getApplicationContext(), "Phone is Vibrating", Toast.LENGTH_LONG).show();
                             }

        @Override
        public IBinder onBind(Intent intent)
        {
            // TODO Auto-generated method stub
            return null;
        }
      
}

Point To Note:


   long pattern[]={0,800,200,1200,300,2000,400,4000}

this is pattern in which we want to Vibrate the Phone
first 0  means silent for 0 milisecond
800 means vibrate for 800 milisecond
200 means  means silent for 200 milisecond
1200  means vibrate for 1200 miliseconds

and So On.



Using Telephony Manager In Android with Example

The Android Development Tutorials blog contains Basic as well as Advanced android tutorials.Go to Android Development Tutorials to get list of all Android Tutorials.

 Telephony Manager

Telephony Manager provides access to information about the telephony services on the device. Applications can use the methods in this class to determine telephony services and states, as well as to access some types of subscriber information. Applications can also register a listener to receive notification of telephony state changes.

You do not instantiate this class directly; instead, you retrieve a reference to an instance through Context.getSystemService(Context.TELEPHONY_SERVICE).

Android Custom Alert Dialog Example

 Some More Good  Android Topics
Customizing Toast In Android 
 Showing Toast for Longer Time
Customizing Checkboxes In Android  
Customizing Progress Bar
To learn Basic of Android Animation  go to  Android Animation Basics

 

 

Permission Required: 


To work with Telephony Manager and to read the phone details we need
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>           permission.So  add this permission in  your manifest file.

Accessing the Telephony Manager:

Have an  object of TelephonyMnager
TelephonyManager  tm=(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);

Get IMEI Number of Phone

         String IMEINumber=tm.getDeviceId();

 Get Subscriber ID

          String subscriberID=tm.getDeviceId();

  Get SIM Serial Number

            String SIMSerialNumber=tm.getSimSerialNumber();

 Get Network Country ISO Code

             String networkCountryISO=tm.getNetworkCountryIso();

 Get SIM Country ISO Code

               String SIMCountryISO=tm.getSimCountryIso();

 Get the device software version

               String softwareVersion=tm.getDeviceSoftwareVersion()

 Get the Voice mail number

               String voiceMailNumber=tm.getVoiceMailNumber();


 Get the Phone Type CDMA/GSM/NONE

/ /Get the type of network you are connected with 
            int phoneType=tm.getPhoneType();

            switch (phoneType)
            {
                    case (TelephonyManager.PHONE_TYPE_CDMA):

                               // your code
                                   break;
                    case (TelephonyManager.PHONE_TYPE_GSM) 

                               // your code                 
                                   break;
                    case (TelephonyManager.PHONE_TYPE_NONE):

                               // your code              
                                    break;
             }


 Find whether the Phone is in Roaming, returns true if in roaming

             boolean isRoaming=tm.isNetworkRoaming();
              if(isRoaming)
                      phoneDetails+="\nIs In Roaming : "+"YES";
              else
                     phoneDetails+="\nIs In Roaming : "+"NO";


Get the SIM state/Details

            int SIMState=tm.getSimState();
            switch(SIMState)
            {
                    case TelephonyManager.SIM_STATE_ABSENT :
                        // your code
                        break;
                    case TelephonyManager.SIM_STATE_NETWORK_LOCKED :
                        // your code
                        break;
                    case TelephonyManager.SIM_STATE_PIN_REQUIRED :
                        // your code
                        break;
                    case TelephonyManager.SIM_STATE_PUK_REQUIRED :
                        // your code
                        break;
                    case TelephonyManager.SIM_STATE_READY :
                        // your code
                        break;
                    case TelephonyManager.SIM_STATE_UNKNOWN :
                        // your code
                        break;
           
            }





How to Get IMEI number of the Phone


Getting  Network Details


// Get connected network country ISO code
String networkCountry = telephonyManager.getNetworkCountryIso();


// Get the connected network operator ID (MCC + MNC)
String networkOperatorId = telephonyManager.getNetworkOperator();


// Get the connected network operator name
String networkName = telephonyManager.getNetworkOperatorName();


// Get the type of network you are connected with 

int networkType = telephonyManager.getNetworkType();
switch (networkType) {
case (TelephonyManager.NETWORK_TYPE_1xRTT) :"  Your Code ":
break;
case (TelephonyManager.NETWORK_TYPE_CDMA) :"  Your Code ":
break;
case (TelephonyManager.NETWORK_TYPE_EDGE) : "  Your Code ":
break;
case (TelephonyManager.NETWORK_TYPE_EVDO_0) :"  Your Code ":
break;





 

Getting SIM Details :


Using the Object of Telephony Manager class we can get the details like SIM Serial number, Country Code, Network Provider code and other Details.

int simState = telephonyManager.getSimState();
switch (simState) 

{
            case (TelephonyManager.SIM_STATE_ABSENT): break;
            case (TelephonyManager.SIM_STATE_NETWORK_LOCKED): break;
            case (TelephonyManager.SIM_STATE_PIN_REQUIRED): break;
           case (TelephonyManager.SIM_STATE_PUK_REQUIRED): break;
           case (TelephonyManager.SIM_STATE_UNKNOWN): break;
           case (TelephonyManager.SIM_STATE_READY): 

            {
                         // Get the SIM country ISO code
                       String simCountry = telephonyManager.getSimCountryIso();
                         // Get the operator code of the active SIM (MCC + MNC)
                      String simOperatorCode = telephonyManager.getSimOperator();
                       // Get the name of the SIM operator
                      String simOperatorName = telephonyManager.getSimOperatorName();
                        // -- Requires READ_PHONE_STATE uses-permission --
                        // Get the SIM’s serial number

                       String simSerial = telephonyManager.getSimSerialNumber();

          }
}





 

New Advance Topics:
Android ImageSwitcher                    Android TextSwitcher                                Android ViewFlipper
Android Gesture Detector               Handling/Detecting Swap Events                Gradient Drawable
Detecting Missed Calls                    Hide Title Bar                                           GridView Animation

 Beginning With Android
      Android : Introduction                                                              Configuring Eclipse for Android Development
     Creating Your First Android Project                                           Understanding Android Manifest File of your android app

 Advance Android Topics                                                              Customizing Android Views


Working With Layouts                                                                Working With Views

Understanding Layouts in Android                                                   Using Buttons and EditText in Android
Working with Linear Layout (With Example)                                     Using CheckBoxes in Android
Nested Linear Layout (With Example)                                              Using AutoCompleteTextView in Android                                                                                          Grid View
Relative Layout In Android                                                               ListView
Table Layout                                                                                   Android ProgressBar
Frame Layout(With Example)                                                          Customizing ProgressBar
Absolute Layout                                                                             Customizing Radio Buttons
Grid Layout                                                                                    Customizing Checkboxes In Android

Android Components                                                                 Dialogs In Android

Activity In Android                                                                    Working With Alert Dialog
Activity Life Cycle                                                                    Adding Radio Buttons In Dialog
Starting Activity For Result                                                       Adding Check Boxes In Dialog
Sending Data from One Activity to Other in Android                    Creating Customized Dialogs in Android
Returning Result from Activity                                                   Creating Dialog To Collect User Input
Android : Service                                                                     DatePicker and TimePickerDialog
BroadcastReceiver                                                                   Using TimePickerDialog and DatePickerDialog In android

Menus In Android                                                                ListView:
Creating Option Menu                                                               Populating ListView With DataBase
Creating Context Menu In Android                                              Populating ListView with ArrayList
                                                                                               ListView with Custom Adapter

Toast                                                                                      Working With SMS
Customizing Toast In Android                                                       How to Send SMS in Android
Customizing the Display Time of Toast                                        How To Receive SMS
Customizing Toast At Runtime                                                  Accessing Inbox In Android
Adding Image in Toast
Showing Toast for Longer Time


TelephonyManager                                                            Storage: Storing Data In Android
Using Telephony Manager In Android                                          SharedPreferences In Android
                                                                                              Reading and Writing files to Internal Stoarage
Working With Incoming Calls                                             DataBase
How To Handle Incoming Calls in Android                                Working With Database in Android
How to Forward an Incoming Call In Android                            Creating Table In Android
CALL States In Android                                                          Inserting, Deleting and Updating Records In Table in Android


Miscellaneous
Notifications In Android
How To Vibrate The Android Phone
Sending Email In Android
Opening a webpage In Browser
How to Access PhoneBook In Android
Prompt User Input with an AlertDialog



How To Handle Incoming Calls in Android

The Android Development Tutorials blog contains Basic as well as Advanced android tutorials.Go to Android Development Tutorials to get list of all Android Tutorials.

Handle Incoming Calls in Android

In this Post I will describe how to Handle incoming Calls on Android and Reacting to them i.e. receiving, rejecting etc.

We  can do this by Activity and by Broadcast Receiver, here we will do using Activity.

Permissions: 
As I mentioned in my earlier posts we require to declare permission in manifest file.
For listening and reacting to Incoming calls we need following permissions

android.permission.READ_PHONE_STATE   to listen to InComing Calls
"android.permission.MODIFY_PHONE_STATE"   to receive Incoming Calls

You can learn more about permission  Here.

Add these permissions in your manifest file.
Your Manifest file should look like

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

    <uses-sdk android:minSdkVersion="8"
              android:targetSdkVersion="15" />
   
    <uses-permission android:name="android.permission.MODIFY_PHONE_STATE" />
       <uses-permission android:name="android.permission.READ_PHONE_STATE" />


 <application
        android:icon="@drawable/icon"
        android:label="@string/app_name" >
        <activity
            android:name=".HomeActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
       
       
           </application>

</manifest
>




How to Get IMEI number of the Phone



Some More Good  Android Topics
Customizing Toast In Android 
 Showing Toast for Longer Time
Customizing Checkboxes In Android 
Customizing Progress Bar
To learn Basic of Android Animation  go to  Android Animation Basics






Activity:

We need to use TelephonyManager class and  TELEPHONY_SERVICE.

The onCallStateChanged handler receives the phone number associated with incoming calls, and the
state parameter represents the current call state as one of the following three values:



➤ TelephonyManager.CALL_STATE_RINGING When the phone is ringing

 

 

 

 

 

 

 

➤ TelephonyManager.CALL_STATE_OFFHOOK When the phone is currently in a call means call is recieved









 

 

 

 

 

➤ TelephonyManager.CALL_STATE_IDLE When the phone is neither ringing nor in a call

 

 

 

 

 

 

 

 

 

 

 

 

How to Monitor Incoming Calls:


We need to have a listener to listen the InComing Calls

PhoneStateListener callStateListener = new PhoneStateListener() {
public void onCallStateChanged(int state, String incomingNumber) {
// TODO React to incoming call.
}
};
telephonyManager.listen(callStateListener,
PhoneStateListener.LISTEN_CALL_STATE);


Code:


public class GetCallerInfoActivity extends Activity
{


  @Override
            public void onCreate(Bundle savedInstanceState)
            {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.main);
                   
                    TelephonyManager telephonyManager =
(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);     
               // register PhoneStateListener
               PhoneStateListener callStateListener = new PhoneStateListener() {
                    public void onCallStateChanged(int state, String incomingNumber)
                    {
                            //  React to incoming call.
                            number=incomingNumber;

                             // If phone ringing
                            if(state==TelephonyManager.CALL_STATE_RINGING)
                            {
                                    Toast.makeText(getApplicationContext(),"Phone Is Riging", Toast.LENGTH_LONG).show();
                                   
                            }

                              // If incoming call received
                            if(state==TelephonyManager.CALL_STATE_OFFHOOK)
                            {
                                Toast.makeText(getApplicationContext(),"Phone is Currently in A call", Toast.LENGTH_LONG).show();
                            }
                           
                           
                            if(state==TelephonyManager.CALL_STATE_IDLE)
                            {
                                Toast.makeText(getApplicationContext(),"phone is neither ringing nor in a call", Toast.LENGTH_LONG).show();
                            }
                    }
                    };
                    telephonyManager.listen(callStateListener,PhoneStateListener.LISTEN_CALL_STATE);
                   
                   
                   
            }
                   

                   
            }



How To Launch the Dialer to Initiate Phone Calls:


Use an Intent action to start a dialer activity; you should specify the number to dial using the tel: schema as the data component of the Intent.

Use the Intent.ACTION_DIAL Activity action to launch a dialer rather than dial the number immediately.
This action starts a dialer Activity, passing in the specified number but allowing the dialer application
to manage the call initialization (the default dialer asks the user to explicitly initiate the call). This
action doesn’t require any permissions and is the standard way applications should initiate calls.

Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:1234567"));
startActivity(intent);










 

New Advance Topics:
Android ImageSwitcher                    Android TextSwitcher                                Android ViewFlipper
Android Gesture Detector               Handling/Detecting Swap Events                Gradient Drawable
Detecting Missed Calls                    Hide Title Bar                                           GridView Animation

 Beginning With Android
      Android : Introduction                                                              Configuring Eclipse for Android Development
     Creating Your First Android Project                                           Understanding Android Manifest File of your android app

 Advance Android Topics                                                              Customizing Android Views


Working With Layouts                                                                Working With Views

Understanding Layouts in Android                                                   Using Buttons and EditText in Android
Working with Linear Layout (With Example)                                     Using CheckBoxes in Android
Nested Linear Layout (With Example)                                              Using AutoCompleteTextView in Android                                                                                          Grid View
Relative Layout In Android                                                               ListView
Table Layout                                                                                   Android ProgressBar
Frame Layout(With Example)                                                          Customizing ProgressBar
Absolute Layout                                                                             Customizing Radio Buttons
Grid Layout                                                                                    Customizing Checkboxes In Android

Android Components                                                                 Dialogs In Android

Activity In Android                                                                    Working With Alert Dialog
Activity Life Cycle                                                                    Adding Radio Buttons In Dialog
Starting Activity For Result                                                       Adding Check Boxes In Dialog
Sending Data from One Activity to Other in Android                    Creating Customized Dialogs in Android
Returning Result from Activity                                                   Creating Dialog To Collect User Input
Android : Service                                                                     DatePicker and TimePickerDialog
BroadcastReceiver                                                                   Using TimePickerDialog and DatePickerDialog In android

Menus In Android                                                                ListView:
Creating Option Menu                                                               Populating ListView With DataBase
Creating Context Menu In Android                                              Populating ListView with ArrayList
                                                                                               ListView with Custom Adapter

Toast                                                                                      Working With SMS
Customizing Toast In Android                                                       How to Send SMS in Android
Customizing the Display Time of Toast                                        How To Receive SMS
Customizing Toast At Runtime                                                  Accessing Inbox In Android
Adding Image in Toast
Showing Toast for Longer Time


TelephonyManager                                                            Storage: Storing Data In Android
Using Telephony Manager In Android                                          SharedPreferences In Android
                                                                                              Reading and Writing files to Internal Stoarage
Working With Incoming Calls                                             DataBase
How To Handle Incoming Calls in Android                                Working With Database in Android
How to Forward an Incoming Call In Android                            Creating Table In Android
CALL States In Android                                                          Inserting, Deleting and Updating Records In Table in Android


Miscellaneous
Notifications In Android
How To Vibrate The Android Phone
Sending Email In Android
Opening a webpage In Browser
How to Access PhoneBook In Android
Prompt User Input with an AlertDialog