我想在振动的同时添加声音。
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"Get Ready Bus is Near",Toast.LENGTH_LONG).show();
Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(2000);
}
振动已成功应用,但是如何在手机振动时添加声音?
答案 0 :(得分:1)
您可以使用MediaPlayer
轻松地做到这一点。
首先,创建MediaPlayer
类的实例:
MediaPlayer mediaPlayer = new MediaPlayer();
然后,为此设置源文件,首先将音频文件放置在res/raw
目录的Project
文件夹中,然后使用以下代码:
mediaPlayer.setDataSource(context, Uri.parse("android.resource://{package name}/res/raw/{audio file name}");
然后使用以下代码播放该文件:
mediaPlayer.prepare();
mediaPlayer.start();
请记住,您必须将此代码放在try | catch
块中。
现在您的整个代码将是这样:
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"Get Ready Bus is Near",Toast.LENGTH_LONG).show();
// Initializing instance of Vibrator.
Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
// Initializing instance of MediaPlayer.
MediaPlayer mediaPlayer = new MediaPlayer();
// Starting Vibration
v.vibrate(2000);
try {
// Setting the source of audio file.
mediaPlayer.setDataSource(context, Uri.parse("android.resource://{package name}/res/raw/{audio file name}"); // Fill the information accordingly.
mediaPlayer.prepare();
// playing audio.
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
}