Friday, November 27, 2015

android - How to Vibrate the device programmatically

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity"
    android:background="#c1cfb7"
    >
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="25dp"
        android:textColor="#000"
        android:padding="15dp"
        />
    <Button
        android:id="@+id/btn_on"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Vibrate"
        android:layout_below="@id/tv"
        />
    <Button
        android:id="@+id/btn_repeat"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Repeat Vibration"
        android:layout_toRightOf="@id/btn_on"
        android:layout_below="@id/tv"
        />
    <Button
        android:id="@+id/btn_off"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Off"
        android:layout_below="@id/tv"
        android:layout_toRightOf="@id/btn_repeat"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcode;

import android.content.Context;
import android.content.res.Resources;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.os.Vibrator;


public class MainActivity extends AppCompatActivity {
    private Context mContext;
    private Resources mResources;
    private RelativeLayout mRelativeLayout;
    private TextView mTextView;
    private Button mButtonOn;
    private Button mButtonRepeat;
    private Button mButtonOff;
    private Vibrator mVibrator;

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

        // Get the application context
        mContext = getApplicationContext();

        // Get the Resources
        mResources = getResources();

        // Get the widgets reference from XML layout
        mRelativeLayout = (RelativeLayout) findViewById(R.id.rl);
        mTextView = (TextView) findViewById(R.id.tv);
        mButtonOn = (Button) findViewById(R.id.btn_on);
        mButtonRepeat = (Button) findViewById(R.id.btn_repeat);
        mButtonOff = (Button) findViewById(R.id.btn_off);

        /*
            public abstract Object getSystemService (String name)
                Return the handle to a system-level service by name. The class of the returned
                object varies by the requested name.
        */
        /*
            public static final String VIBRATOR_SERVICE
                Use with getSystemService(Class) to retrieve a Vibrator for interacting
                with the vibration hardware.
        */

        // Initialize a new instance of system Vibrator
        mVibrator = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
        // Check whether device hardware has a Vibrator
        if(mVibrator.hasVibrator()){
            mTextView.setText("Device has a Vibrator.");
        }

        // Set a click listener for Vibrate button
        mButtonOn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                /*
                    public void vibrate (long milliseconds)
                        Vibrate constantly for the specified period of time.
                        This method requires the caller to hold the permission VIBRATE.

                    Parameters
                        milliseconds : The number of milliseconds to vibrate.

                */

                // Vibrate the device for a specified time
                mVibrator.vibrate(5000); // 5 seconds
            }
        });

        // Set a click listener for repeat button
        mButtonRepeat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                /*
                    public void vibrate (long[] pattern, int repeat)
                        Vibrate with a given pattern.
                        Pass in an array of ints that are the durations for which to turn on or off
                        the vibrator in milliseconds. The first value indicates the number of
                        milliseconds to wait before turning the vibrator on. The next value
                        indicates the number of milliseconds for which to keep the vibrator on
                        before turning it off. Subsequent values alternate between durations in
                        milliseconds to turn the vibrator off or to turn the vibrator on.

                        To cause the pattern to repeat, pass the index into the pattern array
                        at which to start the repeat, or -1 to disable repeating.

                        This method requires the caller to hold the permission VIBRATE.

                    Parameters
                        pattern : an array of longs of times for which to turn the vibrator on or off.
                        repeat : the index into pattern at which to repeat, or -1 if you don't want to repeat.

                */
                // Vibrate the device repeatedly.

                // Set a pattern for vibration
                long pattern[] = {50,100,100,250,150,350};

                // Vibrate the device using a pattern and repeat 3 times
                mVibrator.vibrate(pattern,3);
            }
        });

        // Set a click listener for vibration off button
        mButtonOff.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                /*
                    public abstract void cancel ()
                        Turn the vibrator off.

                        This method requires the caller to hold the permission VIBRATE.
                */

                // Cancel the vibration
                mVibrator.cancel();
            }
        });
   }
}
AndroidManifest.xml [permission]

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