Here is source code of the Program to Start a Service to Vibrate Phone in Android. The program is successfully compiled and run on a Windows system using Eclipse Ide. The program output is also shown below.
MainActivity.java
package com.example.vibratephone_service; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button btn = (Button) findViewById(R.id.buttonVibrate); btn.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); } }); } }
VibrateService.java
package com.example.vibratephone_service; import android.app.Service; import android.content.Context; import android.content.Intent; import android.os.IBinder; import android.os.Vibrator; 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); // Vibrating Pattern long pattern[] = { 0, 800, 200, 1200, 300, 2000, 400, 4000 }; v.vibrate(pattern, -1); } @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return null; } }
Activity_main.xml
<RelativeLayout 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:orientation="vertical" > <Button android:id="@+id/buttonVibrate" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/textView1" android:layout_marginTop="99dp" android:text="Vibrate" /> </RelativeLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.vibratephone_service" android:versionCode="1" android:versionName="1.0" > <uses-permission android:name="android.permission.VIBRATE"/> <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.vibratephone_service.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name=".VibrateService"/> </application> </manifest>