Allows android buttons to vibrate the key sound.
To call the system vibration service when pressing a key, you must first add the corresponding permissions in AndroidMainfest. xml.
Then Vibrator vibrator = (Vibrator) getSystemService (VIBRATOR_SERVICE );
// Vibrator. vibrate (3000 );
// Set the Vibrate vibration cycle
Vibrator. vibrate (new long [] {1000,2000, 3000,4000}, 0 );
Here, I found a method class for writing good vibrations on the Internet.
Package com. lxb. switchdemo; import android. app. activity; import android. app. service; import android. OS. vibrator; import android. widget. linearLayout;/*** mobile phone vibration tool class ** @ author Administrator **/public class VibratorUtil {/*** final Activity: the activity instance that calls this method long milliseconds: vibration duration, in milliseconds * long [] pattern: Custom vibration mode. The meanings of numbers in the array are [static duration, vibration duration, static duration, and vibration duration]. The unit of duration is millisecond * boolean isRepeat: whether to Vibrate repeatedly. If it is true, it vibrates repeatedly. If it is false, it only shakes once */public static void Vibrate (final Activity, long milliseconds) {Vibrator vib = (Vibrator) activity. getSystemService (Service. VIBRATOR_SERVICE); vib. vibrate (milliseconds);} public static void Vibrate (final Activity activity, long [] pattern, boolean isRepeat) {Vibrator vib = (Vibrator) activity. getSystemService (Service. VIBRATOR_SE RVICE); vib. vibrate (pattern, isRepeat? 1:-1 );}}
Of course, you only need to add
VibratorUtil. Vibrate (Switch_demoActivity.this, 100 );
A simple vibration mechanism can be implemented.
Next, we will summarize the implementation of the button sound mechanism,
- Public class MainActivity extends Activity {
- Private Button mButton01;
- Private SoundPool sp; // declare a SoundPool
- Private int music; // defines an integer using load (); To set suondID
-
- @ Override
- Public void onCreate (Bundle savedInstanceState ){
-
- Super. onCreate (savedInstanceState );
- SetContentView (R. layout. activity_main );
- MButton01 = (Button) findViewById (R. id. mButton01 );
- Sp = new SoundPool (10, AudioManager. STREAM_SYSTEM, 5); // The first parameter is the maximum number of data streams simultaneously played, the second data stream type, and the third parameter is the sound quality.
- Music = sp. load (this, R. raw. start, 1); // put your audio material in res/raw. The first parameter is the resource file, and the second parameter is the music priority.
-
- MButton01.setOnClickListener (new OnClickListener (){
- @ Override
- Public void onClick (View v ){
- Sp. play (music, 1, 1, 0, 0, 1 );
- }
- }
- }
- } Raw is a new folder under res, which is a resource file that can be directly used without compilation. Of course, to avoid the problem that keys cannot be recognized in some machines, it is best to convert the audio format to ogg.