开发者

How to start an immediate alarm on Android

I'm trying to write a code that activates an alarm when something happens. I've thought on using the default alarm and fire it 开发者_Python百科when I consider it, but first: I don't know how to fire the alarm or handle it. Second: I don't know if there is an easiest way to fire an immediate alarm that sounds and tells the user a message.

For example:

if (true) Fire an audible alarm with a message to advise the user else Some other code

Thanks for your help.


AlarmManager:

public void startAlert() {
Intent intent = new Intent(this, MyBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
        this.getApplicationContext(), 234324243, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
        + (i * 1000), pendingIntent);
Toast.makeText(this, "Alarm set in " + i + " seconds",
        Toast.LENGTH_LONG).show();
}

BroadCastReceiver:

    public class MyBroadcastReceiver extends BroadcastReceiver {
    @Override
  public void onReceive(Context context, Intent intent) {
  Toast.makeText(context, "Don't panik but your time is up!!!!.",
        Toast.LENGTH_LONG).show();
// Vibrate the mobile phone
  Vibrator vibrator = (Vibrator)    

        context.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(2000);
}


 }


If your code is executing, and you just want to give an audio-visual signal to the user that he's done something wrong, then just play a sound, and show a Toast.

For the text message: http://developer.android.com/guide/topics/ui/notifiers/toasts.html

Toast toast = Toast.makeText(context, myMessage, Toast.LENGTH_LONG).show();

For the sound: http://developer.android.com/guide/topics/media/index.html

If you want a notification to go with it, then take a look at: http://developer.android.com/reference/android/app/NotificationManager.html

Here you can fire a notification by passing a Notification object:

Notification.Builder builder = new Notification.Builder(context);
builder.setSound(Uri.fromFile(yourFile));
builder.setTicker(yourMessage);
NotificationManager.notify(1,builder.getNotification());
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜