0

我希望我的应用程序振动 3 秒钟,但它不起作用,我不知道为什么。当我单击按钮时,它什么也不做。起初我试图在主要活动中这样做,但结果相同。

主要活动

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_my);
    final Button vibrateButton = new Button(this);
    final Intent vibration = new Intent(this, MyService.class);

    vibrateButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            startService(vibration);
        }
    });
}

服务

public class MyService extends IntentService {
    public MyService()
    {
        super("MyService");
    }

    @Override
    protected void onHandleIntent(Intent vibration)
    {
        Vibrator vibe = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
        vibe.vibrate(3000);
    }
}
4

1 回答 1

2

尝试:

 import android.os.Vibrator;
 ...
 Vibrator v = (Vibrator) this.context.getSystemService(Context.VIBRATOR_SERVICE);
 // Vibrate for 3000 milliseconds
 v.vibrate(3000);

笔记:

不要忘记在 AndroidManifest.xml 文件中包含权限:

<uses-permission android:name="android.permission.VIBRATE"/>
于 2014-10-14T07:52:21.610 回答