我正在开发我的第一个 android 应用程序,但在尝试实现 Vibrator 时遇到问题。我想要做的是让 AlertDialog 显示一条消息,并且因为用户当时可能实际上并没有运行该应用程序,所以播放警报并振动手机直到他们关闭警报。首先我让它在没有振动器的情况下工作得很好,然后当我实施振动器时,它停止了警报声,它不再显示 AlertDialog。我发现我可以通过在新线程中执行它来解决警报问题,但仍然没有 AlertDialog。因此,我也尝试将振动器移动到新线程,但这并没有解决我的问题。所以我目前的问题是,手机播放警报声并振动,但我告诉它显示的 AlertDialog 永远不会显示。我怎样才能让这三样东西同时工作?这是我的代码(删除了不相关的部分)...
public class AlarmDisplayActivity extends Activity {
private MediaPlayer media;
private PowerManager.WakeLock lock;
private AlertDialog alert;
private Vibrator vibrator;
private Thread vibrateThread;
@Override
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.alarmdisplay_screen);
PowerManager power = (PowerManager)getSystemService(Context.POWER_SERVICE);
lock = power.newWakeLock(PowerManager.FULL_WAKE_LOCK |
PowerManager.ACQUIRE_CAUSES_WAKEUP, "AlarmReceiverActivity");
alert = new AlertDialog.Builder(AlarmDisplayActivity.this).create();
vibrator = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
vibrateThread = new VibrateThread();
lock.acquire();
alert.setCancelable(false);
alert.setButton("OK", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
media.stop();
vibrateThread.interrupt();
lock.release();
}// Ends onClick
}// Ends setButton
startAlarm(this);
vibrateThread.start();
alert.show();
}// Ends onCreate
private void startAlarm(final Context context) {
new Thread() {
public void run() {
Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
if(uri == null) {
uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
if(uri == null)
uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
}// Ends if
media = new MediaPlayer();
try{
media.setDataSource(context, uri);
final AudioManager audioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
if(audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
media.setAudioStreamType(AudioManager.STREAM_ALARM);
media.setLooping(true);
media.prepare();
media.start();
}// Ends if
}// Ends try
catch(Exception e){}
}// Ends run method
}.start();
}// Ends startAlarm method
class VibrateThread extends Thread {
public VibrateThread() {
super();
}
public void run() {
try {
long[] vibPattern = new long[] {0L,100L,250L,1000L,250L,500L};
vibrator.vibrate(vibPattern, 2);
}// Ends try
catch (Exception e) {}
}// Ends run method
}// Ends VibrateThread class
}// Ends AlarmDisplayActivity