以下代碼做到:
1.系統(tǒng)震動
2.消息提示音
3.系統(tǒng)震動伴隨提示音
4.相關(guān)權(quán)限為Nomal Permission,運(yùn)行在6.0之上不需要動態(tài)申請權(quán)限
操作:
1.在Menifest.xml中添加權(quán)限:
//添加震動權(quán)限
<uses-permission android:name="android.permission.VIBRATE"/>
2.在res文件夾下創(chuàng)建raw文件夾(與layout同級),將下載的音頻文件放進(jìn)去,下面附上蘋果各種消息提示音下載鏈接地址:http://sc.chinaz.com/tag_yinxiao/iphone.html
3.將下列代碼考進(jìn)項(xiàng)目中;
import android.app.Service;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Vibrator;
import com.ebig.pharmacyalliance.R;
import java.io.IOException;
/**
* @author Is-Poson
* @time 2017/9/13 11:05
* @desc 提示音 + 手機(jī)震動管理類
*/
public class BeeAndVibrateManager {
private static boolean shouldPlayBeep = true;
/**
* @param context Context實(shí)例
* @param milliseconds 震動時(shí)長 , 單位毫秒
*/
public static void vibrate(Context context, long milliseconds) {
Vibrator vib = (Vibrator) context.getSystemService(Service.VIBRATOR_SERVICE);
vib.vibrate(milliseconds);
}
/**
* @param context Context實(shí)例
* @param pattern 自定義震動模式 。數(shù)組中數(shù)字的含義依次是[靜止時(shí)長仅偎,震動時(shí)長,靜止時(shí)長药有,震動時(shí)長。愤惰。。]單位是毫秒
* @param isRepeat true-> 反復(fù)震動扇单,false-> 只震動一次
*/
public static void vibrate(Context context, long[] pattern, boolean isRepeat) {
Vibrator vib = (Vibrator) context.getSystemService(Service.VIBRATOR_SERVICE);
vib.vibrate(pattern, isRepeat ? 1 : -1);
}
public static void playBee(final Context context, PlayerCompleteListener listener) {
AudioManager audioService = (AudioManager) context
.getSystemService(Context.AUDIO_SERVICE);
if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
shouldPlayBeep = false;//檢查當(dāng)前是否是靜音模式
}
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer player) {
player.seekTo(0);
}
});
AssetFileDescriptor file = context.getResources().openRawResourceFd(
R.raw.dingding);
try {
mediaPlayer.setDataSource(file.getFileDescriptor(),
file.getStartOffset(), file.getLength());
file.close();
mediaPlayer.setVolume(0, 1);
mediaPlayer.prepare();
} catch (IOException ioe) {
mediaPlayer = null;
}
if (shouldPlayBeep && mediaPlayer != null) {
mediaPlayer.start();
}
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mp.stop();
listener.onCompletion(mp);
}
});
}
public static void playBeeAndVibrate(final Context context, long milliseconds, PlayerCompleteListener listener) {
//震動
vibrate(context, milliseconds);
//提示音
playBee(context, listener);
}
//MediaPlayer播放完畢監(jiān)聽
public interface PlayerCompleteListener {
void onCompletion(MediaPlayer mp);
}
}