android 震动和提示音

简短记录下android震动和提示音编写代码,方便以后编写

首先震动需要权限:

<uses-permission android:name="android.permission.WRITE_SETTINGS" />

然后就直接使用

1 private Vibrator vibrator;//震动
2 private MediaPlayer mediaplayer;//提示音

这里就是开始震动和启动提示音

//震动
vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(3000l);
// 铃声(这里是先释放掉内存)
if(mediaplayer!=null){
    mediaplayer.stop();
    mediaplayer.release();
    mediaplayer = null;
}
mediaplayer = new MediaPlayer();
try {
    mediaplayer.setDataSource(UpLoadService.this, RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
    mediaplayer.prepare();
} catch (Exception e) {
    e.printStackTrace();
}
mediaplayer.start();

震动和提示音的取消方式

1 vibrator.cancel();
2 if(mediaplayer.isPlaying()){
3     mediaplayer.stop();
4 }

尽量考虑全面点释放掉内存

@Override
protected void onDestroy() {
    if(mediaplayer!=null){
        mediaplayer.stop();
        mediaplayer.release();
        mediaplayer = null;
    }
    super.onDestroy();
}
原文地址:https://www.cnblogs.com/bxfx111/p/4775688.html