一个测试马达和听筒的activity

        工程模式中,测试马达功能和听筒是否正常也是测试项目的一部分。简单的测试可如下:

(1)使用的特定import

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Vibrator;

需要在XML中添加马达特定权限

(2)activity内容

	Vibrator mVibrator;
	AudioManager am;
	public MediaPlayer myPlayer1;
	private int mSystemVol_music = 0;   //保存当前music音量
	private int mSystemVol_voice = 0;   //保存当前voice音量
         onCreate函数

		mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
		am= (AudioManager) getSystemService(Context.AUDIO_SERVICE);
		myPlayer1 = new MediaPlayer();
		myPlayer1 = MediaPlayer.create(MainActivity.this, R.raw.masque);  //添加一个音频文件
		try{
			setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
			am.setMode(AudioManager.MODE_IN_CALL);   //当前activity的audio mode
						
			mSystemVol_music= am.getStreamVolume(AudioManager.STREAM_MUSIC);
			int vol_max_music = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);	
			am.setStreamVolume(AudioManager.STREAM_MUSIC, vol_max_music, 0);
			
			mSystemVol_voice = am.getStreamVolume(AudioManager.STREAM_VOICE_CALL);	
			int vol_max_voice = am.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL);	
			am.setStreamVolume(AudioManager.STREAM_VOICE_CALL, vol_max_voice, 0);
			
			if(myPlayer1.isPlaying()==true)
			{
				myPlayer1.reset();
			}
			myPlayer1.setLooping(true);
			myPlayer1.start();
		}catch (IllegalStateException e){
			e.printStackTrace();
		}
		
		mVibrator.vibrate(new long[]{100, 300, 150, 400}, 1);
        onDestroy函数
		myPlayer1.stop();
		
		am.setStreamVolume(AudioManager.STREAM_VOICE_CALL, mSystemVol_voice, 0);
		am.setStreamVolume(AudioManager.STREAM_MUSIC, mSystemVol_music, 0);   //恢复默认音量
		setVolumeControlStream(AudioManager.STREAM_MUSIC);			
		am.setMode(AudioManager.MODE_NORMAL);
		mVibrator.cancel();
		super.onDestroy();




你可能感兴趣的:(Android)