2011-10-03 43 views
2

我正在嘗試編寫一個代碼,用於在出現問題時激活報警。我想過使用默認鬧鐘並在我考慮時觸發它,但首先:我不知道如何觸發鬧鐘或處理鬧鐘。第二:我不知道是否有最簡單的方法來觸發立即發出的警報,並告訴用戶一條消息。如何在Android上啓動即時報警

例如:

如果(真) 消防與消息的發出聲光報警,以提醒用戶 其他 其他一些代碼

感謝您的幫助。

+0

你的意思是在狀態欄(帶聲音)通報? –

+0

謝謝大家!那就是我一直在尋找的東西! :)不,我不希望它在狀態欄中,但現在很好!謝謝! – Sonhja

回答

1

如果您的代碼正在執行,並且您只是想給用戶一個視聽信號,表示他做錯了什麼,那麼只需播放聲音並顯示一個Toast即可。

對於短信:http://developer.android.com/guide/topics/ui/notifiers/toasts.html

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

對於聲音:http://developer.android.com/guide/topics/media/index.html

如果你想有一個通知去用它,然後看看:http://developer.android.com/reference/android/app/NotificationManager.html

在這裏,您可以通過通知對象發出通知:

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

這種方法非常完美,但是......如果我不希望吐司消失,直到我觸摸屏或任何開火事件,那麼該怎麼辦? – Sonhja

+1

好吧,吐司是一段時間內顯示的小文本消息。如果你想要更持久的東西,請使用對話框!它更加豪華,但給你更多的自由。 –

+0

好吧,我會這樣做的。謝謝! – Sonhja

3

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(); 
} 

廣播接收器:

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); 
} 


}