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.



83 comments:

  1. Brilliant! I'm an experienced developer but new to android. I've looked a loads of other examples of how to do this, but your code is simple and easy to follow.

    Thank you!

    ReplyDelete
  2. Really helpfull!!!!!!!

    ReplyDelete
  3. Extremely helpful! Very concise and clear.

    ReplyDelete
  4. How to make with checkbox ? Thanks...

    ReplyDelete
  5. Does not work on Android 5.0+

    ReplyDelete
  6. I want to add vibration pattern for specfic contact can you please help me with this..??

    ReplyDelete
  7. Thanks for sharing this valuable content. In my view, if all webmasters and bloggers made good content as you did, the web will be a lot more useful than ever before. Voyance telephone

    ReplyDelete
  8. Wow, What a Excellent post. I really found this to much informatics. It is what i was searching for.I would like to suggest you that please keep sharing such type of info.Thanks Onida Customer Care

    ReplyDelete
  9. Thank you again for all the knowledge you distribute,Good post. I was very interested in the article, it's quite inspiring I should admit. I like visiting you site since I always come across interesting articles like this one.Great Job, I greatly appreciate that.Do Keep sharing! Regards, Phone spy

    ReplyDelete
  10. I found your this post while searching for some related information on blog search...Its a good post..keep posting and update the information. spy phone app

    ReplyDelete
  11. Cell phones have become a significant piece of our lives.Display reparatur

    ReplyDelete
  12. Anupama is an Indian drama television series produced by Ekta Kapoor's Anupama delayed check out the new premiere date India Today.

    Anupama Full Episode

    ReplyDelete
  13. I definitely enjoying every little bit of it. It is a great website and nice share. I want to thank you. Good job! You guys do a great blog, and have some great contents. Keep up the good work 먹튀검증커뮤니티

    ReplyDelete
  14. "Superb, what a weblog it is! This webpage presents helpful data to us, keep it up.

    " 메이저놀이터

    ReplyDelete
  15. "Thanks for the valuable information and insights you have so provided here...

    " 메이저놀이터

    ReplyDelete
  16. I read your post and I found it amazing! thank! 먹튀검증목록

    ReplyDelete
  17. Very informative post! There is a lot of information here that can help any business get started with a successful social networking campaign. 토토사이트

    ReplyDelete
  18. Good article, but it would be better if in future you can share more about this subject. Keep posting. 메이저놀이터

    ReplyDelete
  19. I’ve found every article I’ve read very helpful. Good one, and keep it going. windshield repair san diego

    ReplyDelete
  20. I found that site very usefull and this survey is very cirious, I ' ve never seen a blog that demand a survey for this actions, very curious.. 토토사이트

    ReplyDelete
  21. I seriously love your website.. Excellent colors & theme.
    Did you create this amazing site yourself? Please reply back as I’m attempting to create my own site
    and want to know where you got this from or just what the theme is named.
    Cheers!한국야동

    ReplyDelete
  22. It's always a pleasure to read your magnificent articles on this site. You are among the top writers of this generation, and there's nothing you can do that will change my opinion on that. My friends will soon realize how good you are. 온라인포커

    ReplyDelete
  23. Thank you and thank you so much. I'll share you useful information.사설토토사이트

    ReplyDelete
  24. Your writing is perfect and complete. However, I think it will be more wonderful if your post includes additional topics that I am thinking of. I have a lot of posts on my site similar to your topic. Would you like to visit once? 토토커뮤니티

    ReplyDelete
  25. Your writing is perfect and complete. However, I think it will be more wonderful if your post includes additional topics that I am thinking of. I have a lot of posts on my site similar to your topic. Would you like to visit once? 토토커뮤니티

    ReplyDelete
  26. Hello, I'm happy to see some great articles on your site. Would you like to come to my site later? My site also has posts, comments and communities similar to yours. Please visit and take a look 토토사이트

    ReplyDelete
  27. I saw your article well. You seem to enjoy 바카라검증사이트 for some reason. We can help you enjoy more fun. Welcome anytime :-)

    ReplyDelete
  28. I've been searching for hours on this topic and finally found your post. , I have read your post and I am very impressed. We prefer your opinion and will visit this site frequently to refer to your opinion. When would you like to visit my site? 토토사이트

    ReplyDelete
  29. Do you have a spam problem on this website; I also am a blogger, and I was wanting to know your situation 먹튀검증 many of us have developed some nice practices and we are looking to trade techniques with others, why not shoot me an email if interested.

    ReplyDelete
  30. The article composing business is going extraordinary for me at this moment, and the vast majority of my prosperity is because of the substance that you post here. I utilize your substance to compose my articles, and the substance makes my great article incredible! 메이저놀이터

    ReplyDelete
  31. Your post is very interesting to me. Reading was so much fun. I think the reason reading is fun is because it is a post related to that I am interested in. Articles related to 메이저놀이터순위 you are the best. I would like you to write a similar post about !

    ReplyDelete
  32. What a post I've been looking for! I'm very happy to finally read this post. 토토사이트 Thank you very much. Can I refer to your post on my website? Your post touched me a lot and helped me a lot. If you have any questions, please visit my site and read what kind of posts I am posting. I am sure it will be interesting.

    ReplyDelete
  33. First of all, I would like to thank you for writing this article. I'm trying to make an article by citing your article.바카라사이트

    ReplyDelete
  34. I've been looking for photos and articles on this topic over the past few days due to a school assignment, and I'm really happy to find a post with the material I was looking for! I bookmark and will come often! Thanks :D 먹튀신고

    ReplyDelete
  35. When I read an article on this topic, the first thought was profound and difficult, and I wondered if others could understand.. My site has a discussion board for articles and photos similar to this topic. Could you please visit me when you have time to discuss this topic? 먹튀검증커뮤니티

    ReplyDelete
  36. Your writing is perfect and complete. However, I think it will be more wonderful if your post includes additional topics that I am thinking of. I have a lot of posts on my site similar to your topic. Would you like to visit once? 먹튀커뮤니티

    ReplyDelete
  37. It's really great. Thank you for providing a quality article. There is something you might be interested in. Do you know 메이저토토 ?

    ReplyDelete
  38. There must have been many difficulties in providing this information.Bóng88 Nevertheless, thank you for providing such high-quality information.

    ReplyDelete
  39. Wow! Thank you! I continuously needed to write on my site something like that. Can I include a part of your post to my site?egaon casino

    ReplyDelete
  40. Youre so right. Im there with you. Your weblog is definitely worth a read if anyone comes throughout it. Im lucky I did because now Ive received a whole new view of this. 먹튀검증사이트

    ReplyDelete

  41. Thanks for your marvelous posting! I actually enjoyed reading it, you could be
    a great author.I will remember to bookmark your blog and will
    eventually come back from now on. I want to encourage you to continue your great
    writing, have a nice weekend!

    Website:온라인카지노


    ReplyDelete
  42. Definitely, what a fantastic website and revealing posts, I definitely will bookmark your site.Have an awsome day!

    Click here to chceck my blog :: 강남안마

    ReplyDelete
  43. Thanks for your marvelous posting! I actually enjoyed reading it, you could be
    a great author.I will remember to bookmark your blog and will
    eventually come back from now on. I want to encourage you to continue your great
    writing, have a nice weekend!카지노사이트

    ReplyDelete
  44. Spot on with this write-up, I seriously 스포츠사이트검증 feel this web site needs a lot more attention.

    ReplyDelete
  45. There is definately a great deal to find out about this topic much for all your proposals on this site. Your shares are very interesting and very enriching 놀이터검증업체

    ReplyDelete
  46. Pretty! This was an extremely wonderful article. Thank you for providing these and wondering how you managed this blog so well. It’s so 먹튀사이트 remarkable thato through this valuable information whenever

    ReplyDelete
  47. Keep working like that!. back scratcher shoe horn Please write good things from now on 토토사이트보증업체

    ReplyDelete
  48. You obviously know what youre talking about 검증사이트목록 I live in a different country than you

    ReplyDelete
  49. Thanks for sharing your info. I truly appreciate your efforts and I will be waiting for your next
    write ups thank you once again. 토토사이트

    ReplyDelete
  50. What’s up to every one, the contents existing at this web page are truly remarkable
    for people knowledge, well, keep up the good work fellows. 온라인경마

    ReplyDelete
  51. Wonderful, what a blog it is! This weblog gives useful facts to us, keep it up. 카지노사이트

    ReplyDelete
  52. Pretty! This was an extremely wonderful post. Thank you for providing this info 토토

    ReplyDelete
  53. First of all, thank you for your post. Your posts are neatly organized with the information I want, so there are plenty of resources to reference. I bookmark this site and will find your posts frequently in the future. Thanks again ^^ Keo hay

    ReplyDelete
  54. It has fully emerged to crown Singapore's southern shores and undoubtedly placed her on the global map of residential landmarks. I still scored the more points than I ever have in a season for GS. I think you would be hard pressed to find somebody with the same consistency I have had over the years so I am happy with that. 메이저토토사이트

    ReplyDelete
  55. Papers get to operate through Bible helpers and also plagiarism checkers to be certain that the author did not find idle at any stage in the process. Language inconsistencies won't be a thing with your newspapers as the specialists of our school paper writing support are passionate about writing and are always excited to strike you with something fresh. By: 메이저사설놀이터

    ReplyDelete
  56. This post is really magnificent. I really like this post. It is one of the best posts that I ve read in a long time. Thanks a lot for this really good post. I really appreciate it 메이저토토

    ReplyDelete
  57. Hello, I am one of the most impressed people in your article. 메이저토토사이트 I'm very curious about how you write such a good article. Are you an expert on this subject? I think so. Thank you again for allowing me to read these posts, and have a nice day today. Thank you.

    ReplyDelete
  58. Please let me know if you’re looking for a article writer for your site. You have some really great posts and I feel I would be a good asset. If you ever want to take some of the load off, I’d absolutely love to write some material for your blog in exchange for a link back to mine. Please send me an email if interested. Thank you 먹튀사이트 I couldn't think of this, but it's amazing! I wrote several posts similar to this one, but please come and see!!

    ReplyDelete
  59. Looking at this article, I miss the time when I didn't wear a mask. Hopefully this corona will end soon. My blog is a blog that mainly posts pictures of daily life before Corona and landscapes at that time. If you want to remember that time again, please visit us. ty le keo

    ReplyDelete
  60. You make so many great points here that I read your article a couple of times. Your views are in accordance with my own for the most part. This is great content for your readers. 우리카지노
    (mm)

    ReplyDelete
  61. One other issue is when you are in a predicament where you would not have a co-signer then you may genuinely wish to try to exhaust all of your financing options. You can get many grants or loans and other grants that will give you finances to assist with school expenses. Thank you for the post.
    カジノ

    ReplyDelete
  62. I used to be able to find good information from your blog posts.
    카지노커뮤니티

    wep

    ReplyDelete
  63. Looking at this article, I miss the time when I didn't wear a mask. keonhacai Hopefully this corona will end soon. My blog is a blog that mainly posts pictures of daily life before Corona and landscapes at that time. If you want to remember that time again, please visit us.

    ReplyDelete
  64. Many thanks for the article, I have a lot of spray lining knowledge but always learn something new. Keep up the good work and thank you again. 먹튀사이트

    ReplyDelete
  65. I finally found what I was looking for! I'm so happy. 안전한놀이터 Your article is what I've been looking for for a long time. I'm happy to find you like this. Could you visit my website if you have time? I'm sure you'll find a post of interest that you'll find interesting.

    ReplyDelete
  66. Been looking for this article for long time ago and finally found here. Thanks for the tips and sharing this post. appreciate!Please check out my website too and let me know what you think.
    스포츠토토

    ReplyDelete
  67. This is very interesting, You are a very skilled blogger. I've joined your rss feed and look forward to seeking more of your wonderful 메이저토토. Also, I have shared your website in my social networks!

    ReplyDelete
  68. While looking for articles on these topics, I came across this article on the site here. As I read your article, I felt like an expert in this field. I have several articles on these topics posted on my site. Could you please visit my homepage? 메이저놀이터순위

    ReplyDelete
  69. You made some good points there. I did a Google search about the topic and found most people will believe your blog. 메이저사이트

    ReplyDelete
  70. Really no matter if someone doesn't be aware of after that its up to other users that they will help, so here it takes place 토토사이트추천.

    ReplyDelete
  71. Hello, I'm happy to see some great articles on your site. Would you like to come to my site later? My site also has posts, comments and communities similar to yours. Please visit and take a look 메이저놀이터

    ReplyDelete
  72. That's a really impressive new idea! 메이저토토사이트추천 It touched me a lot. I would love to hear your opinion on my site. Please come to the site I run once and leave a comment. Thank you.

    ReplyDelete
  73. Howdy! Do you know if they make any plugins to assist with SEO? I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good results. If you know of any please share. Cheers! 안전토토사이트

    ReplyDelete
  74. It's too bad to check your article late. I wonder what it would be if we met a little faster. I want to exchange a little more, but please visit my site 메이저토토사이트 and leave a message!!

    ReplyDelete
  75. Hey, I simply hopped over in your web page by means of StumbleUpon. Not one thing I might in most cases learn, however I favored your feelings none the less. Thank you for making something price reading. 메이저토토사이트

    ReplyDelete