Vibrator
端末のバイブレーション機能を利用するときに使用します。
使用するにはAndroidManifest.xmlにパーミッションを追加する必要があります。
<uses-permission android:name="android.permission.VIBRATE"/>
![]() |
| Vibrator |
public class MainActivity extends Activity implements OnClickListener{
private Vibrator vibrator;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1 = (Button)findViewById(R.id.button1);//バイブ単発
button1.setOnClickListener(this);
Button button2 = (Button)findViewById(R.id.button2);//バイブ連続
button2.setOnClickListener(this);
Button button3 = (Button)findViewById(R.id.button3);//止める
button3.setOnClickListener(this);
//Vibratorインスタンス取得
vibrator = (Vibrator)getSystemService(VIBRATOR_SERVICE);
}
@Override
public void onClick(View arg0) {
// TODO 自動生成されたメソッド・スタブ
switch (arg0.getId()){
case R.id.button1:
//バイブ単発
vibrator.vibrate(300);//300ミリ秒の振動
break;
case R.id.button2:
//バイブ連続
long[] pattern = {100, 500, 300, 1000, 300, 1500};//{開始,振動,休止,振動,休止,振動}
vibrator.vibrate(pattern, 0);//第2引数,0は繰り返し,-1は単発
break;
case R.id.button3://止める
vibrator.cancel();
break;
}
}
}
res/layout/activity_main.xml
<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:orientation="vertical" android:gravity="center" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="20sp" android:text="バイブレーション" /> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="バイブ単発" /> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="バイブ連続" /> <Button android:id="@+id/button3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="止める" /> </LinearLayout>
res/AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="sample.helloworld" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <uses-permission android:name="android.permission.VIBRATE"/>//これを追加 <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="sample.helloworld.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> </application> </manifest>

0 件のコメント:
コメントを投稿