2012-03-16 4 views
0

Вот мой код. От того, где я нахожусь не в состоянии генерировать сигнал тревоги программно ..Генерация тревоги с уведомлением в android

Calendar cal = Calendar.getInstance(); 
    int id = (int) cal.getTimeInMillis(); 
    Intent myIntent = new Intent(this,MyScheduledReceiver.class); 
    myIntent.putExtra("taskTitle", taskTitle.getText().toString()); 
    myIntent.putExtra("taskDetails", taskDetails.getText().toString()); 

    cal.setTimeInMillis(System.currentTimeMillis()); 
    cal.set(year, mon, day,tp.getCurrentHour(),tp.getCurrentMinute()); 
    PendingIntent sender = PendingIntent.getBroadcast(getApplicationContext(), id, 
      myIntent,PendingIntent.FLAG_UPDATE_CURRENT| Intent.FILL_IN_DATA); 
      AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE); 
      am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender); 

я объявил в файле манифест

<receiver android:name=".MyScheduledReceiver"></receiver> 

An в вещательном приемнике.

NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); 
NotificationManager manger = (NotificationManager)  
context.getSystemService(Context.NOTIFICATION_SERVICE); 
Notification notification = new Notification(R.drawable.ic_launcher, "Combi Note", 
System.currentTimeMillis()); 
PendingIntent contentIntent = PendingIntent.getActivity(context, 
NOTIFICATION_ID, 
new Intent(context, MyScheduledReceiver.class), 0); 
     Bundle extras=intent.getExtras(); 
     String title=extras.getString("taskTitle"); 
    String note=extras.getString("taskDetails"); 
     notification.setLatestEventInfo(context, note, title, contentIntent); 
     notification.flags = Notification.FLAG_INSISTENT; 
     notification.defaults |= Notification.DEFAULT_SOUND; 
    manger.notify(NOTIFICATION_ID++, notification); 
+0

Я немного смущен - вы упомянули, что не можете генерировать сигнал тревоги, который я подразумеваю, что onReceive (...) вашего получателя никогда не вызывается? Это так? – Nick

+0

Хорошо, оставьте его, если я хочу передать уведомление, а не правильно, это правильный способ ... это своего рода напоминания. Я думаю, у меня есть моя точка зрения. Уведомление о какой-либо задаче, например, задание 17 марта 2012 года в 7:00 вечера –

+0

Я не вижу очевидных ошибок в вашем сигнальном коде, поэтому, скорее всего, это что-то еще, как время будильника, которое вы устанавливаете, не то, что вы ожидаете, или ваш приемник не делает что вы ожидаете и т. д. Для простоты я бы просто отображал сообщение тоста внутри onReceive вашего приемника (...). Я также прокомментирую ваш вызов cal.set (...) и измените ваш cal.setTimeInMillis на cal.setTimeInMillis (System.currentTimeMillis() + 5000); так что, когда вы запустите приложение, если вы не видите Toast msg, вы знаете, что он не стреляет. – Nick

ответ

0

У меня есть нечто подобное, и оно работает.

Первый привет объявить В ожидании:

Intent intent = new Intent(Global.a, EventAlarmReceiver.class); 
    intent.putExtra("title", ""+cd.title); 
    intent.putExtra("desc", ""+cd.description); 

    PendingIntent pendingIntent = PendingIntent.getBroadcast(
      Global.a.getApplicationContext(), (int) (cd.alarmTime), intent, PendingIntent.FLAG_CANCEL_CURRENT); 

    AlarmManager alarmManager = (AlarmManager) Global.a.getSystemService(Activity.ALARM_SERVICE); 
    alarmManager.set(AlarmManager.RTC, cd.alarmTime, pendingIntent); 

и в EventAlarmReceiver классе у меня есть:

NotificationManager notificationManager = (NotificationManager) context.getSystemService(Activity.NOTIFICATION_SERVICE); 

    String text = String.valueOf(intent1.getCharSequenceExtra("title")); 

    Notification notification = new Notification(R.id.icon, 
      text, System.getTimeInMillis()); 

    notification.vibrate = new long[]{100,250,300,330,390,420,500}; 

    // Hide the notification after its selected  
    notification.flags |= Notification.FLAG_AUTO_CANCEL; 

    Intent intent = new Intent(context, ShowEventActivity.class); 
    intent.putExtra("title", String.valueOf(intent1.getCharSequenceExtra("title"))); 
    intent.putExtra("desc", String.valueOf(intent1.getCharSequenceExtra("desc"))); 


    String text1 = String.valueOf(intent1.getCharSequenceExtra("desc")); 

    PendingIntent activity = PendingIntent.getActivity(context, (int) System.getTimeInMillis() , intent, PendingIntent.FLAG_CANCEL_CURRENT); 

    notification.setLatestEventInfo(context, text, text1, activity); 

    notificationManager.notify((int)System.getTimeInMillis(), notification); 

убедитесь, что в манифесте объявляется объявить пакет, в котором приемник является: например, в в моем случае класс EventAlarmReceiver представляет собой пакет com.app.name.notifications, поэтому в манифесте у меня есть:

<receiver android:name=".notifications.EventAlarmReceiver"></receiver> 
Смежные вопросы