1. 若要在應用程式內使用到震動這個服務,需先在AndroidManifest.xml允許存取android.permission.VIBRATE這個權限。
2. MainActivity.java
package org.me.android_vibrate;
import android.app.Activity;
import android.app.Service;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
Spinner spinner = (Spinner) findViewById(R.id.spinnner);
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item,new String[]{"長震動","短震動","連續短震動"});
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){
public void onItemSelected(AdapterView adapterView, View view, int position, long id){
//取得震動服務
Vibrator myVibrator = (Vibrator) getApplication().getSystemService(Service.VIBRATOR_SERVICE);
switch(position) {
case 0:
//震動3秒
myVibrator.vibrate(3000);
break;
case 1:
//震動0.1秒
myVibrator.vibrate(100);
break;
case 2:
//停0.01秒之後震動0.1秒(重覆三次)
myVibrator.vibrate(new long[]{10, 100, 10, 100, 10, 100}, -1);
break;
default:
break;
}
}
public void onNothingSelected(AdapterView arg0) {
Toast.makeText(MainActivity.this, "您沒有選擇任何項目", Toast.LENGTH_LONG).show();
}
});
}
}
3. main.xml(Layout)
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">"
<Spinner
android:id="@+id/spinnner"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Spinner>
</LinearLayout>
4. AndroidManifest.xml
<?xml version="1.0" encoding="UTF-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.me.android_vibrate">
<application>
<activity android:name=".MainActivity" android:label="Vibrate">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.VIBRATE" />
</manifest>
5. 執行之後的畫面。