效果
需要真实手机
代码
package com.javen.devicemange.CrazyOne.content; import android.app.Service; import android.os.Bundle; import android.os.Vibrator; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import com.javen.devicemange.R; /** * Created by Administrator on 2017/2/21 0021. * 使用Vibrator控制手机震动 * 权限:<uses-permission android:name="android.permission.VIBRATE"/> */ public class VibratorTest extends AppCompatActivity implements View.OnClickListener { private Button vibrator1; private Button vibrator2; Vibrator vibrator; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.vibratortest); initView(); vibrator = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE); } private void initView() { vibrator1 = (Button) findViewById(R.id.vibrator1); vibrator1.setOnClickListener(this); vibrator2 = (Button) findViewById(R.id.vibrator2); vibrator2.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.vibrator1: //控制手机震动2s vibrator.vibrate(2000); break; case R.id.vibrator2: //等待400ms打开震动,持续800ms,等待1200ms打开震动,持续1600ms。。。 long[] pattern = {400, 800, 1200, 1600}; //指定对pattern数组从repeat索引开始的震动进行循环,-1代表不进行循环 int repeat = 1; vibrator.vibrate(pattern, repeat); break; } } @Override protected void onDestroy() { super.onDestroy(); vibrator.cancel(); } }
布局xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <Button android:id="@+id/vibrator1" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="控制手机震动2s"/> <Button android:id="@+id/vibrator2" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="进行循环震动"/> </LinearLayout>
AndroidManifest.xml
<uses-permission android:name="android.permission.VIBRATE"/>
。。。